blob_id stringlengths 40 40 | repo_name stringlengths 5 127 | path stringlengths 2 523 | length_bytes int64 22 3.06M | score float64 3.5 5.34 | int_score int64 4 5 | text stringlengths 22 3.06M |
|---|---|---|---|---|---|---|
e2ef440e9f140b93cb1adc8bf478baf2beae8fa3 | timmichanga13/python | /fundamentals/oop/demo/oop_notes.py | 1,389 | 4.25 | 4 | # Encapsulation is the idea that an instance of the class is responsible for its own data
# I have a bank account, teller verifies account info, makes withdrawal from acct
# I can't just reach over and take money from the drawer
# Inheritance allows us to pass attributes and methods from parents to children
# Vehicles are a class that can carry cargo and passengers
# we wouldn't create vehicles, but we would create classes that inherit from our vehicle class:
# wheeled vehicles with wheels, aquatic vehicle that floats, winged vehicle that flies, living vehicles like a horse
# all require fuel, but it's different for each subclass
# multiple inheritance - a class can inherit from multiple classes
# Polymorphism - many forms, classes that are similar can behave similarly
# can have x = 34, y = 'hello!', z = {'key_a': 2883, 'key_b': 'a word!'}
# can find the length of each; len(x), len(y), len(z)
# each gives us a length, but differs based on the type of info (number of items, number of letters)
# Abstraction: an extension of encapsulation, we can hide things that a class doesn't need to know about
# a class can use methods of another class without needing to know how they work
# we can drive a car, fill tank with gas, might not be able to change oil but can take it somewhere to get oil changed
# can't make a car out of raw materials, but still know how to drive it
|
523094f54d9bd067b8fd7164cf312c3ace1fd9d9 | timmichanga13/python | /fundamentals/oop/user_chaining/user.py | 1,338 | 3.6875 | 4 | # declare a class and give it a user
class User:
# declaring class attribute
bank_name = "First National Dojo"
def __init__(self, name, email_address, account_balance):
self.name = name
self.email = email_address
# the account balance is set to 0
self.account_balance = account_balance
def make_deposit(self, amount):
self.account_balance += amount
return self
def make_withdrawal(self, amount):
self.account_balance -= amount
return self
def display_user_balance(self):
print(f"User: {self.name}, Balance: ${self.account_balance}")
return self
def transfer_money(self, amount, transfer_user):
self.make_withdrawal(amount)
transfer_user.make_deposit(amount)
return self
user1 = User("Harold", 'harold@codingdojo.com', 40000)
user2 = User('Harriet', 'harriet@codingdojo.com', 99000)
user3 = User("Maude", 'maude@codingdojo.com', 23)
user1.make_deposit(500).make_deposit(7000).make_deposit(23).make_withdrawal(4000).display_user_balance()
user2.make_deposit(500000).make_deposit(3000).make_withdrawal(32).make_withdrawal(4000).display_user_balance()
user3.make_deposit(4800000000).make_withdrawal(500000).make_withdrawal(2500000).display_user_balance()
user1.transfer_money(500, user3).display_user_balance()
user3.display_user_balance() |
2616ca8a82f4341ceee1be609efa5c8648aa2f29 | Mikey-Simmons/Python_Stack | /python/fundamentals/for_loops_basic_1.py | 531 | 3.71875 | 4 | for num in range(151):
print(num)
for num in range(5,1001,5):
print(num)
for num in range(1,100,1):
if num % 5 == 0:
print("Coding")
if num % 10 == 0:
print("Coding Dojo")
else:
print(num)
sum = 0
for num in range(0,500000,1):
if num % 2 == 0:
continue
else:
sum = sum + num
print(sum)
for num in range(2018,0,-4):
print(num)
lowNum = 1
highNum = 100
mult = 20
for num in range(lowNum,highNum,1):
if num % 20 ==0:
print(num) |
25fa2b72832de7ec8c2734d043d854834ee0fd33 | notwhale/devops-school-3 | /Python/Homework/hw21/hw21.py | 1,825 | 4.03125 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Написать функцию-генератор, которая объединяет два отсортированных итератора.
Результирующий итератор должен содержать последовательность в которой содержаться все элементы из каждой коллекции, в упорядоченном виде.
list(merge((x for x in range(1,4)),(x for x in range(2,5)))) == [1,2,2,3,3,4]
"""
from itertools import count, islice
def merge(iter_a, iter_b, limiter=20):
"""
A generator which joins two sorted iterators.
"""
iter_a = islice(iter_a, 0, limiter)
iter_b = islice(iter_b, 0, limiter)
list_ab = []
while True:
try:
a = next(iter_a)
list_ab.append(a)
except StopIteration:
break
while True:
try:
b = next(iter_b)
list_ab.append(b)
except StopIteration:
break
list_ab.sort()
for x in list_ab:
yield x
if __name__ == "__main__":
print(list(merge((x for x in range(1, 4)), (x for x in range(2, 5)))))
# examples with count
print()
print(list(merge((x for x in range(1, 4)), count(1))))
print(list(merge(count(1), (x for x in range(2, 5)))))
print(list(merge(count(1), count(1))))
print(list(merge((x for x in range(1, 25)), (x for x in range(2, 25, 6)))))
#samples from unittest
print(list(merge((x for x in range(0)), (y for y in range(0)))))
print(list(merge((x for x in range(1,4)),(x for x in range(2,5)))))
print(list(merge((x for x in range(11, 25, 3) if not x), (x for x in range(13, 24, 2)))))
print(list(merge((a for a in range(20)), (b for b in range(10)))))
|
95eaa4c8b527c0ac22bbd95dcfc30dad1fc836ad | notwhale/devops-school-3 | /Python/Homework/hw09/problem6.py | 973 | 4.1875 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Решить несколько задач из projecteuler.net
Решения должны быть максимально лаконичными, и использовать list comprehensions.
problem6 - list comprehension : one line
problem9 - list comprehension : one line
problem40 - list comprehension
problem48 - list comprehension : one line
Sum square difference
Problem 6
The sum of the squares of the first ten natural numbers is, 1^2 + 2^2 + ... + 10^2 = 385
The square of the sum of the first ten natural numbers is, (1 + 2 + ... + 10)^2 = 3025
Hence the difference between the sum of the squares of the first ten natural numbers and the square of the sum is 3025 - 385 = 2640.
Find the difference between the sum of the squares of the first one hundred natural numbers and the square of the sum.
"""
print(sum([_ for _ in range(1, 101)]) ** 2 - sum(map(lambda x: x**2, [_ for _ in range(1, 101)])))
|
5c754ed426a79e09081690eadbbd540479faf987 | mariapacifico/CSE231 | /proj02.py | 5,361 | 4.03125 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Sep 11 20:49:43 2019
"""
#Car Rental Sales
#Show user what info they will need to put in
#Ask if they want to continue
#If they do, ask to put in information needed
#Print to show what was inputed and they're final price and milage
#Intro to what info customer will put in
print()
print("Welcome to car rentals.")
print()
print("At the prompts, please enter the following: ")
print("Customer's classification code (a character: BDW) ")
print("Number of days the vehicle was rented (int)")
print("Odometer reading at the start of the rental period (int)")
print("Odometer reading at the end of the rental period (int)")
print()
answer = input("Would you like to continue (Y/N)? ")
#if customer chooses to continue
while answer == 'Y':
classification = input("Customer code (BDW): ")
if not(classification == 'B' or classification == 'D'
or classification == 'W'): #if invalid code is put in
print("*** Invalid customer code. Try again. ***")
continue #loop until they put in the right code
print()
days_str = input ("Number of days: ")
days = int(days_str)
start_odometer_str = input("Odometer reading at the start: ")
start_odometer = int(start_odometer_str)
end_odometer_str = input("Odometer reading at the end: " )
end_odometer = int(end_odometer_str)
if classification == 'B': #budget
days_owed = days * 40 #$40 per day
if end_odometer < start_odometer: #if odometer resets during rental
end_odometer2 = end_odometer + 1000000
odometer = (end_odometer2 - start_odometer) / 10
else:
odometer = (end_odometer - start_odometer) / 10
#divide by 10 to get correct number of miles
odometer_owed = odometer * 0.25 #$0.25 per mile
amount = float(odometer_owed + days_owed)
#to show the decimal if amount is an int
amount = round(amount, 2) #round to hundredths
print() #show final results
print ("Customer summary:") #' ', for indentation
print (' ', "classification code:", classification)
print(' ', "rental period (days):", days)
print (' ', "odometer reading at start:", start_odometer)
print (' ', "odometer reading at end: ", end_odometer)
print(' ', "number of miles driven: ", odometer)
print (' ', "amount due: $", amount)
print()
answer = input("Would you like to continue (Y/N)? ")
print() #loop again
elif classification == 'D': #daily
days_owed = days * 60 #$60 per day
if end_odometer < start_odometer: #if odometer resets
end_odometer2 = end_odometer + 1000000
odometer = (end_odometer2 - start_odometer) / 10
else:
odometer = (end_odometer - start_odometer) / 10
if (odometer / days) <= 100: #average less then 100 miles a day
odometer_owed = 0
else: #average more then 100 mi per day
odometer_owed = ((odometer / days) - 100) * days * 0.25
amount = float(odometer_owed + days_owed )
amount = round(amount, 2) #round to hundredths
print() #print receipt
print ("Customer summary:")
print (' ', "classification code:", classification)
print(' ', "rental period (days):", days)
print (' ', "odometer reading at start:", start_odometer)
print (' ', "odometer reading at end: ", end_odometer)
print(' ', "number of miles driven: ", odometer)
print (' ', "amount due: $", amount)
print()
answer = input("Would you like to continue (Y/N)? ") #loop again
elif classification == 'W': #weekly
weeks = days / 7
if not(days % 7 == 0) : #round up if not divisible by 7
weeks = int(weeks)
weeks += 1
weeks_owed = weeks * 190 #190 a week
if end_odometer < start_odometer: #if odometer resets
end_odometer2 = end_odometer + 1000000
odometer = (end_odometer2 - start_odometer) / 10
else:
odometer = (end_odometer - start_odometer) / 10
if (odometer / weeks) <= 900: #less then 90 mi, no charge
odometer_owed = 0
elif 1500 > (odometer / weeks) > 900:
odometer_owed = 100 * weeks #$100 a week between 900 & 1500 mi
else:
odometer_owed1 = 200 * weeks #$200 a week over 1500
odometer_owed2 = ((odometer/ weeks) - 1500) * weeks * 0.25
#extra 0.25 for every mi over 1500 per week
odometer_owed = odometer_owed1 + odometer_owed2
amount = float(odometer_owed + weeks_owed)
amount = round(amount, 2) #round to hundredths
print ("Customer summary:") #print summary
print (' ', "classification code:", classification,)
print(' ', "rental period (days):", days)
print (' ', "odometer reading at start:", start_odometer)
print (' ', "odometer reading at end: ", end_odometer)
print(' ', "number of miles driven: ", odometer)
print (' ', "amount due: $", amount)
print()
answer = input("Would you like to continue (Y/N)? ") #loop
else:
print("Thank you for your loyalty.") #if customer said no
|
8fc4d6e7d2e0228911a8b3f768fd2acd62c7e1ba | NovaJuan/python-linkedlist | /controllers.py | 2,216 | 4.0625 | 4 | # Here we create the logic to handle all the list functionality
import csv
import platform
import sys
import os
from linkedlist import LinkedList
from data_type import User
users = LinkedList(User)
def clear_terminal():
system = platform.system()
if system == 'Windows':
os.system('cls')
elif system == 'Darwin' or system == 'Linux':
os.system('clear')
def load_data():
"Load data (if exists) from csv set put into the Linked list"
try:
with open('scraper/people.csv', 'r') as file:
reader = csv.DictReader(file)
for row in reader:
users.insert(name=row['Name'], age=row['Age'])
except FileNotFoundError:
pass
def setup():
clear_terminal()
print('\nWelcome to this Linked list test.')
print('You can create and manage your list of friends here.')
set_placeholder = input(
'\nWant to add some placeholder friends? Y or N: ')
if set_placeholder == 'Y' or set_placeholder == 'y':
print('\nSetting up data...')
load_data()
def add_user():
name = input('\nFriend\'s name: ')
age = input('Friend\'s age: ')
users.append(name=name, age=age)
print(f'\n{name} was added to your list.')
def list_all_users():
print('\nYour list of friends')
if len(users) == 0:
return print('No friends in your list.')
row = ''
for i in range(len(users)):
row = row + ('%3d.%-12s ' % (i + 1, users[i].name))
if (i + 1) % 3 == 0:
row = row + '\n'
print(row)
def get_one_user():
if len(users) == 0:
return
try:
index = int(input('\nEnter the index: '))
user = users[index - 1]
print(f'\nYour friend is called {user.name},')
print(f'and is {user.age} years old.')
except (IndexError, ValueError):
print('\nThat index is not in the list.')
def remove_user():
if len(users) == 0:
return
try:
index = int(input('\nEnter the index: '))
user = users[index - 1]
users.remove(index - 1)
print(f'\n{user.name} was removed.')
except (IndexError, ValueError):
print('\nThat index is not in the list.')
|
647852fbc2f57fd041f877af1e7759b6bb5098bf | leostein1234/leostein1234 | /bioinformatics/Matplotlib/random lineplot pyplot.py | 647 | 3.78125 | 4 | import random as r
from matplotlib import pyplot as plt
print(plt.style.available)
plt.style.use('fivethirtyeight')
list_x = [0]
list_y = [0]
for x in range(100):
list_x.append(r.randint(1, 100) - r.randint(1, 50))
list_y.append(1+list_y[x])
plt.plot(list_y, list_x, color = 'b', linestyle='--',label = 'first rand', linewidth = .9)
plt.xlabel('x label')
plt.ylabel('y label')
plt.title('random graph')
for x in range(100):
list_x[x] = (r.randint(1, 100))
list_y[x] = (1 + list_y[x])
print(list_y)
plt.plot(list_y, list_x, color = 'g', linestyle = '-',label='second rand', linewidth = .9)
plt.show()
|
2e7c08e518d29bbbcca0cd478c6de19411bdc3f4 | osyunya/pull-request-test | /Hello World.py | 323 | 3.75 | 4 | import numpy as np
print("Hello World")
for i in range(5):
print(i+1)
<<<<<<< HEAD
def count(a,b):
return a+b
print(count(5,3))
=======
a=np.randint(1,5)
if a%2==0:
print("even_number")
else:
print("odd_number")
>>>>>>> 661e5f764b6a1187272a5c8f5e12fde48b41fd37
print("request")
print("develop")
print("competition") |
9bc2dabf91883f8ba94d7699fbd661da410076da | Riyuzak2510/Cat-Dog-Image-recognition-system | /cnn.py | 2,039 | 3.625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Tue Dec 12 22:55:27 2017
@author: lenovo
"""
#Convolutional Neural Networks
#since we are using data which is already managed very well and we dont need to work out on splitting the training and testing sets.
#working on building the cnn will be a good idea and this will be our 1st part of our program.
#Part-1 building the cnn
#importing the required libraries
from keras.models import Sequential
from keras.layers import Convolution2D
from keras.layers import MaxPooling2D
from keras.layers import Flatten
from keras.layers import Dense
#initialising the CNN as a sequence of layers
classifier = Sequential()
#Adding the Layers
#Convolution -> Max Pooling -> Flattening -> Full Connection
#Step-1 -> Convolution
classifier.add(Convolution2D(32, 3, 3, input_shape = (64,64,3), activation = 'relu'))
#Step-2 -> Max Pooling
classifier.add(MaxPooling2D(pool_size = (2,2)))
#Step-3 -> Flattening
classifier.add(Flatten())
#step-4 -> Full Connection
#output nodes here can be decided on the basis of input nodes and output nodes as an average
classifier.add(Dense(output_dim = 128, activation = 'relu'))
classifier.add(Dense(output_dim = 1, activation = 'sigmoid'))
#Compiling the Model
classifier.compile(optimizer = 'adam', loss = 'binary_crossentropy', metrics = ['accuracy'])
#fitting the Model
from keras.preprocessing.image import ImageDataGenerator
train_datagen = ImageDataGenerator(
rescale=1./255,
shear_range=0.2,
zoom_range=0.2,
horizontal_flip=True)
test_datagen = ImageDataGenerator(rescale=1./255)
training_set = train_datagen.flow_from_directory( 'dataset/training_set', target_size=(64, 64), batch_size=32,class_mode='binary')
test_set = test_datagen.flow_from_directory(
'dataset/test_set',
target_size=(64, 64),
batch_size=32,
class_mode='binary')
classifier.fit_generator(
training_set,
steps_per_epoch=8000,
epochs=25,
validation_data=test_set,
validation_steps=2000)
|
216821c580ff5d5f8b1968afb3f9635b7178389a | MIKI90/python_The_Hard_way_examples | /ex15.py | 240 | 3.828125 | 4 | from sys import argv
script, filename = argv
txt = open(filename)
print "Here's your file %r:" % filename
print txt.read()
print"Type the filename again: "
file_again= raw_input("> ")
txt_again= open(file_again)
print txt_again.read()
|
2e164e0e08c86171d4543a6d431c3b02896ce900 | hemdai/Robot-Battle-Game-With-Python | /robot.py | 1,548 | 3.78125 | 4 | from setup import BLUE, WHITE, SQUARE_SIZE, GRAY, ROBOTS
import pygame
class Robot:
PADDING = 10
OUTLINE = 2
def __init__(self, row, col, color):
self.row = row
self.col = col
self.color = color
self.robot1 = False
self.robot2 = False
self.robot3 = True
self.x = 0
self.y = 0
self.calc_position()
def calc_position(self):
self.x = SQUARE_SIZE * self.col + SQUARE_SIZE//2
self.y = SQUARE_SIZE * self.row + SQUARE_SIZE//2
def make_robot1(self):
self.robot1 = True
def make_robot2(self):
self.robot2 = True
def make_robot3(self):
self.robot3 = True
def draw(self, win):
radius = SQUARE_SIZE//2 - self.PADDING
pygame.draw.circle(win, self.color, (self.x, self.y), radius + self.OUTLINE)
pygame.draw.circle(win, self.color, (self.x, self.y), radius)
if self.make_robot1:
win.blit(ROBOTS['robot1'], (self.x - ROBOTS['robot1'].get_width()//2, self.y-ROBOTS['robot1'].get_height()//2))
if self.make_robot2:
win.blit(ROBOTS['robot2'], (self.x - ROBOTS['robot2'].get_width()//2, self.y-ROBOTS['robot2'].get_height()//2))
if self.make_robot3:
win.blit(ROBOTS['robot3'], (self.x - ROBOTS['robot3'].get_width()//2, self.y-ROBOTS['robot3'].get_height()//2))
def move(self, row, col):
self.row = row
self.col = col
self.calc_position()
def __repr__(self):
return str(self.color)
|
7b268a8bc5ff03e6973649785a24e517b35238c9 | ducquang2/Python | /Basic_on_HackerRank/Finding_the_percentage.py | 617 | 3.78125 | 4 | # Import decimal
from decimal import Decimal
if __name__ == '__main__':
n = int(input())
student_marks = {}
for _ in range(n):
name, *line = input().split()
scores = list(map(float, line))
student_marks[name] = scores
querry_name = input()
# Extract the value into a list: query_scores
querry_scores = student_marks[querry_name]
# Sum the scores in the list: total_scores
total_scores = sum(querry_scores)
# Convert the floats to dicimals and average the scores: avg
avg = Decimal(total_scores/3)
# Print the mean of the scores, correct to two decimals
print(round(avg,2)) |
97d12c33b2d142eaf238ae867bf6324c08a02bf9 | lanvce/learn-Python-the-hard-way | /ex32.py | 1,033 | 4.46875 | 4 | the_count=[1,2,3,4,5]
fruits=['apples','oranges','pears','apricots']
change=[1,'pennies',2,'dimes',3,'quarters']
#this fruit kind of fora-loop goes through a list
for number in the_count:
print(f"this is count {number}")
#same as above
for fruit in fruits:
print(f"A fruit of type :{fruit}")
#also we can go through mixed lists too
#noticed we have to use {} since we don't know what's in it
for i in change:
print(f"I go {i}")
#we can built lists,first start with an emoty one
elements=[]
#then use the range function to da 0 to 5 counts
for i in range(0,6):
print(f"Adding {i} to the list.")
#append is a function that lists understand
elements.append(i)
#now we can print them out too
for i in range(1,100,10):
print(f"they are {i}")
elements.append(i)
elements.append('kugou')
elements.append('wangyiyun')
del elements[10]
print (elements)
print(len(elements))
#for i in elements:
# print(f"Elements was :{i}")
print(elements.count(1))
elements.reverse()
print (elements)
|
d51ea3e1714590cf9818e86d97507b217a30927f | lanvce/learn-Python-the-hard-way | /ex43_classes.py | 2,686 | 3.625 | 4 | from sys import exit
from random import randint
from textwrap import dedent
class Scene(object):
def enter(self):
print("This scene is not yet configured")
print("Subclass it and implement enter()")
exit(1)
class Engine(object):
def __init__(self,scene_map):
self.scene_map=scene_map
def play(self):
current_scene=self.scene_map.opening_scene(
last_scene=self.scene_map.next_scene('finished')
while current_file!=last_scene:
next_scene_name=current_scene.enter()
current_scene=self.scene_map.next_scene(next_scene_name)
current_scene.enter()
class Death(Scene):
quips=[
"You died. You kinda suck at this ."
"Your mom would be proud ...if she were smarter."
"Such a luser"
"I have a small puppy that's a better at this ."
"You're wrose than your Dad's jokes."
]
def enter(self):
print(Death.quips[randint(0,len(self.quips)-1)])
exit(1)
class CentralCorridor(Scene):
def enter(self):
print(dedent("""
The Gothons of planet Percal #25 have invaded your ship
and destroyed your entire craw.You are the last surviving
member and your last mission is to get the neutron
destruct bomb from the Weapons Armory ,put it in the
bridge ,and blow the ship up after getting into an escape pod.
You're running down the central corridor to the Weapons Armoy
when a Gothon jumps put,red scaly skin ,dark grimy teeth,and
evil clown costume flowing around his hate filled body.
He's blocking the door to Armory and about to pull a weapon to
blast you"""))
action=input(">")
if action=="shoot!":
print(dedent("""
Quick on the draw you yank out your blaster and fire it at
the Gothon.His clown costume is flowing and moving around his body
,which throws off your aim.Your blaster hits his costume but misses
him entirely.This competely ruins his brand new costume his mother
bought him,which makes him fly into an insane rage and blast you
repeatedly in the face until you are dead.Then he eats you.
"""))
return 'death'
elif action=="dodge!":
class LaserWeaponArmory(Scene):
def enter(self):
pass
class TheBridge(Scene):
def enter(self):
pass
class EscapePod(Scene):
def enter(self):
pass
class Map(object):
def __init__(self,start_scene):
pass
def next_scene(self,scene_name):
pass
def opening_scene(self):
pass
a_map=Map('central_corridor')
a_game=Engine('a_map')
a_game.play()
|
ce5457678e0742d76a9e7935a257cd1af6e05617 | RobertElias/PythonProjects | /GroceryList/main.py | 1,980 | 4.375 | 4 | #Grocery List App
import datetime
#create date time object and store current date/time
time = datetime.datetime.now()
month = str(time.month)
day = str(time.day)
hour = str(time.hour)
minute = str(time.minute)
foods = ["Meat", "Cheese"]
print("Welcome to the Grocery List App.")
print("Current Date and Time: " + month + "/" + day + "\t" + hour + ":" + minute)
print("You currently have " + foods[0] + " and " + foods[1] + " in your list.")
#Get user input
food = input("\nType of food to add to grocery list: ")
foods.append(food.title())
food = input("\nType of food to add to grocery list: ")
foods.append(food.title())
food = input("\nType of food to add to grocery list: ")
foods.append(food.title())
#Print and sort the list
print("Here is your grocery list: ")
print(foods)
foods.sort()
print("Here is you grocery list sorted: ")
print(foods)
#Shopping for your list
print("\nSimulating Grocery Shopping...")
print("\nCurrent grocery list: " + str(len(foods)) + " items")
print(foods)
buy_food = input("What food did you just buy: ").title()
foods.remove(buy_food)
print("Removing " + buy_food + " from the list...")
print("\nSimulating Grocery Shopping...")
print("\nCurrent grocery list: " + str(len(foods)) + " items")
print(foods)
buy_food = input("What food did you just buy: ").title()
foods.remove(buy_food)
print("Removing " + buy_food + " from the list...")
print("\nSimulating Grocery Shopping...")
print("\nCurrent grocery list: " + str(len(foods)) + " items")
print(foods)
buy_food = input("What food did you just buy: ").title()
foods.remove(buy_food)
print("Removing " + buy_food + " from the list...")
#The store is out of this item
print("\nCurrent grocery list: " + str(len(foods)) + " items")
print(foods)
no_item = foods.pop()
print("\nSorry, the store is out of " + no_item + ".")
new_food = input("What food would you like instead: ").title()
food.insert(0,new_food)
print("\nHere is what remains on your grocery list: ")
print(foods)
#New food
|
dae536759b45c9c3db4f98695e57aa4aeb51c88d | RobertElias/PythonProjects | /Multiplication_Exponentiation_App/main.py | 1,673 | 4.15625 | 4 | print("Welcome to the multiplication/exponentiation table app.")
print("What number would you like to work with?")
# Gather user input
name = input("\nHello, what is your name: ").title().strip()
num = float(input("What number would you like to work with: "))
message = name + ", Math is really cool!!!"
# Multiplication Table
print("\nMultiplication Table for " + str(num))
print("\n\t 1.0 * " + str(num) + " = " + str(round(1*num, 4)))
print("\t 2.0 * " + str(num) + " = " + str(round(2*num, 4)))
print("\t 3.0 * " + str(num) + " = " + str(round(3*num, 4)))
print("\t 4.0 * " + str(num) + " = " + str(round(4*num, 4)))
print("\t 5.0 * " + str(num) + " = " + str(round(5*num, 4)))
print("\t 6.0 * " + str(num) + " = " + str(round(6*num, 4)))
print("\t 7.0 * " + str(num) + " = " + str(round(7*num, 4)))
print("\t 8.0 * " + str(num) + " = " + str(round(8*num, 4)))
print("\t 9.0 * " + str(num) + " = " + str(round(9*num, 4)))
#Exponent Table
print("\nExponent Table for " + str(num))
print("\n\t " + str(num) + " ** 1 = " + str(round(num**1,4)))
print("\t " + str(num) + " ** 2 = " + str(round(num**2, 4)))
print("\t " + str(num) + " ** 3 = " + str(round(num**3, 4)))
print("\t " + str(num) + " ** 4 = " + str(round(num**4, 4)))
print("\t " + str(num) + " ** 5 = " + str(round(num**5, 4)))
print("\t " + str(num) + " ** 6 = " + str(round(num**6, 4)))
print("\t " + str(num) + " ** 7 = " + str(round(num**7, 4)))
print("\t " + str(num) + " ** 8 = " + str(round(num**8, 4)))
print("\t " + str(num) + " ** 9 = " + str(round(num**9, 4)))
#Math is cool
print("\n" + message)
print("\t" + message.lower())
print("\t\t" + message.title())
print("\t\t\t" + message.upper()) |
0cf8bac0a47bb1156eaaff40503bc1cdcadb50a1 | RobertElias/PythonProjects | /Arrays/main_1.py | 309 | 4.375 | 4 | #Write a Python program to create an array of 5 integers and display the array items.
from array import *
array_num = array('i', [1,3,5,7,9])
for i in array_num:
print("Loop through the array.",i)
print("Access first three items individually")
print(array_num[0])
print(array_num[1])
print(array_num[2])
|
83fb395b9fc573098d6fe9f258391a4eef07f0e9 | RobertElias/PythonProjects | /Favorite_Teacher/main.py | 2,539 | 4.46875 | 4 | print("Welcome to the Favorite Teachers Program")
fav_teachers = []
#Get user input
fav_teachers.append(input("Who is your first favorite teacher: ").title())
fav_teachers.append(input("Who is your second favorite teacher: ").title())
fav_teachers.append(input("Who is your third favorite teacher: ").title())
fav_teachers.append(input("Who is your fourth favorite teacher: ").title())
#Summary of list
print("\nYour favorite teachers ranked are: " + str(fav_teachers))
print("You favorite teachers alphabetically are: " + str(sorted(fav_teachers)))
print("You favorite teachers in reverse are: " + str(sorted(fav_teachers, reverse=True)))
print("\nYour top Two favorite teachers are: " + fav_teachers[0] + " and " + fav_teachers[1] + ".")
print("Your next two favorite teachers are: " + fav_teachers[2] + " and " + fav_teachers[3] + ".")
print("Your last favorite teachers is: " + fav_teachers[-1])
print("You have a total of: " + str(len(fav_teachers)) + " favorite teachers.")
#Insert a new favorite teacher
fav_teachers.insert(0, input("\nOops, " + fav_teachers[0] + " is no longer you first favorite teacher. Who is your new Favorite Teacher: ").title())
#Summary of list
print("\nYour favorite teachers ranked are: " + str(fav_teachers))
print("You favorite teachers alphabetically are: " + str(sorted(fav_teachers)))
print("You favorite teachers in reverse are: " +
str(sorted(fav_teachers, reverse=True)))
print("\nYour top Two favorite teachers are: " +
fav_teachers[0] + " and " + fav_teachers[1] + ".")
print("Your next two favorite teachers are: " +
fav_teachers[2] + " and " + fav_teachers[3] + ".")
print("Your last favorite teachers is: " + fav_teachers[-1])
print("You have a total of: " + str(len(fav_teachers)) + " favorite teachers.")
#Remove a specific teacher
fav_teachers.remove(input("\nYou decide you no longer like a teacher. Who do we remove form the list: ").title())
#Summary of list
print("\nYour favorite teachers ranked are: " + str(fav_teachers))
print("You favorite teachers alphabetically are: " + str(sorted(fav_teachers)))
print("You favorite teachers in reverse are: " +
str(sorted(fav_teachers, reverse=True)))
print("\nYour top Two favorite teachers are: " +
fav_teachers[0] + " and " + fav_teachers[1] + ".")
print("Your next two favorite teachers are: " +
fav_teachers[2] + " and " + fav_teachers[3] + ".")
print("Your last favorite teachers is: " + fav_teachers[-1])
print("You have a total of: " + str(len(fav_teachers)) + " favorite teachers.")
|
641f7c3be30c236e2fde95d35f59de323cf2643b | RobertElias/PythonProjects | /Arrays/main_7.py | 248 | 4.0625 | 4 | #7. Write a Python program to append items from inerrable to the end of the array.
from array import *
array_num = array('i',[1,3,5,7,9])
print("Original array: " +str(array_num))
array_num.extend(array_num)
print("Extended array: "+str(array_num)) |
6607e083228f819582c1b3adf51b92828287c196 | Nayiib/Programas-de-haskell-a-python | /sumar.py | 121 | 3.796875 | 4 | def division(a,b):
if a<b:
return 0
else:
return 1+division(a-b,b)
print(division(15,3))
|
aceb434b82b3764cd302950e702716604dd71c93 | samiksha-patil/Tic-Tac-Toe | /TicTacToe.py | 3,733 | 3.984375 | 4 | import random
import os
def display_board(board):
os.system('cls')
print('For Your Reference')
print("-------------")
print("| 1 | 2 | 3 |")
print("-------------")
print("| 4 | 5 | 6 |")
print("-------------")
print("| 7 | 8 | 9 |")
print("-------------")
print()
print(' -------------')
print(' | '+board[1]+' | '+board[2]+' | '+board[3]+ ' |')
print(' -------------')
print(' | '+board[4]+' | '+board[5]+' | '+board[6]+' |')
print(' -------------')
print(' | '+board[7]+' | '+board[8]+' | '+board[9]+' |')
print(' -------------')
def player_input():
markers=' '
print("player 1 : choose X or 0")
markers=input("player 1= ")
if markers=='X':
return('X','0')
else:
return('0','X')
def play_first():
flip=random.randint(0,1)
if flip==0:
return('player1')
else:
return('player2')
def player_choice(board):
position=int(input("enter the number where you want to place your marker= "))
if board[position]==' ':
return position
else:
while (board[position]!=' '):
print("you have entered the marker where marker is already placed ...please enter new position")
position=int(input("enter the number where you want to place your marker= "))
return position
def place_marker(board,marker,position):
board[position]=marker
def win_check(board,marker):
if((board[1]==board[2]==board[3]==marker)or(board[4]==board[5]==board[6]==marker)or(board[7]==board[8]==board[9]==marker)or(board[1]==board[4]==board[7]==marker)or(board[2]==board[5]==board[8]==marker)or(board[3]==board[6]==board[9]==marker)or(board[3]==board[5]==board[7]==marker)or(board[1]==board[5]==board[9]==marker)):
return(True)
else:
return(False)
def replay():
x=input(" PLAY AGAIN? yes or no:")
if(x=='yes'):
return(True)
else:
return(False)
def play_game():
print('Tic Tac Toe')
board=['#',' ',' ',' ',' ',' ',' ',' ',' ',' ']
display_board(board)
player1,player2=player_input()
print('player 2='+player2)
turn=play_first()
print("first chance:"+turn)
play_game=input("ready to play? yes or no:")
if(play_game=='yes'):
game_on=True
else:
game_on=False
while game_on :
if(turn=='player1'):
display_board(board)
position=player_choice(board)
place_marker(board,player1,position)
if(win_check(board,player1)):
display_board(board)
print("player1 won")
game_on=False
else:
c=0
for i in range(1,10):
if board[i]==' ':
c=c+1
if(c==0):
print("game tie")
game_on=False
else:
turn='player2'
if(turn=='player2'):
display_board(board)
position=player_choice(board)
place_marker(board,player2,position)
if(win_check(board,player2)):
display_board(board)
print("player2 won")
game_on=False
else:
c=0
for i in range(1,10):
if board[i]==' ':
c=c+1
if(c==0):
print("game tie")
game_on=False
else:
turn='player1'
play_game()
while (replay()):
play_game()
|
2fdaa0262999821ba9c56b768202d90c30ea48f0 | lmlongna/Programming-Paradigme-CSCE-3193 | /Assignment9/assignment9.py | 1,522 | 3.890625 | 4 | # Lambert Longnang
# Assignment9
# December, 01 2019
import sys
import operator
args = sys.argv
if len(args) != 3:
exit("Not enough arguments please pass 2 arguments")
storyFileName = args[1]
skipWordsFileName = args[2]
with open(storyFileName, 'r') as storyFile:
storyString = storyFile.read()
print('Story filename: ' + storyFileName)
with open(skipWordsFileName, 'r') as skipWordsFile:
skipWordsString = skipWordsFile.read()
skiplist = skipWordsString.split(',')
print('Skip word file name: ' + skipWordsFileName)
print('Skip words: ' + str(skiplist))
erasures = ['\n','\t','.','?','!',',',';',':','\'','\"']
for character in erasures:
storyString = storyString.replace(character, ' ')
skipWordsList = skipWordsString.split(',')
storyString = storyString.lower()
storySplitList = storyString.split()
storySplitList = [word for word in storySplitList if word not in skipWordsList]
storyString = ' '.join(storySplitList)
storyList = storyString.split(' ')
storyList = list(filter(lambda x: x != '', storyList))
PairCount = {}
for i in range(len(storyList) - 1):
if (storyList[i] + ' ' + storyList[i+1]) in PairCount:
PairCount[storyList[i] + ' ' + storyList[i + 1]] += 1
else:
PairCount[storyList[i] + ' ' + storyList[i + 1]] = 1
dctionaryCount = sorted(PairCount.items(), key=operator.itemgetter(1))
print("The five most frequently occurring word pairs are:")
for i in range(1, 6):
print(dctionaryCount[-i])
|
15c344a5337e339a895151575642f932d812b552 | jagadeesh-tolnut/GeeksforGeeks-must-do-coding-questions | /Linked_List/Finding middle element in a linked list.py | 512 | 3.609375 | 4 | # your task is to complete this function
'''
class node:
def __init__(data):
self.data = data
self.next = None
'''
# function should return index to the any valid peak element
def findMid(head):
temp = head
i=1
while temp:
temp = temp.next
i+=1
mid = (i/2)+1
tpoint = head
j=1
while j<mid:
element = tpoint.data
tpoint = tpoint.next
j+=1
return element
# Code here
# return the value stored in the middle node
|
f39a746ea3b200e62e80f3cce4fee4bc30db002b | JagDecoded/100DaysOfCode | /CodeFights/Intro/013-reverseParentheses.py | 313 | 3.53125 | 4 | def reverseParentheses(ary):
ary=list(ary)
while '(' in ary:
for i in range(len(ary)):
if ary[i]=='(':
head=i
elif ary[i]==')':
tail= i
break
ary[head:tail+1]= ary[tail-1:head:-1]
return ''.join (i for i in ary)
|
78289dc9692e19988b1966c19e5a05b5906ece7d | JagDecoded/100DaysOfCode | /CodeFights/Intro/028-alphabeticShift.py | 110 | 3.75 | 4 | def alphabeticShift(inputString):
return ''.join([chr(ord(i)+1) if i!='z' else 'a' for i in inputString])
|
39e63e39353b051896a07eb473ef407514b4df50 | JagDecoded/100DaysOfCode | /CodeFights/Intro/003-checkPalindrome.py | 144 | 3.828125 | 4 | #Given the string, check if it is a palindrome.
def checkPalindrome(inputString):
return True if inputString==inputString[::-1] else False
|
2dae568f69ab9c93d43fb38f7f5a776844bb5e3e | Isco170/Python_tutorial | /Lists/listComprehension.py | 723 | 4.84375 | 5 | # List Comprehension offers a shorter syntax when you want to create a new list based on the values of an existing list.
# Example: Based on a list of fruits, you want a new list, containing only the fruits with the letter "a" in the name
# Without list comprehension
# fruits = ["apple", "banana", "cherry", "kiwi", "mango"]
# newList = []
# for x in fruits:
# if "a" in x:
# newList.append(x)
# print(newList)
# With list comprehension
fruits = ["apple", "banana", "cherry", "kiwi", "mango"]
# newList = [ x for x in fruits if "a" in x]
# Only accept items that are not "apple"
# newList = [x.upper() for x in fruits if x != "apple"]
newList = ['Hello' for x in fruits if x != "apple"]
print(newList) |
3b34b3e68f3687a698ba6aa60bc368ab6c1799cf | Isco170/Python_tutorial | /excercises_folder/02_areaQuadrado.py | 158 | 3.90625 | 4 | lado = int(input("Digite a medida de um dos lados do quadrado: "))
# area = int(lado) ** int(lado)
area = lado**lado
print("Area do quadrado: " + str(area)) |
b1a1d9c0229e6ef91e67a7b12c4a5ff106996742 | Isco170/Python_tutorial | /Strings/escapeCharacters.py | 624 | 3.765625 | 4 | # Escape Character
# To insert characters that are illegal in a string, use an escape character.
# An escape character is a backslash \ followed by the character you want to insert.
# An example of an illegal character is a double quote inside a string that is surrounded by double quotes:
# You will get an error if you use double quotes inside a string that is surrounded by double quotes:
# txt = "We are the so-called "Vikings" from the north."
# txt = "We are the so-called \"Vikings\" from the north."
# txt2 = "It\'s alright"
# txt3 = "This will insert one \\ (backlash)."
# print(txt)
# print(txt2)
# print(txt3)
|
7ec680db4a57cf287609cc90c66f32258c244cfe | BarryPercy/XsandOs | /XsandOs.py | 3,422 | 3.59375 | 4 | ###First Milestone Project. Tic Tac Toe
import random
import sys
from os import system
from IPython.display import clear_output
def checkifboardisfull(boardstate):
counter = 0
for i in boardstate:
if i == 'X' or i=='O':
counter+=1
if counter==9:
print("The game has ended in a draw!")
sys.exit(0)
return True
else:
return False
def hasplayerwon(shape,boardstate):
playerhaswon=False
if boardstate[0]==shape and boardstate[1]==shape and boardstate[2]==shape:
playerhaswon=True
elif boardstate[3]==shape and boardstate[4]==shape and boardstate[5]==shape:
playerhaswon=True
elif boardstate[6]==shape and boardstate[7]==shape and boardstate[8]==shape:
playerhaswon=True
elif boardstate[0]==shape and boardstate[3]==shape and boardstate[6]==shape:
playerhaswon=True
elif boardstate[1]==shape and boardstate[4]==shape and boardstate[7]==shape:
playerhaswon=True
elif boardstate[2]==shape and boardstate[6]==shape and boardstate[8]==shape:
playerhaswon=True
elif boardstate[0]==shape and boardstate[4]==shape and boardstate[8]==shape:
playerhaswon=True
elif boardstate[2]==shape and boardstate[4]==shape and boardstate[6]==shape:
playerhaswon=True
return playerhaswon
def randomizestartingorder(name1='name1',name2='name2'):
goingfirst=random.randint(0,1)
if goingfirst==0:
print ("{} you are going first".format(name1))
else:
print ("{} you are going first".format(name2))
return(goingfirst)
def displayboard(boardstate):
print(' '+boardstate[0]+'|'+boardstate[1]+'|'+boardstate[2])
print('-------')
print(' '+boardstate[3]+'|'+boardstate[4]+'|'+boardstate[5])
print('-------')
print(' '+boardstate[6]+'|'+boardstate[7]+'|'+boardstate[8])
def taketurn(name,shape,boardstate):
print('{} please choose a square to place an {} in the range 1-9: '.format(name,shape), end = '')
movenotcorrect=True
while(movenotcorrect):
playerinput=int(input())
if playerinput not in range(1,10) or boardstate[playerinput-1] =='X' or boardstate[playerinput-1] =='O':
print('Invalid move, please enter a number between 1-9 that does not already contain an X or O: ', end = '')
else:
boardstate[playerinput-1] = shape
system('cls')
displayboard(boardstate)
break
return boardstate
def rungame():
print("Welcome to Tic Tac Toe!")
print("What are your Names?")
print("Player one: ", end = '')
player1name=input()
print("Player two: ", end = '')
player2name=input()
print("Great! Nice to meet you {} and {}. {} you will be Xs and {} you will be Os".format(player1name,player2name,player1name,player2name))
player1shape='X'
player2shape='O'
currentturn=randomizestartingorder(player1name,player2name)
currentboardstate=['1','2','3','4','5','6','7','8','9']
displayboard(currentboardstate)
gamenotover=True
while (gamenotover):
checkifboardisfull(currentboardstate)
if currentturn==0:
currentboardstate=taketurn(player1name,player1shape,currentboardstate)
if hasplayerwon(player1shape,currentboardstate):
break
currentturn=1
else:
currentboardstate=taketurn(player2name,player2shape,currentboardstate)
if hasplayerwon(player2shape,currentboardstate):
break
currentturn=0
if currentturn==0:
print('Congratulations {}! You have won!'.format(player1name))
else:
print('Congratulations {}! You have won!'.format(player2name))
rungame()
|
a584ecce006e31bdf07577c279005ac403745f4c | cccczl/testpy | /test10.py | 419 | 3.875 | 4 | #!/usr/bin/python
# -*- coding: UTF-8 -*-
for i in "python":
if i == 'h':
continue #条件满足后继续进行循环
print i
#for 循环中 int 会报错
var = 10
while var > 0:
var = var-1
if var == 5:
continue
print "当前变量", var
print "结束"
#for 数值使用范围
for i in range(10):
if i == 5:
continue
print "当前变量是" ,i
print "结束" |
d290da8a6a1c605135c04042a63f569b9f987c50 | cccczl/testpy | /test4.py | 238 | 3.9375 | 4 | #!/usr/bin/python
# -*- coding: UTF-8 -*-
count = 0
while count<5:
print count, " is less than 5 " # 比5小的数 加后面的话
count = count + 1
else:
print count, "is not less than 5" #如果比5大时,打印这段话 |
02caf0b38eff8ee25714962a07215de61cc8a05c | margocrawf/GeneFinder | /gene_finder.py | 6,851 | 3.890625 | 4 | # -*- coding: utf-8 -*-
"""
Given a dna strand (in this case salmonella) gene_finder finds protein sequences that could be genes
Function takes about 8 seconds with 1500 trials of longest_ORF_noncoding.
@author: Margaret Crawford
"""
import random
from amino_acids import aa, codons, aa_table # you may find these useful
from load import load_seq
def shuffle_string(s):
"""Shuffles the characters in the input string
NOTE: this is a helper function, you do not
have to modify this in any way """
return ''.join(random.sample(s, len(s)))
# YOU WILL START YOUR IMPLEMENTATION FROM HERE DOWN ###
# K
def get_complement(nucleotide):
""" Returns the complementary nucleotide
nucleotide: a nucleotide (A, C, G, or T) represented as a string
returns: the complementary nucleotide
>>> get_complement('A')
'T'
>>> get_complement('C')
'G'
>>> get_complement('W')
input not a nucleotide.
Edit: Used a dictionary for this instead of if/elif statements, and a try/except
to deal with the edge case of a non-nucleotide answer.
"""
nucDict = {'A':'T', 'T':'A', 'G':'C', 'C':'G'}
try:
return nucDict[nucleotide]
except KeyError:
print 'input not a nucleotide.'
return None
def get_reverse_complement(dna):
""" Computes the reverse complementary sequence of DNA for the specfied DNA
sequence
dna: a DNA sequence represented as a string
returns: the reverse complementary DNA sequence represented as a string
Edit: Used a string concatenation, not sure if its more efficient
but its pretty and readable.
>>> get_reverse_complement("ATGCCCGCTTT")
'AAAGCGGGCAT'
>>> get_reverse_complement("CCGCGTTCA")
'TGAACGCGG'
"""
l = [get_complement(char) for char in dna[::-1]]
return ''.join(l)
def rest_of_ORF(dna):
""" Takes a DNA sequence that is assumed to begin with a start
codon and returns the sequence up to but not including the
first in frame stop codon. If there is no in frame stop codon,
returns the whole string.
dna: a DNA sequence
returns: the open reading frame represented as a string
>>> rest_of_ORF("ATGTGAA")
'ATG'
>>> rest_of_ORF("ATGAGATAGG")
'ATGAGA'
"""
string = ''
for i in xrange(0, len(dna), 3):
codon = dna[i:i+3]
if codon == 'TAG' or codon =='TAA' or codon =='TGA':
return string
else:
string += codon
return string
def find_all_ORFs_oneframe(dna):
""" Finds all non-nested open reading frames in the given DNA
sequence and returns them as a list. This function should
only find ORFs that are in the default frame of the sequence
(i.e. they start on indices that are multiples of 3).
By non-nested we mean that if an ORF occurs entirely within
another ORF, it should not be included in the returned list of ORFs.
dna: a DNA sequence
returns: a list of non-nested ORFs
>>> find_all_ORFs_oneframe("ATGCATGAATGTAGATAGATGTGCCC")
['ATGCATGAATGTAGA', 'ATGTGCCC']
"""
ORFlist = []
i = 0
lend = len(dna)
while i < lend:
codon = dna[i:i+3]
if codon == 'ATG':
orf = rest_of_ORF(dna[i:])
ORFlist.append(orf)
i = i + len(orf)
else:
i = i+3
return ORFlist
def find_all_ORFs(dna):
""" Finds all non-nested open reading frames in the given DNA sequence in
all 3 possible frames and returns them as a list. By non-nested we
mean that if an ORF occurs entirely within another ORF and they are
both in the same frame, it should not be included in the returned list
of ORFs.
dna: a DNA sequence
returns: a list of non-nested ORFs
>>> find_all_ORFs("ATGCATGAATGTAG")
['ATGCATGAATGTAG', 'ATGAATGTAG', 'ATG']
"""
ORFs = find_all_ORFs_oneframe(dna) + find_all_ORFs_oneframe(dna[1:]) + find_all_ORFs_oneframe(dna[2:])
return ORFs
def find_all_ORFs_both_strands(dna):
""" Finds all non-nested open reading frames in the given DNA sequence on both
strands.
dna: a DNA sequence
returns: a list of non-nested ORFs
>>> find_all_ORFs_both_strands("ATGCGAATGTAGCATCAAA")
['ATGCGAATG', 'ATGCTACATTCGCAT']
"""
reverse_strand = get_reverse_complement(dna)
return find_all_ORFs(dna) + find_all_ORFs(reverse_strand)
def longest_ORF(dna):
""" Finds the longest ORF on both strands of the specified DNA and returns it
as a string
>>> longest_ORF("ATGCGAATGTAGCATCAAA")
'ATGCTACATTCGCAT'
"""
ORFs = find_all_ORFs_both_strands(dna)
longest = ''
for ORF in ORFs:
if len(ORF) > len(longest):
longest = ORF
return longest
def longest_ORF_noncoding(dna, num_trials):
""" Computes the maximum length of the longest ORF over num_trials shuffles
of the specfied DNA sequence
Edit: Saved length of longest string as a variable so it isn't
recalculated every time.
dna: a DNA sequence
num_trials: the number of random shuffles
returns: the maximum length longest ORF
"""
longest = ''
lenl = 0
for i in range(num_trials):
shuffle = shuffle_string(dna)
if len(longest_ORF(shuffle)) > lenl:
longest = longest_ORF(shuffle)
lenl = len(longest)
return len(longest)
def coding_strand_to_AA(dna):
""" Computes the Protein encoded by a sequence of DNA. This function
does not check for start and stop codons (it assumes that the input
DNA sequence represents an protein coding region).
dna: a DNA sequence represented as a string
returns: a string containing the sequence of amino acids encoded by the
the input DNA fragment
>>> coding_strand_to_AA("ATGCGA")
'MR'
>>> coding_strand_to_AA("ATGCCCGCTTT")
'MPA'
"""
list1 = get_codons(dna)
string = ''
for codon in list1:
try:
string = string + aa_table[codon]
except KeyError:
continue
return string
def gene_finder(dna):
""" Returns the amino acid sequences that are likely coded by the specified dna
dna: a DNA sequence
returns: a list of all amino acid sequences coded by the sequence dna.
"""
threshold = longest_ORF_noncoding(dna, 1500)
orfs = find_all_ORFs_both_strands(dna)
list1 = []
for orf in orfs:
if len(orf) > threshold:
list1.append(coding_strand_to_AA(orf))
return list1
if __name__ == "__main__":
from load import load_seq
dna = load_seq("./data/X73525.fa")
print gene_finder(dna)
import doctest
doctest.testmod() |
c19d0fb75a783587a2da882ce9a1eff7091c400a | IonutPopovici1992/Python | /Socratica/random_module_ex2.py | 211 | 3.734375 | 4 | # Generate random numbers from interval [3, 7)
import random
def random_function():
# Random, scale, shift, return...
return 4 * random.random() + 3
for i in range(10):
print(random_function())
|
a315863eeb4b603354fc7f681e053554a35582fc | IonutPopovici1992/Python | /LearnPython/if_statements.py | 276 | 4.25 | 4 | is_male = True
is_tall = True
if is_male and is_tall:
print("You are a tall male.")
elif is_male and not(is_tall):
print("You are a short male.")
elif not(is_male) and is_tall:
print("You are not a male, but you are tall.")
else:
print("You are not a male.")
|
3b8bd7bde6eeff8d4eacc3286e17cd2c1751ebba | IonutPopovici1992/Python | /Socratica/list_comprehension_3.py | 786 | 3.5625 | 4 | # List Comprehension
# Problem
# p_remainders = [x ** 2 % p for x in range(0, p)]
# len(p_remainders) = (p + 1) / 2
# Gauss
movies = ["Star Wars", "Gandhi", "Casablanca", "Shawshank Redemption", "Toy Story",
"Gone with the Wind", "Citizen Kane", "It's a Wonderful Life", "The Wizard of Oz", "Gattaca",
"Rear Window", "Ghostbusters", "To Kill A Mockingbird", "Good Will Hunting", "2001: A Space Odyssey",
"Raiders of the Lost Ark", "Groundhog Day", "Close Encounters of the Third Kind"]
# Without List Comprehension
gmovies = []
for title in movies:
if title.startswith("G"):
gmovies.append(title)
print(gmovies)
# With List Comprehension
print(80 * "-")
gmovies2 = [title for title in movies if title.startswith("G")]
print(gmovies2)
|
6a7bb24267b969c8ef619255e6b3d22c590b8daf | IonutPopovici1992/Python | /Socratica/classes.py | 754 | 3.875 | 4 | # Python Classes and Objects
class User:
pass
user1 = User()
# user1 is an "instance" of User
# user1 is an "object"
user1.first_name = "Dave"
user1.last_name = "Bowman"
print(user1.first_name)
print(user1.last_name)
print(80 * "-")
first_name = "Arthur"
last_name = "Clarke"
print(first_name, last_name)
print(80 * "-")
print(user1.first_name, user1.last_name)
print(80 * "-")
user2 = User()
user2.first_name = "Frank"
user2.last_name = "Poole"
print(first_name, last_name)
print(10 * "*")
print(user1.first_name, user1.last_name)
print(10 * "*")
print(user2.first_name, user2.last_name)
print(80 * "-")
user1.age = 37
user2.favorite_book = "2001: A Space Odyssey"
print(user1.age)
# print(user2.age)
print(user2.favorite_book)
|
feceb19dab475d964be829cab4843f43ca96268e | XCYZ/pythonlearn | /pythoncorlib/builtin-callable-example-1.py | 291 | 3.5625 | 4 | def dump(fun):
if callable(fun):
print fun,"is callable"
else:
print fun,"is not callable"
class A:
def method(self, value):
return value
class B(A):
def __call__(self, value):
return value
a = A()
b = B()
dump(a)
dump(b)
dump(A)
dump(B) |
d6b57183228bf76a1e3d1d78d3eed262c68c0b06 | UserPython123/python | /week10task1ab.py | 735 | 3.734375 | 4 | # -*- coding: utf-8 -*-
"""
Created on
@author:
"""
from student import student
def main():
Surname = input("Enter student's surname: ")
Firstname = input("Enter student's first name: ")
StuNo = input("Enter student number: ")
Course = input("Enter student's course: ")
stuObj = student(Surname,Firstname,StuNo, Course)
print("Initial details...",stuObj)
print("Change Surname...")
Surname = input("Enter new surname: ")
stuObj.set_Surname(Surname)
print("Change course...")
Course = input("Enter the name for new course: ")
stuObj.set_Course(Course)
print("Updated student details...",stuObj)
main()
|
a3d9c08704bc4387db208058be87aafac8a1eac7 | UserPython123/python | /week7task4.py | 312 | 3.859375 | 4 | # -*- coding: utf-8 -*-
"""
Created on
@author:
"""
shoppinglist = []
setFlag = 1
item = ""
while(setFlag != 0):
item = input("Enter the item in shopping list : ")
if item == "":
setFlag = 0
break;
else:
shoppinglist.append(item)
print(shoppinglist)
|
3f4261421609d3248060d7b9d12de47ad8bac76d | becomeuseless/WeUseless | /204_Count_Primes.py | 2,069 | 4.125 | 4 | '''
Count the number of prime numbers less than a non-negative number, n.
Example:
Input: 10
Output: 4
Explanation: There are 4 prime numbers less than 10, they are 2, 3, 5, 7.
'''
class Solution(object):
def countPrimes(self, n):
"""
:type n: int
:rtype: int
"""
#attemp 1: for every number smaller than n+1, check if it is a prime. To check if a number p is a prime, see if it #divisible by the numbers smaller than p.
#Time Complexity : O(n**2)
#Space Complexity : O(1)
'''
cnt = 0
for i in range(1,n):
if self.isPrime(i):
cnt += 1
return cnt
def isPrime(self, x):
if x == 1:
return False
for i in range(2,x):
if x%i == 0:
return False
return True
'''
#attemp 2:To check if a number is p is a prime, we dont need to divide it by all the numbers smaller than p. Actually only
#the numbers smaller than p**1/2 would be enough.
#Time Complexity : O(n**1.5)
#Space Complexity : O(1)
'''
cnt = 0
for i in range(1,n):
if self.isPrime(i):
cnt += 1
return cnt
def isPrime(self, x):
if x == 1:
return False
i = 2
while i <= x**0.5:
if x%i == 0:
return False
i += 1
return True
'''
#attemp 3:When check if a number is a prime number, we will know for sure the multiples of the number are not prime numbers.
#Thus we dont need to check the multiples.
#Time Complexity : O(loglogn)
#Space Complexity : O(n)
if n < 3:
return 0
isPrime = [True]*n
isPrime[0] = isPrime[1] = False
for i in range(int(n**0.5) + 1):
if not isPrime[i]:
continue
j = i*i
while j< n:
isPrime[j] = False
j += i
return sum(isPrime)
|
8edd49288e0835c3199760611ae138a555f92b63 | becomeuseless/WeUseless | /136_Single_Number.py | 919 | 3.953125 | 4 | '''
Given a non-empty array of integers, every element appears twice except for one. Find that single one.
Note:
Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory?
Example 1:
Input: [2,2,1]
Output: 1
Example 2:
Input: [4,1,2,1,2]
Output: 4
'''
class Solution(object):
def singleNumber(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
#Option 1 : use dictionary
#Time Complexity : O(n)
#Space Complexity : O(n)
#Option 2 : math (rabbit and duck in the same cage). One single line code
#Time Complexity : O(n)
#Space Complexity : O(n)
#return 2*sum(set(nums)) - sum(nums)
#Option 3 : Bit manipulation
#Time Complexity : O(n)
#Space Comlexity : O(1)
a = 0
for n in nums :
a ^= n
return a
|
bf5ae7c2e62b993181809a5a3aa7f8473c737012 | becomeuseless/WeUseless | /58_Length_of_Last_Word.py | 1,705 | 3.765625 | 4 | '''
Given a string s consists of upper/lower-case alphabets and empty space characters ' ', return the length of last word in the string.
If the last word does not exist, return 0.
Note: A word is defined as a character sequence consists of non-space characters only.
Example:
Input: "Hello World"
Output: 5
'''
class Solution(object):
def lengthOfLastWord(self, s):
"""
:type s: str
:rtype: int
test cases:
''
' '
'Hello '
'Hello'
' Hello World'
Time Complexity O(m) m = length of the last word
Space Complexity O(1)
"""
if not s :
return 0
length = switch = i = 0
while i < len(s) :
if switch == 0 and s[-1-i] != ' ' :
switch = 1
if switch == 1 and s[-1-i] == ' ' :
break
if switch == 1 :
length += 1
i += 1
return length
def lengthOfLastWord2(self, s: str) -> int:
count = 0
strLen = len(s)
metFirstAlph = False
for i in range(strLen):
each = s[strLen - 1 - i]
if each != ' ': #if each not a space
count += 1
metFirstAlph = True
else:
if metFirstAlph: #already a word
break
else:
continue
return count
def lengthOfLastWord3(self, s: str) -> int:
"[thing for thing in list_of_things if expression]"
last_word = [word for word in s.split(' ') if word]
if last_word:
return len(last_word[-1])
return 0
|
749f3e58f0dadf8a03dd8a38423c4e2f5d91fca1 | becomeuseless/WeUseless | /168_Excel_Sheet_Column_Title.py | 826 | 4 | 4 | '''
Given a positive integer, return its corresponding column title as appear in an Excel sheet.
For example:
1 -> A
2 -> B
3 -> C
...
26 -> Z
27 -> AA
28 -> AB
...
Example 1:
Input: 1
Output: "A"
Example 2:
Input: 28
Output: "AB"
Example 3:
Input: 701
Output: "ZY"
'''
class Solution(object):
def convertToTitle(self, n):
"""
:type n: int
:rtype: str
"""
#the math is treat this as 26-ary. The only thing needs to be careful is there is no Zero in this 26-ary.
#Time Complexity : O(logn) ???
#Space Complexity : O(1)
Capitals = [chr(x) for x in range(ord('A'), ord('Z')+1)]
output = ''
while n != 0:
output = Capitals[(n-1)%26] + output
n = (n - 1)//26
return output
|
e309820fa81af0c9ac2c89d90ae4f3d083801822 | becomeuseless/WeUseless | /206_Reverse_Linked_List.py | 1,218 | 4.03125 | 4 | '''
Reverse a singly linked list.
Example:
Input: 1->2->3->4->5->NULL
Output: 5->4->3->2->1->NULL
Follow up:
A linked list can be reversed either iteratively or recursively. Could you implement both?
'''
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def reverseList(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
'''
# NULL <- 1 <- 2 <- 3 4 -> 5
#Option 1: Recursive
#Time Complexity : O(n)
#Space Complexity : O(n)
if not head:
return head
return self.reverseNode(head, None)
def reverseNode(self, cur, pre):
if not cur:
return pre
nxt = cur.next
cur.next = pre
return self.reverseNode(nxt, cur)
'''
#Option 2: Iterative
#Time Complexity : O(n)
#Space Complexity : O(1)
if not head:
return head
cur = head
pre = None
while cur:
nxt = cur.next
cur.next = pre
pre = cur
cur = nxt
return pre
|
77665880cde79a8f833fb1a3f8dfe9c88368d970 | codexnubes/Coding_Dojo | /api_ajax/OOP/bike/bikechain.py | 1,120 | 4.25 | 4 | class Bike(object):
def __init__(self,price,max_speed):
self.price = price
self.max_speed = max_speed
self.miles = 0
def displayinfo(self):
print "Here are your bike stats:\n\
Price: ${}\n\
Max Speed: {}\n\
Miles Rode: {}".format(self.price, self.max_speed, self.miles)
def ride(self):
self.miles += 10
print "Riding..."
return self
def reverse(self):
if self.miles >= 5:
self.miles -= 5
print "Reversing..."
else:
print "Can't reverse!"
return self
bike1 = Bike(200, "10mph")
bike2 = Bike(1000, "50mph")
bike3 = Bike(500, "38mph")
bike1.displayinfo()
bike2.displayinfo()
bike3.displayinfo()
for i in range(0,3):
bike1.ride().ride().ride().reverse()
bike2.ride().reverse().reverse().reverse()
bike3.reverse().ride().reverse()
bike1.displayinfo()
bike2.displayinfo()
bike3.displayinfo()
for i in range(0,2):
bike1.reverse()
bike2.ride()
bike3.ride()
bike1.displayinfo()
bike2.displayinfo()
bike3.displayinfo()
|
5ebcc5307bcc5c5ddf117d32054a904f0a4258f7 | Phisit2001/Python | /1-2-3/Test 3 week2.py | 289 | 3.703125 | 4 | friend =["Jan","Cream","Phoo","Bam","Aom","Pee","Bas","Kong","Da","Jame"]
friend[9]="May"
friend[3]="boat"
friend.append("Dome")
friend.append("Poondang")
friend.insert(1,"Csa")
friend.insert(8,"Ped")
friend.remove("Aom")
friend.pop(3)
del friend[7]
friend.clear()
del friend
print(friend) |
617f11b1595c4aacfe6cdbb62bcae48ffa22d10d | NimaFathi/Bioinformatics-Rosalind-Textbook | /BookProblems/Chapter9/Generate the Last-to-First Mapping of a String(BA9K)/BA9K.py | 599 | 3.625 | 4 | def cyclicForm(pattern):
length = len(pattern)
form = [pattern]
def cyclicFormed(pattern , k ):
old = pattern
new = [0] * len(pattern)
for i in range(k):
new[0] = old[-1]
new[1:] = old[:-1]
old = new.copy()
return ''.join(new)
for i in range(1, length):
x = cyclicFormed(pattern,i)
form.append(x)
return form
if __name__ == '__main__':
text = input()
form = cyclicForm(text)
form.sort()
BWT = ''
for pattern in form:
BWT += pattern[len(pattern) - 1]
print(BWT) |
b709a3c1eee9ac609a5551f3d35cd32fc2b236d9 | NimaFathi/Bioinformatics-Rosalind-Textbook | /BookProblems/Chapter2/Implement MedianString (BA2B)/BA2B.py | 1,811 | 3.625 | 4 | import sys
def hamming(str1, str2):
HammingDistance = 0
for i in range(len(str2)):
if str1[i] != str2[i]:
HammingDistance += 1
return HammingDistance
def find_kmer(text, k):
kmer_collection = []
for i in range(len(text) - k):
kmer_collection.append(text[i:i + k])
return kmer_collection
def distance_between_pattern_and_strings(Pattern, Dna):
k = Pattern.__len__()
distance = 0
for dna_str in Dna:
HammingDistance = sys.maxsize
kmer_collection = find_kmer(dna_str, k)
for kmer in kmer_collection:
if HammingDistance > hamming(Pattern, kmer):
HammingDistance = hamming(Pattern, kmer)
distance += HammingDistance
return distance
def kmers_in_DNA(Dna, k):
possible_kmers = []
for dna_str in Dna:
for i in range(len(dna_str) - k):
possible_kmers.append(dna_str[i:i + k])
return set(possible_kmers)
def median_string(Dna, k):
distance = sys.maxsize
def kmersInDNA():
possible_kmers = []
for dna_str in Dna:
for i in range(len(dna_str) - k):
possible_kmers.append(dna_str[i:i + k])
return set(possible_kmers)
for Pattern in kmersInDNA():
if distance > distance_between_pattern_and_strings(Pattern, Dna):
distance = distance_between_pattern_and_strings(Pattern, Dna)
Median = Pattern
return Median
if __name__ == '__main__':
INPUT_FILE_NAME = 'rosalind_ba2b.txt'
OUTPUT_FILE_NAME = 'rosalind.txt'
file = open(INPUT_FILE_NAME, "r")
k = int(file.readline())
DNA = []
for line in file:
DNA.append(line.replace("\n", ""))
file.close()
file = open(OUTPUT_FILE_NAME, "w")
file.write(median_string(DNA, k))
|
95c64e20f324714ffd2b6892d1ac8ea3c1d328ed | furusawa057/dict_practice | /address.py | 614 | 3.625 | 4 | def main():
address_books = [
{'name': '東京タワー',
'location': '東京都港区芝公園4丁目2−8',
'zipcode': '1050011'},
{'name': 'スカイツリー',
'location': '東京都墨田区押上1丁目1−2',
'zipcode': '1310045'},
{'name': '通天閣タワー',
'location': '大阪府大阪市浪速区恵美須東1丁目18−6',
'zipcode': '5560002'},
]
for book in address_books:
print(f"{book['name']} 〒{book['zipcode']} {book['location']}")
if __name__ == '__main__':
main()
|
8f2b34c087cd792c481acff0c67e15a4420ab6b1 | Sanngeeta/function11 | /Question_2_perfect.py | 663 | 3.734375 | 4 | # def perfect(num):
# i=1
# sum=0
# while i<num:
# if num%i==0:
# sum=sum+i
# if num==sum:
# print("Perfact Number=",num)
# else:
# print("Not perfact number",num)
# i=i+1
# num1=int(input("enter your perfact number:"))
# perfect(num1)
def perfact(a):
i=1
sum=0
while i<=1000:
if a%i==0:
sum=sum+i
if a==sum:
print("Perfact",i)
else:
print("not perfact",i)
i=i+1
num1=int(input("enter the number"))
perfact(num1)
|
cfc22bb8b42a56025016a54555b7e7677968eaba | Sanngeeta/function11 | /new ques.py | 592 | 3.8125 | 4 |
# print ("NavGurukul")
# def say_hello():
# print ("Hello!")
# print ("Aap kaise ho?")
# say_hello()
# print ("Python is awesome")
# say_hello()
# print ("Hello…")
# say_hello()
# def message:
# print("hello python")
# message()
# def addtion(a,b):
# c=a+b
# print("Addtion",c)
# addtion(5,8)
def addtion(a,b):
c=a+b
print("Addtion",c)
x=int(input("enter the first no:"))
y=int(input("enter the second no:"))
addtion(y,x)
# a=50
# def show():
# x=10
# print(x)
# # print(a)
# print(a)
# show()
|
ffb1625654153f165e478e4fdc01a2b87636d6d7 | Sanngeeta/function11 | /Ques 3_sum_average.py | 546 | 4.03125 | 4 | # def sum_average(a,b,c):
# sum=a+b+c
# avg=sum/3
# print("sum is",sum)
# print("avg is",avg)
# num1=int(input("enter the number"))
# num2=int(input("enter the number"))
# num3=int(input("enter the number"))
# sum_average(num1,num2,num3)
# num=[1,2,3,[4,5],6,7,[8,9],1,2,3,[4,5]]
# i=0
# sum=0
# while i<len(num):
# if type(num[i])==type(num):
# j=0
# while j<len(num[i]):
# sum=sum+num[i][j]
# j=j+1
# else:
# sum=sum+num[i]
# i=i+1
# print(sum)
|
5efbe08e0c6bfcfa17af4e5903e0ab6ef9175785 | Sanngeeta/function11 | /pre-defind function_que.py | 770 | 4.03125 | 4 |
# def maximum():
# numbers = [3, 5, 7, 34, 2, 89, 2, 5]
# k=max(numbers)
# print(k)
# maximum()
# def addition():
# numbers = [1, 2, 3, 4, 5]
# k=sum(numbers)
# print(k)
# addition()
# def sort_list():
# unorder_list = [6, 8, 4, 3, 9, 56, 0, 34, 7, 15]
# unorder_list.sort()
# print(unorder_list)
# sort_list()
# def revers_list():
# number= [0, 3, 4, 6, 7, 8, 9, 15, 34, 56]
# number.reverse()
# # print(number)
# # revers_list()
# def reverse_list():
# list = ["Z", "A", "A", "B", "E", "M", "A", "R", "D"]
# list.reverse()
# print(list)
# reverse_list()
def min_list():
list = [8, 6, 4, 8, 4, 50, 2, 7]
k=min(list)
print(k)
min_list()
|
b96a0cdb70b59a8aae13e6824ec72958eef62c8f | erkghlerngm44/aniffinity | /aniffinity/aniffinity.py | 9,416 | 3.765625 | 4 | """aniffinity class."""
from . import calcs
from . import models
from . import resolver
from .exceptions import NoAffinityError
class Aniffinity:
"""
The Aniffinity class.
The purpose of this class is to store a "base user"'s scores, so
affinity with other users can be calculated easily.
For the username ``Josh`` on the service ``AniList``, the class can
be initialised as follows:
.. code-block:: python
from aniffinity import Aniffinity
af = Aniffinity("Josh", base_service="AniList")
There are multiple ways of specifying this information, and multiple
ways to initialise this class. For more info, read the documentation.
The instance, stored in ``af``, will now hold ``Josh``'s scores.
:meth:`.comparison` and :meth:`.calculate_affinity` can now be called,
to perform operations on this data.
"""
def __init__(self, base_user=None, base_service=None, round=10, **kws):
"""
Initialise an instance of ``Aniffinity``.
The information required to retrieve a users' score from a service
are their "username" and "service". For a list of "service"s,
read the documentation.
.. note::
As this applies to the "base" user, the params used are
``base_user`` and ``base_service`` respectively.
There are multiple ways of specifying the above information,
and multiple aliases for services that can be used as shorthand.
As docstrings are annoying to write, please refer to the
documentation for a list of these. For an example of the simplest
method to use, refer to the docstring for the :class:`Aniffinity`
class.
.. note::
To avoid dealing with dodgy globals, this class MAY be
initialised without the ``base_user`` argument, in the global
scope (if you wish), but :meth:`.init` MUST be called sometime
afterwards, with a ``base_user`` and ``base_service`` passed,
before affinity calculations take place.
Example (for the username ``Josh`` on the service ``AniList``):
.. code-block:: python
from aniffinity import Aniffinity
af = Aniffinity()
ma.init("Josh", base_service="AniList")
The class should then be good to go.
:param base_user: Base user
:type base_user: str or tuple
:param base_service: The service to use. If no value is specified
for this param, specify the service in the ``base_user`` param,
either as part of a url, or in a tuple
:type base_service: str or None
:param round: Decimal places to round affinity values to.
Specify ``False`` for no rounding
:type round: int or False
:param int wait_time: Wait time in seconds between paginated
requests (default: 2)
"""
self._base_username = None
self._base_service = None
self._base_scores = {}
self._round = round
self._wait_time = kws.get("wait_time", 2)
if base_user:
self.init(base_user, base_service)
def __repr__(self): # noqa: D105 # pragma: no cover
return "{}(base_user={!r}, base_service={!r}, round={!r})" \
.format(self.__class__.__name__, self._base_username,
self._base_service, self._round)
def init(self, base_user, base_service=None):
"""
Retrieve a "base user"'s list, and store it in :attr:`._base_scores`.
:param base_user: Base user
:type base_user: str or tuple
:param base_service: The service to use. If no value is specified
for this param, specify the service in the ``base_user`` param,
either as part of a url, or in a tuple
:type base_service: str or None
"""
# Figure out the service ourselves, instead of just passing this to
# `resolver.resolve_and_call` (and letting it handle everything),
# as we want to set `self._base_service`.
base_username, base_service = \
resolver.resolve_user(base_user, base_service)
base_scores = resolver.resolve_and_call(base_username, base_service,
wait_time=self._wait_time)
self._base_username = base_username
self._base_service = base_service
self._base_scores = base_scores
return self
def comparison(self, user, service=None):
"""
Get a comparison of scores between the "base user" and ``user``.
A Key-Value returned will consist of the following:
.. code-block:: none
{
"ANIME_ID": [BASE_USER_SCORE, OTHER_USER_SCORE],
...
}
Example:
.. code-block:: none
{
"30831": [3, 8],
"31240": [4, 7],
"32901": [1, 5],
...
}
.. note::
The ``ANIME_ID`` s will be the MyAnimeList anime ids. As annoying
as it is, cross-compatibility is needed between services to get
this module to work, and MAL ids are the best ones to use as other
APIs are able to specify it. If you wish to use the anime ids for
the service you specified, set the param
``<TO BE IMPLEMENTED>`` to ``<TO BE IMPLEMENTED>``.
:param user: The user to compare the base users' scores to.
:type user: str or tuple
:param service: The service to use. If no value is specified
for this param, specify the service in the ``user`` param,
either as part of a url, or in a tuple
:type service: str or None
:return: Mapping of ``id`` to ``score`` as described above
:rtype: dict
"""
# Check if there's actually a base user to compare scores with.
if not self._base_username or not self._base_scores:
raise Exception("No base user has been specified. Call the `init` "
"function to retrieve a base users' scores")
user_list = resolver.resolve_and_call(user, service,
wait_time=self._wait_time)
comparison_dict = {}
for key in (self._base_scores.keys() & user_list.keys()):
comparison_dict[key] = [self._base_scores[key], user_list[key]]
return comparison_dict
def calculate_affinity(self, user, service=None):
"""
Get the affinity between the "base user" and ``user``.
.. note::
The data returned will be a namedtuple, with the affinity
and shared rated anime. This can easily be separated
as follows:
.. code-block:: python
affinity, shared = af.calculate_affinity(...)
Alternatively, the following also works:
.. code-block:: python
affinity = af.calculate_affinity(...)
with the affinity and shared available as ``affinity.value`` and
``affinity.shared`` respectively.
.. note::
The final affinity value may or may not be rounded, depending on
the value of :attr:`._round`, set at class initialisation.
:param user: The user to calculate affinity with.
:type user: str or tuple
:param service: The service to use. If no value is specified
for this param, specify the service in the ``user`` param,
either as part of a url, or in a tuple
:type service: str or None
:return: (float affinity, int shared)
:rtype: tuple
"""
scores = self.comparison(user, service)
# Handle cases where the shared scores are <= 10 so
# affinity can not be accurately calculated.
if len(scores) <= 10:
# FIXME: Ok I can't think of a clean way of doing this, so this
# will have to do until I find a good implementation...
res_username, res_service = \
resolver.resolve_user(user, service)
raise NoAffinityError(
"Shared rated anime count between `{}:{}` and `{}:{}` is "
"less than eleven"
.format(self._base_service, self._base_username,
res_service, res_username)
)
# Sort multiple rows of scores into two arrays for calculations.
# E.G. [1,2], [3,4], [5,6] to [1,3,5], [2,4,6]
scores1, scores2 = zip(*scores.values())
try:
pearson = calcs.pearson(scores1, scores2)
except ZeroDivisionError:
# denominator is zero. catch this and raise our own exception.
# FIXME: Ditto
res_username, res_service = \
resolver.resolve_user(user, service)
raise NoAffinityError(
"Standard deviation of `{}:{}` or `{}:{}` scores is zero"
.format(self._base_service, self._base_username,
res_service, res_username)
)
pearson *= 100
if self._round is not False:
pearson = round(pearson, self._round)
return models.Affinity(value=pearson, shared=len(scores))
|
1c2228453d3381c88f22ecc15238a30bf15bf309 | easykatka04/ft_strtlist.py | /ft_sum_even_part_lst.py | 110 | 3.65625 | 4 | def ft_sum_even_part_lst(a):
b = 0
for i in a:
if i % 2 == 0:
b += i
return b
|
316dba09db34dce86510050f12e971d4123897d4 | Istiyaq123/NEA-2020-OCR | /new.py | 1,966 | 4.03125 | 4 | #initialiser
p1_score = 0
p2_score = 0
roll = 0
#import random
import random
#define login
def login():
usernameone = input('Enter Username One Username: ')
passwordone = input('Enter Username One Password: ')
usernametwo = input('Enter Username Two Username: ')
while usernameone == usernametwo:
usernametwo = input('Error ')
passwordtwo = input('Enter Username Two Password: ')
#define logup
def logup():
usernameone = input('Enter Username One: ')
passwordone = input('Enter Username One Password (Must be more than 3 letters): ')
while len(passwordone)<3:
passwordone = input('Error ')
usernametwo = input('Enter Username Two: ')
while usernameone == usernametwo:
usernametwo = input('That name has arealdy been signed up ')
passwordtwo = input('Enter Username Two Password (Must be more than 3 letters): ')
while len(passwordtwo)<3:
passwordtwo = input('Error ')
#define play()
def play():
number = random.randint(1,6)
p1_roll = input('Player One Roll. Yes or No').title()
if p1_roll == 'Yes':
print(number)
if number <6:
p1_score = p1_score + number
check = number %2
if check %2:
p1_score = p1_score + 10
else:
p1_score = p1_score - 5
elif number == 6:
p1_score = p1_score + number
number = random.randint(1,6)
print(number)
p1_score = p1_score + number
#Loging in or loging up
log = input('Do you have an account? ').title()
if log == 'Yes':
login()
elif log == 'Y':
login()
elif log == 'No':
logup()
elif log == 'N':
logup()
else:
print('Program has crashed.\nPlease try again.')
quit()
#Rules
print('\nEvery player has 5 rolls')
print('If you roll and even number ten points is added to your score\nIf you roll and odd number 5 points is subtracted from your score')
#Play
play() |
a49dc6026e472799e3f25ac9825e071c5e683c5f | arumugam-ramasamy/algorithms | /python/string/reversestrings.py~ | 290 | 4.03125 | 4 | import sys
def reverseString(str) :
strWords = str.split(' ')
strWords = strWords[-1::-1]
return ' '.join(strWords)
def main():
# print command line arguments
for arg in sys.argv[1:]:
print reverseString(arg)
if __name__ == "__main__":
main()
|
c8f387e774863d1e329bec07592d5191b66004cb | filipov73/SoftUni | /programming_basics_with_python/04.simple_operations_and_calculations-more_exercises/09.weather_forecast-part_2.py | 462 | 4.09375 | 4 | degree_celsius = float(input())
if (degree_celsius >= 26.00) and (degree_celsius <= 35.00):
print(f"Hot")
elif (degree_celsius >= 20.10) and (degree_celsius <= 25.90):
print(f"Warm")
elif (degree_celsius >= 15.00) and (degree_celsius <= 20.00):
print(f"Mild")
elif (degree_celsius >= 12.00) and (degree_celsius <= 14.90):
print(f"Cool")
elif (degree_celsius >= 5.00) and (degree_celsius <= 11.90):
print(f"Cold")
else:
print(f"unknown")
|
4faa0822e9a63a1efc25ef9de4c0310e3446550b | filipov73/SoftUni | /programming_basics_with_python/07.conditional_statements-more_exercises/02.sleepy_tom_cat.py | 437 | 3.59375 | 4 | vacation_days = int(input())
minutes_game = ((365 - vacation_days) * 63) + vacation_days * 127
diff = 30000 - minutes_game
if diff > 0:
down_min = 30000 - minutes_game
print(f"Tom sleeps well")
print(f"{down_min // 60} hours and {down_min % 60} minutes less for play")
else:
over_min = minutes_game - 30000
print(f"Tom will run away")
print(f"{over_min // 60} hours and {over_min % 60} minutes more for play")
|
db65eb95188f1b830449851e56c5cb77dcf39f6c | filipov73/SoftUni | /programming_basics_with_python/05.conditional_statements-lab/08.equal_words.py | 113 | 3.921875 | 4 | word_1 = input().lower()
word_2 = input().lower()
if word_1 == word_2:
print(f"yes")
else:
print(f"no")
|
1af7a9246aec6a2f769e3d1f8133afd24c9a706f | filipov73/SoftUni | /python_fundamentals_open_courses/02.functions_and_debugging/03.printing_triangle.py | 396 | 3.921875 | 4 | def print_col(col):
print(f"{col} ", end='')
def print_row():
print()
def draw(n):
for row in range(1, n+1):
for col in range(1, row+1):
print_col(col)
print_row()
for row in range(n, 1, -1):
for col in range(1, row):
print_col(col)
print_row()
def input_num():
number = int(input())
draw(number)
input_num() |
c236705806c8da54a7b163b8eb78de17c2bd718e | filipov73/SoftUni | /programming_basics_with_python/18.nested-loops-exercise/04.equal_sums_even_odd_position.py | 300 | 3.96875 | 4 | num_1 = int(input())
num_2 = int(input())
for n in range(num_1, num_2 + 1):
odd_sum = 0
even_sum = 0
number = n
for i in range(3):
even_sum += n % 10
n = n // 10
odd_sum += n % 10
n = n // 10
if odd_sum == even_sum:
print(number, end=' ')
|
aaa0e1bb681a7b3a1f57b12929a760898075c8b8 | filipov73/SoftUni | /programming_basics_with_python/17.nested-loops-lab/06.travelling.py | 312 | 4 | 4 | while True:
saved_money = 0
country = input()
if country == 'End':
break
budget = float(input())
while not saved_money >= budget:
money = float(input())
saved_money += money
if saved_money >= budget:
print(f'Going to {country}!')
break
|
46fc8fc6d3faba8aec5fdb615a2f07473f91d224 | filipov73/SoftUni | /programming_basics_with_python/15.for-loop-exercise/07.salary.py | 423 | 3.875 | 4 | num_open_site = int(input())
salary = int(input())
for _ in range(num_open_site):
name_site = input()
if name_site == 'Facebook':
fine = 150
elif name_site == 'Instagram':
fine = 100
elif name_site == 'Reddit':
fine = 50
else:
fine = 0
salary -= fine
if salary <= 0:
break
if salary <= 0:
print('You have lost your salary.')
else:
print(salary)
|
7224f796380c94eb143194b6d360f0b11ad12cd2 | filipov73/SoftUni | /programming_basics_with_python/11.while-loop-lab/04.max_number.py | 128 | 3.703125 | 4 | num = int(input())
num_list = []
while num:
n = int(input())
num_list.append(n)
num -= 1
print(f"{max(num_list)}")
|
5cd22038d4983ef2b9bfbec9770044f7398f5458 | filipov73/SoftUni | /programming_basics_with_python/03.simple_operations_and_calculations-exercise/04.tailoring_workshop.py | 332 | 3.609375 | 4 | num_tables = int(input())
length = float(input())
width = float(input())
usd = 1.85
cover_table_big = (width + 0.60) * (length + 0.60)
cover_table_small = length / 2 * length / 2
price_usd = (cover_table_big * num_tables * 7) + (cover_table_small * num_tables * 9)
print(f"{price_usd:.2f} USD")
print(f"{price_usd * usd:.2f} BGN")
|
b18bc8a3b4f75f276ef8d9d07f44856032611d0e | filipov73/SoftUni | /programming_basics_with_python/09.nested_conditional_statements-exercise/09.on_time_for_the_exam.py | 863 | 3.953125 | 4 | hour_exam = int(input())
minute_exam = int(input())
hour_arrival = int(input())
minute_arrival = int(input())
exam = (hour_exam * 60) + minute_exam
arrival = (hour_arrival * 60) + minute_arrival
diff_time = exam - arrival
if diff_time < 0:
print(f"Late")
if abs(diff_time) < 60:
print(f"{abs(diff_time)} minutes after the start")
else:
h = abs(diff_time) // 60
m = str(abs(diff_time) % 60).zfill(2)
print(f"{h}:{m} hours after the start")
elif (diff_time >= 0) and (diff_time <= 30):
print(f"On time")
if diff_time != 0:
print(f"{diff_time} minutes before the start")
else:
print(f"Early")
if diff_time < 60:
print(f"{diff_time} minutes before the start")
else:
h = diff_time // 60
m = str(diff_time % 60).zfill(2)
print(f"{h}:{m} hours before the start")
|
dfdff57d7bd0134065cf484807c57a14d7c82dad | filipov73/SoftUni | /programming_basics_with_python/12.while-loop-exercise/05.coins.py | 790 | 3.859375 | 4 | change = float(input())
change = round(change * 100)
coin = 200
total_coins = 0
while not change == 0:
coins = change // coin
change = change % coin
coin = coin // 2
if coin == 25:
coin = 20
total_coins += coins
print(total_coins)
# change = float(input())
#
# count = 0
# while change:
# if change >= 2:
# change -= 2
# elif change >= 1:
# change -= 1
# elif change >= 0.50:
# change -= 0.50
# elif change >= 0.20:
# change -= 0.20
# elif change >= 0.10:
# change -= 0.10
# elif change >= 0.05:
# change -= 0.05
# elif change >= 0.02:
# change -= 0.02
# elif change >= 0.01:
# change -= 0.01
# change = round(change, 2)
# count += 1
#
# print(f"{count}")
|
9ed84fe8900dc202c6d160ef193dc248c6926715 | filipov73/SoftUni | /programming_basics_with_python/14.for-loop-lab/07.vowels_sum.py | 650 | 3.921875 | 4 | word = input()
sum_vowels_letters = 0
vowels_letters_dict = {
'a': 1,
'e': 2,
'i': 3,
'o': 4,
'u': 5
}
for l in word:
if l in vowels_letters_dict.keys():
sum_vowels_letters += vowels_letters_dict[l]
print(sum_vowels_letters)
# word = input()
# sum_vowels_letters = 0
#
# for letter in word:
# if letter == 'a':
# sum_vowels_letters += 1
# elif letter == 'e':
# sum_vowels_letters += 2
# elif letter == 'i':
# sum_vowels_letters += 3
# elif letter == 'o':
# sum_vowels_letters += 4
# elif letter == 'u':
# sum_vowels_letters += 5
# print(sum_vowels_letters)
|
50b1be7a68dcce6b3c193a3390df2ff5931608c2 | MahoHarasawa/Maho | /uranai02.py | 5,773 | 4 | 4 | '''ソウルナンバー占い
合計が1桁になるまで足し、最終的に出た数がソウルナンバー
ぞろ目はそのまま'''
#8桁の生年月日を入力 1998/04/11生まれ⇒1,9,9,8,0,4,1,1
num1=int(input("1桁目⇒"))
while num1>=10 or num1<0:
print("0または1桁の正の数で入力してください")
print()
num1=int(input("1桁目⇒"))
num2=int(input("2桁目⇒"))
while num2>=10 or num2<0:
print("0または1桁の正の数で入力してください")
print()
num2=int(input("2桁目⇒"))
num3=int(input("3桁目⇒"))
while num3>=10 or num3<0:
print("0または1桁の正の数で入力してください")
print()
num3=int(input("3桁目⇒"))
num4=int(input("4桁目⇒"))
while num4>=10 or num4<0:
print("0または1桁の正の数で入力してください")
print()
num4=int(input("4桁目⇒"))
num5=int(input("5桁目⇒"))
while num5>=10 or num5<0:
print("0または1桁の正の数で入力してください")
print()
num5=int(input("5桁目⇒"))
num6=int(input("6桁目⇒"))
while num6>=10 or num6<0:
print("0または1桁の正の数で入力してください")
print()
num6=int(input("6桁目⇒"))
num7=int(input("7桁目⇒"))
while num7>=10 or num7<0:
print("0または1桁の正の数で入力してください")
print()
num7=int(input("7桁目⇒"))
num8=int(input("8桁目⇒"))
while num8>=10 or num8<0:
print("0または1桁の正の数で入力してください")
print()
num8=int(input("8桁目⇒"))
total1=num1 + num2 + num3 + num4 + num5 + num6 + num7 + num8
print()
print("合計: ",total1)
#ループ処理を使ってコードの無駄を省けないものか??
def get_total(x,y):
return x+y
#while文がありプログラム内で一度しか使わないため本来は不要
while total1 >= 10:
if total1 == 11:
print("あなたのソウルナンバーは11です!ソウルナンバー11の人を一言でいうと「直感で人が何考えているか、どういう人か察知してしまう鋭い感受性」の人です。")
break
elif total1 == 22:
print("あなたのソウルナンバーは22です!ソウルナンバー22の人を一言でいうと「しっかりと準備をしてから行動を行う、冷静な分析力と大胆な行動力」の人です。")
break
elif total1 == 33:
print("あなたのソウルナンバーは33です!ソウルナンバー33の人を一言でいうと「カリスマ性を持つ、人々を魅了する、スター中のスター」です。")
break
elif total1 == 44:
print("あなたのソウルナンバーは44です!ソウルナンバー44の人を一言でいうと「鋭い考えをもった、まさにキレ者。乗り越えられる重責を負う人」です。")
break
else:
num9=int(input("1桁目⇒"))
while num9>=10 or num9<0:
print("0または1桁の正の数で入力してください")
print()
num9=int(input("1桁目⇒"))
num10=int(input("2桁目⇒"))
while num10>=10 or num10<0:
print("0または1桁の正の数で入力してください")
print()
num10=int(input("2桁目⇒"))
total1=get_total(num9,num10)
print()
print("合計: ",total1)
else:
if total1 == 1:
print("あなたのソウルナンバーは1です!ソウルナンバー1の人を一言でいうと「才能も運もあるが、ハートが弱く小心者」です。")
elif total1 == 2:
print("あなたのソウルナンバーは2です!ソウルナンバー2の人を一言でいうと「頭がよく直感も働くが、短気で人からあれこれ言われたくない人」です。")
elif total1 == 3:
print("あなたのソウルナンバーは3です!ソウルナンバー3の人を一言でいうと「面倒見がよく芸術センスもあるがストレスをためやすい人」です。")
elif total1 == 4:
print("あなたのソウルナンバーは4です!ソウルナンバー4の人を一言でいうと「働き者でリーダーシップがあるがクールで人間味がない人」です。")
elif total1 == 5:
print("あなたのソウルナンバーは5です!ソウルナンバー5の人を一言でいうと「マイペースで安定志向だが恋愛下手な人」です。")
elif total1 == 6:
print("あなたのソウルナンバーは6です!ソウルナンバー6の人を一言でいうと「八方美人で愛情深いが裏切りを許さない人」です。")
elif total1 == 7:
print("あなたのソウルナンバーは7です!ソウルナンバー7の人を一言でいうと「お調子者でぱわふるだがデリケートで傷つきやすい人」です。")
elif total1 == 8:
print("あなたのソウルナンバーは8です!ソウルナンバー8の人を一言でいうと「こだわりが強く金運もあるがものの考え方が極端な人」です。")
elif total1 == 9:
print("あなたのソウルナンバーは9です!ソウルナンバー9の人を一言でいうと「記憶力がよく天才肌だが寂しがりや。一番浮気しやすい人」です。")
'''引用
http://soulnumber.me/
https://www.denwauranaichan.com/%E3%82%BD%E3%82%A6%E3%83%AB%E3%83%8A%E3%83%B3%E3%83%90%E3%83%BC/'''
|
54c0907406dce3b5e70762bef6da236633b2b344 | rjunghaas/Data-Mining-Examples | /Tensorflow/mb_sgd_classifier_basic.py | 2,358 | 3.625 | 4 | import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
from tensorflow.contrib.layers import fully_connected
# Load MNIST data
mnist = input_data.read_data_sets("/tmp/data")
# Constants for setting up neural network
n_inputs = 28*28 #MNIST
n_hidden1 = 30
n_hidden2 = 10
n_outputs = 10
# Learning rate for optimizer
learning_rate = 0.01
# Parameters for training
n_epochs = 10
batch_size = 50
# Create placeholders to hold X & y values in neural network
X = tf.placeholder(tf.float32, shape=(None, n_inputs), name="X")
y = tf.placeholder(tf.int32, shape=(None), name="y")
# Construction phase of neural network. Feed X into hidden1 into hidden2 and then output
with tf.name_scope("dnn"):
hidden1 = fully_connected(X, n_hidden1, scope="hidden1")
hidden2 = fully_connected(hidden1, n_hidden2, scope="hidden2")
logits = fully_connected(hidden2, n_outputs, scope="outputs", activation_fn=None)
# Use cross entropy for loss function
with tf.name_scope("loss"):
xentropy = tf.nn.sparse_softmax_cross_entropy_with_logits(labels=y, logits=logits)
loss = tf.reduce_mean(xentropy, name="loss")
# Use Gradient Descent to minimize cross entropy loss function
with tf.name_scope("train"):
optimizer = tf.train.GradientDescentOptimizer(learning_rate)
training_op = optimizer.minimize(loss)
# Accuracy used as evaluation measure to pass to optimizer
with tf.name_scope("eval"):
# Get highest logit as class our neural network predicts and form a tensor with boolean of whether prediction was correct
correct = tf.nn.in_top_k(logits, y, 1)
# Cast from boolean to float and compute average of correct tensor
accuracy = tf.reduce_mean(tf.cast(correct, tf.float32))
# Initialize variables and train neural network
with tf.Session() as sess:
init = tf.global_variables_initializer()
init.run()
for epoch in range(n_epochs):
# Grab mini-batch and pass to training network
for iteration in range(mnist.train.num_examples):
X_batch, y_batch = mnist.train.next_batch(batch_size)
sess.run(training_op, feed_dict={X: X_batch, y: y_batch})
# Test model against batch of test data for accuracy
acc_test = accuracy.eval(feed_dict={X: mnist.test.images, y: mnist.test.labels})
print("Epoch:", epoch, "Test accuracy:", acc_test)
|
51bb0eae8c6fd2a5b4c1fc554e95ec85dde18a57 | sandeepkapase/examples | /templates/python/threading.Thread.example.py | 450 | 3.78125 | 4 | import threading
import time
import sys
import random
class Hello(threading.Thread):
def __init__(self, min, max):
self.min, self.max = min, max
threading.Thread.__init__(self)
def run(self):
time.sleep(random.randint(1,3))
print "This is simple string"
tLst = []
for i in range(1,10):
tLst.append(Hello(0,i))
x = Hello(1,3)
x.start()
# This causes each thread to do its work
#h.start()
#k.start()
|
99193b9b585fd3cdb2829f13e7fac7786d388491 | ayush-09/Recursion | /IsArraySorted.py | 349 | 3.828125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sun Jul 18 14:04:51 2021
@author: Ayush
"""
def isSort(arr,n):
if n==0 or n==1:
return True
if arr[n-2]>arr[n-1]:
return False
sa = isSort(arr, n-1)
return sa
if __name__=="__main__":
n=int(input())
arr = list(input().split()[:n])
print(isSort(arr,n)) |
2730166b08043764a7e58c606495f8d55f881b76 | ayush-09/Recursion | /Class Assignment.py | 435 | 3.796875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sun Jul 18 19:15:26 2021
@author: Ayush
"""
def TeacherAlice(n):
if n==1 or n==2:
return n+1
else:
c1 = TeacherAlice(n-1)
c2 = TeacherAlice(n-2)
return c1+c2
if __name__=="__main__":
T = int(input())
for i in range(1,T+1):
n = int(input())
a = TeacherAlice(n)
print("#"+str(i)+" : "+ str(a))
|
23ed4ec62d29dc84254b51f079dcd36b8337249a | ayush-09/Recursion | /FactorialPop.py | 247 | 3.84375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sat Jul 17 13:47:33 2021
@author: Ayush
"""
def fact(n): # result while pop the stack
if n==0 or n==1:
return 1
return n * fact(n-1)
if __name__=="__main__":
print(fact(5)) |
9724d8fa3e0c33411618c6e3186200d67c0d2bb0 | DuoLife-QNL/Python_OJ | /character_statistics.py | 186 | 3.5625 | 4 | ch = input()
num = int(input())
l = []
for x in range(0, num):
s = input()
if (s.count(ch.upper()) + s.count(ch.lower()) >= 3):
l.insert(0, s)
for x in l:
print(x)
|
a408767d618b41216a8375c5d2d117346ada4b49 | DuoLife-QNL/Python_OJ | /hw_06/fraction.py | 2,641 | 3.859375 | 4 | class fraction(object):
def __init__(self, numerator, denominator):
#将分数正规化处理,即只在分子中出现负号
if(denominator < 0):
numerator = -numerator
denominator = - denominator
self.numerator = numerator
self.denominator = denominator
def add(self, a):
numerator = self.numerator * a.denominator + self.denominator * a.numerator
denominator = self.denominator * a.denominator
result = fraction(numerator, denominator)
return result.reduction()
def substract(self, a):
numerator = self.numerator * a.denominator - self.denominator * a.numerator
denominator = self.denominator * a.denominator
result = fraction(numerator, denominator)
return result.reduction()
def multiply(self, a):
numerator = self.numerator * a.numerator
denominator = self.denominator * a.denominator
result = fraction(numerator, denominator)
return result.reduction()
def division(self, a):
numerator = self.numerator * a.denominator
denominator = self.denominator * a.numerator
result = fraction(numerator, denominator)
return result.reduction()
#返回元组:约分后的分子,分母
def reduction(self):
#定义函数:求给定两数的最大公因数,其中x, y 是正数
def gcd(x, y):
if x > y:
smaller = y
else:
smaller = x
for i in range(1,smaller + 1):
if((x % i == 0) and (y % i == 0)):
result = i
return result
if(self.numerator < 0):
self.gcd = gcd(-self.numerator, self.denominator)
else:
self.gcd = gcd(self.numerator, self.denominator)
result = fraction(self.numerator // self.gcd, self.denominator // self.gcd)
return result
def get_value(self):
return self.numerator / self.denominator
def reciprocal(self):
return fraction(self.denominator, self.numerator)
def display(self):
print("{}/{}".format(self.numerator, self.denominator))
an, ad, bn, bd = map(int, input().split())
a = fraction(an, ad)
b = fraction(bn, bd)
a.reduction().display()
b.reduction().display()
result = a.add(b)
result.display()
result = a.substract(b)
result.display()
result = a.multiply(b)
result.display()
result = a.division(b)
result.display()
result = a.reciprocal().reduction()
result.display()
result = a.get_value()
print("{:.1f}".format(result)) |
a9c7e6fbb09f341a39589fcd2e4cb417179a0d79 | DuoLife-QNL/Python_OJ | /BMI.py | 243 | 4 | 4 | weight, height = map(float, input().split())
bmi = weight / (height ** 2)
if bmi < 18.5:
grade = 'A'
elif 18.5 <= bmi < 24:
grade = 'B'
elif 24 <= bmi < 28:
grade = 'C'
else:
grade = 'D'
print("{}:{:.2f}".format(grade, bmi)) |
256f3e7cfe573c0bed1c8e5e62c6df1226d9cc79 | AlenaGB/hw | /5.py | 465 | 4.125 | 4 | gain = float(input("What is the revenue this month? $"))
costs = float(input("What is the monthly expenses? $"))
if gain == costs:
print ("Not bad. No losses this month")
elif gain < costs:
print("It's time to think seriosly about cutting costs")
else:
print("Great! This month you have a profit")
staff = int(input("How many employees do you have?"))
profit = (gain - costs)/staff
print ("Your profit is ${:.2f} per person".format(profit)) |
8c15d523e93f4a23bb5e30d10f605350dac426a7 | buffik1989/untitled | /venv/list5_2.py | 1,531 | 3.859375 | 4 | # -*- coding: utf-8 -*-
'''
Задание 5.2
Запросить у пользователя ввод IP-сети в формате: 10.1.1.0/24
Затем вывести информацию о сети и маске в таком формате:
Network:
10 1 1 0
00001010 00000001 00000001 00000000
Mask:
/24
255 255 255 0
11111111 11111111 11111111 00000000
Проверить работу скрипта на разных комбинациях сеть/маска.
Ограничение: Все задания надо выполнять используя только пройденные темы.
'''
ip = input("Введите IP в формате: 10.1.1.0/24: ")
ip = ip.replace('.', ' ')
ip = ip.replace('/',' ')
ip = ip.split()
print("-" * 30)
print(f'''Network:\n{ip[0]:<8} {ip[1]:<8} {ip[2]:<8} {ip[3]:<8}''')
print(f'''{int(ip[0]):08b} {int(ip[1]):08b} {int(ip[2]):08b} {int(ip[3]):08b}''')
ip_int = int(ip[4])
#print(ip_int)
mask = str(("1" * ip_int) + "0" * (32 - ip_int))
#print(mask)
mask_bin0 = mask[0:8]
mask_bin1 = mask[8:16]
mask_bin2 = mask[16:24]
mask_bin3 = mask[24:32]
'''print(mask_bin0)
print(mask_bin1)
print(mask_bin2)
print(mask_bin3)'''
mask_int0 = int(mask_bin0, 2)
mask_int1 = int(mask_bin1, 2)
mask_int2 = int(mask_bin2, 2)
mask_int3 = int(mask_bin3, 2)
print(f'''Mask:\n/{ip[4]}''')
print(f'''{mask_int0:<8} {mask_int1:<8} {mask_int2:<8} {mask_int3:<8}''')
print(f'''{mask_bin0:<8} {mask_bin1:<8} {mask_bin2:<8} {mask_bin3:<8}''')
|
25e69bb7661ba76e71a42c2f924274d1d1107a31 | txemac/adventofcode2017 | /day02_2.py | 2,621 | 3.9375 | 4 | """
--- Part Two ---
"Great work; looks like we're on the right track after all. Here's a star for your effort." However, the program
seems a little worried. Can programs be worried?
"Based on what we're seeing, it looks like all the User wanted is some information about the evenly divisible values
in the spreadsheet. Unfortunately, none of us are equipped for that kind of calculation - most of us specialize in
bitwise operations."
It sounds like the goal is to find the only two numbers in each row where one evenly divides the other - that is,
where the result of the division operation is a whole number. They would like you to find those numbers on each
line, divide them, and add up each line's result.
For example, given the following spreadsheet:
5 9 2 8
9 4 7 3
3 8 6 5
In the first row, the only two numbers that evenly divide are 8 and 2; the result of this division is 4.
In the second row, the two numbers are 9 and 3; the result is 3.
In the third row, the result is 2.
In this example, the sum of the results would be 4 + 3 + 2 = 9.
What is the sum of each row's result in your puzzle input?
Although it hasn't changed, you can still get your puzzle input.
"""
input = """409 194 207 470 178 454 235 333 511 103 474 293 525 372 408 428
4321 2786 6683 3921 265 262 6206 2207 5712 214 6750 2742 777 5297 3764 167
3536 2675 1298 1069 175 145 706 2614 4067 4377 146 134 1930 3850 213 4151
2169 1050 3705 2424 614 3253 222 3287 3340 2637 61 216 2894 247 3905 214
99 797 80 683 789 92 736 318 103 153 749 631 626 367 110 805
2922 1764 178 3420 3246 3456 73 2668 3518 1524 273 2237 228 1826 182 2312
2304 2058 286 2258 1607 2492 2479 164 171 663 62 144 1195 116 2172 1839
114 170 82 50 158 111 165 164 106 70 178 87 182 101 86 168
121 110 51 122 92 146 13 53 34 112 44 160 56 93 82 98
4682 642 397 5208 136 4766 180 1673 1263 4757 4680 141 4430 1098 188 1451
158 712 1382 170 550 913 191 163 459 1197 1488 1337 900 1182 1018 337
4232 236 3835 3847 3881 4180 4204 4030 220 1268 251 4739 246 3798 1885 3244
169 1928 3305 167 194 3080 2164 192 3073 1848 426 2270 3572 3456 217 3269
140 1005 2063 3048 3742 3361 117 93 2695 1529 120 3480 3061 150 3383 190
489 732 57 75 61 797 266 593 324 475 733 737 113 68 267 141
3858 202 1141 3458 2507 239 199 4400 3713 3980 4170 227 3968 1688 4352 4168"""
rows = input.split("\n")
result = 0
for row in rows:
row = map(int, row.split())
for i, a in enumerate(row):
for j, b in enumerate(row[i+1:]):
if (i != j) and ((a % b == 0) or (b % a == 0)):
result += max([a,b]) / min([a,b])
break
print result
|
c619f9cd9cef317f81eab2637a5b454ef9c745e5 | TwiggyTwixter/Udemy-Project | /test.py | 309 | 4.15625 | 4 | print("This program calculates the average of two numbers")
firstNumber = float (input({"What will the first number be:"}))
secondNumber = float (input({"What will the second number be:"}))
print("The numbers are",firstNumber, "and",secondNumber)
print("The average is: ", (firstNumber + secondNumber )/ 2) |
2fff0de67010646a6e04b1b07da6f3be7cb31631 | MaxOvcharov/Python_for_DevOps | /sys_admin_utils_for_working_with_data/duplicate_file_finder.py | 963 | 3.640625 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys
from checksum_checker import create_checksum
from disk_path_scanner import RecursivePathWalker
from os.path import getsize
def find_duplicates(path='/tmp'):
"""
Recursive finder of all duplicate path
:param path: paht name
:return:
"""
dup = []
record = {}
d = RecursivePathWalker(path)
files = d.enumerate_path()
for file in files:
compound_key = (getsize(file), create_checksum(file))
if compound_key in record:
dup.append(file)
else:
record[compound_key] = file
return dup
if __name__ == '__main__':
if len(sys.argv) < 2:
print('Find duplicates for default dir -> /tmp')
duplicates = find_duplicates()
else:
duplicates = find_duplicates(sys.argv[1])
print('//-//-' * 9 + '\n')
for dup in enumerate(duplicates, start=1):
print('%s) Duplicate file: %s" % dup')
|
305ed394d7736235e0feec707e4d1f6072c7e955 | craigerrington/codeacademy | /coin_toss.py | 482 | 3.765625 | 4 | import random
def coin_toss(call,bet):
num = random.randint(1, 2)
if call == "Heads" and num == 1:
print("Heads, you won " + str(bet))
return bet
elif call == "Tails" and num == 2:
print("Tails, you won " + str(bet))
return bet
elif call == "Tails" and num == 1:
print("Heads, you lost " + str(-bet))
return -bet
else:
print("Tails, you lost " + str(-bet))
return -bet
#Test
coin_toss("Heads",25) |
d0a525d5b4decc9b9c3190ba84eb06e4c06ca4d8 | hariss0411/Python-Codes | /cheap.py | 678 | 3.734375 | 4 | for _ in range(int(input())):
string = input()
aCost = int(input())
bCost = int(input())
length = len(string)
ans = 0
for i in range(0,length//2):
if(string[i] == '/' or string[length - i - 1] == '/'):
if(i == length - i - 1):
ans += min(aCost, bCost)
elif(string[i] == string[length - i - 1]):
ans += 2*min(aCost, bCost)
elif(string[i] == 'b' or string[length - i - 1] == 'b'):
ans += bCost
else:
ans += aCost
elif(string[i] != string[length - i - 1]):
ans = -1
break
print(ans) |
a82800080a68aa44601c27075fe1d79d0fc49d22 | hariss0411/Python-Codes | /exception.py | 632 | 3.75 | 4 | class InvalidLengthException (Exception):
pass
class Mobile:
def __init__ (self,mob_no):
self.__mob_no=mob_no
def validate_mobile_number(self):
try:
if(len(self.__mob_no)!=10):
raise InvalidLengthException
else:
print("Valid Mobile Number")
except InvalidLengthException:
print("Invalid Length inside class")
print("Inside the class")
mob=Mobile("987665")
try:
mob.validate_mobile_number()
print("Outside the class")
except InvalidLengthException:
print("Invalid Length - outside class")
|
37899a51d576727fdbde970880245b40e7e5b7b4 | dusanvojnovic/tic-tac-toe | /tic_tac_toe.py | 2,430 | 4.125 | 4 | import os
board = [" ", " ", " ", " ", " ", " ", " ", " ", " ", " "]
def print_board(board):
print(board[7] + ' |' + board[8] + ' |' + board[9])
print("--------")
print(board[4] + ' |' + board[5] + ' |' + board[6])
print("--------")
print(board[1] + ' |' + board[2] + ' |' + board[3])
def game():
play = "X"
count = 0
global board
for i in range(10):
os.system('cls')
print ("Welcome to the TicTacToe! Use your num keypad(1-9) to play.")
print_board(board)
choice = input(f"Player {play} it's your turn to play: ")
move = int(choice)
if board[move] != " ":
print("That field is not empty, please try again.")
continue
else:
board[move] = play
count += 1
if count >= 5:
# checking rows
if board[7] == board[8] == board[9] == play or \
board[4] == board[5] == board[6] == play or \
board[1] == board[2] == board[3] == play:
os.system('cls')
print_board(board)
print (f"GAME OVER! The winner is {play} player!")
break
# checking columns
elif board[7] == board[4] == board[1] == play or \
board[8] == board[5] == board[2] == play or \
board[9] == board[6] == board[3] == play:
os.system('cls')
print_board(board)
print (f"GAME OVER! The winner is {play} player!")
break
# checking diagonals
elif board[1] == board[5] == board[9] == play or \
board[7] == board[5] == board[3] == play:
os.system('cls')
print_board(board)
print (f"GAME OVER! The winner is {play} player!")
break
if count == 9:
os.system('cls')
print_board(board)
print ("GAME OVER! It's tied!")
break
if play == "X":
play = "O"
else:
play = "X"
if input("Do you want to play again? (Y)es or (N)o: ").upper() == "Y":
board = [" ", " ", " ", " ", " ", " ", " ", " ", " ", " "]
os.system('cls')
game()
else:
os.system('cls')
print("Goodbye")
game()
|
46be93000434cb66a3ad8784c4c65d03d9f3eab6 | ravindrank10/list_python | /insertndelete.py | 199 | 4 | 4 |
x=[10,2,3,40,3]
print (x)
x.remove(3)
print("after removing 3" , x)
del x[3]
print("after deleting index3" , x)
x.append(5)
print("after appending 5" , x)
x.pop(1)
print("after popping index 1" ,x)
|
ba76e52f1664383fe838450358d8fdd961844e00 | Garage-at-EEE/Python-JavaScript | /Python_Syntax/garage - 4. class.py | 509 | 3.578125 | 4 | class Human:
# class Human(object):
def talk(self):
print('I can talk')
def walk(self):
print('I can walk')
def eat(self):
print('I can eat')
class Teacher():
def teach(self):
print('I can teach')
class Honored_Teacher(Teacher,Human):
def __init__(self,number):
self.number = number
def prize(self):
print(f"I received {self.number} prizes.")
Tom = Human()
Tom.talk()
Tom2 = Human()
Tom2.talk()
Bob = Teacher()
Bob.teach()
Kyle = Honored_Teacher(3)
Kyle.talk()
Kyle.teach()
Kyle.prize()
|
8ffb1206686eda2a633ccf79d07d1123627b3ba4 | zhaopengme/utilbox | /utilbox/mail_utils/mail_utils.py | 4,162 | 3.53125 | 4 | """
Utility module to handle sending of email messages.
"""
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
__author__ = "Jenson Jose"
__email__ = "jensonjose@live.in"
__status__ = "Alpha"
class MailUtils:
"""
Utility class containing methods for sending of email messages.
"""
def __init__(self, smtp_server, sender_email_id):
self.smtp_server = smtp_server
self.sender_email_id = sender_email_id
def send_mail_plain(self, recipient_email_id, email_subject, reply_to_email, message_string):
"""
Sends a plain-text email message.
:param recipient_email_id: The email ID of the recipient.
:param email_subject: The subject of the email.
:param reply_to_email: The 'reply-to' email address
:param message_string: The body of the email message.
:return: True, if message was sent successfully, False otherwise.
:rtype: bool
"""
# Create message container - the correct MIME type is multipart/alternative.
email_message = MIMEText(message_string)
email_message['Subject'] = email_subject
email_message['From'] = self.sender_email_id
email_message['To'] = reply_to_email
try:
# Send the message via local SMTP server.
smtp_session = smtplib.SMTP(self.smtp_server)
# sendmail function takes 3 arguments: sender's address, recipient's address
# and message to send - here it is sent as one string.
smtp_session.sendmail(self.sender_email_id, recipient_email_id, email_message.as_string())
smtp_session.quit()
return True
except Exception as ex:
import traceback
traceback.format_exc()
return False
@staticmethod
def _create_html_message(plain_message_string):
"""
Internal method to convert plain-text message string to HTML.
:param plain_message_string: The message string to converted to HTML.
:return: The HTML-based message string.
:rtype: str
"""
return "<html><head></head><body><p>" + str(plain_message_string) + "</p></body></html>"
def send_mail_html(self, recipient_email_id, email_subject, reply_to_email, message_string):
"""
Sends an HTML-format email message.
:param recipient_email_id: The email ID of the recipient.
:param email_subject: The subject of the email.
:param reply_to_email: The 'reply-to' email address
:param message_string: The body of the email message.
:return: True, if message was sent successfully, False otherwise.
:rtype: bool
"""
# Create message container - the correct MIME type is multipart/alternative.
email_message = MIMEMultipart('alternative')
email_message['Subject'] = email_subject
email_message['From'] = self.sender_email_id
email_message['To'] = reply_to_email
# Create the body of the message (a plain-text and an HTML version).
text = message_string
html = self._create_html_message(message_string)
# Record the MIME types of both parts - text/plain and text/html.
part1 = MIMEText(text, 'plain')
part2 = MIMEText(html, 'html')
# Attach parts into message container.
# According to RFC 2046, the last part of a multipart message, in this case
# the HTML message, is best and preferred.
email_message.attach(part1)
email_message.attach(part2)
try:
# Send the message via local SMTP server.
smtp_session = smtplib.SMTP(self.smtp_server)
# sendmail function takes 3 arguments: sender's address, recipient's address
# and message to send - here it is sent as one string.
smtp_session.sendmail(self.sender_email_id, recipient_email_id, email_message.as_string())
smtp_session.quit()
return True
except Exception as ex:
import traceback
traceback.format_exc()
return False
|
4529eef083b4a27e6b7bf0c36448deea1a213878 | TIPlatypus/RS-Codes | /Test.py | 11,933 | 3.515625 | 4 | inverseval = [[0,0]]*7
def gf_division(x,y):
if y == 0:
print("Division By Zero")
return null
return gf_multiplication(x,inverseval[y-1][1])
def create_inverse():
for i in range(0,7):
inverseval[i] = [gf_pow(2,i),gf_pow(2,7-i)]
#bubble
temp = [0,0]
for i in range(0,7):
for i in range(0,6):
if inverseval[i+1][0] < inverseval[i][0]:
temp = inverseval[i+1]
inverseval[i+1] = inverseval[i]
inverseval[i] = temp
def no_carry_multiplication(x,y):
z = 0
i = 0
while (y >> i) > 0:
if y & (1 << i):
z ^= x << i
i += 1
return z
def gf_multiplication(x, y):
mul = no_carry_multiplication(x,y)
return reduction(mul)
def gf_xor(a, b):
return a ^ b
def reduction(x):
a = 0b1011
xl = (x).bit_length()
al = (a).bit_length()
if xl < al:
return x
b = xl - al
a = a << b
xl2 = xl
while xl2 >= al:
x = x ^ a
xl2 = x.bit_length()
difference = xl - xl2
xl = xl2
a = a >> difference
return x
def gf_pow(a,n):
result = a
if n == 0:
return 1
for i in range(1,n):
result = gf_multiplication(result,a)
return result
create_inverse()
#that was the end of the basic gf operations
#next I define functions on polynomials whose coefficients are themselves elements of the galois field
print(inverseval)
#create the generator poly
def gen_polynomial(n, a):
result = [1]
for i in range(1,n+1):
result = poly_mul(result, [1, gf_pow(a,i)])
return result
def poly_scale(poly,r):
for i in range(0, len(poly)):
poly[i] = gf_multiplication(poly[i],r)
return poly
def poly_add(x,y):
length = max(len(x), len(y))
result = [0] * length
if len(x) > len(y):
for i in range(0, len(y)) :
result[i] = x[i] ^ y[i]
for i in range(len(y), len(result)):
result[i] = x[i]
else:
for i in range(0, len(x)):
result[i] = x[i] ^ y[i]
for i in range(len(x), len(result)):
result[i] = y[i]
return result
def poly_mul(x,y):
length = len(x) + len(y) - 1
result = [0] * length
for i in range(len(x)):
for j in range(len(y)):
result[i+j] = result[i+j] ^ gf_multiplication(x[i],y[j])
return result
def poly_eval(poly, a):
y = poly[0]
for i in range(1,len(poly)):
y = gf_xor(gf_multiplication(poly[i], gf_pow(a,i)),y)
return y
def poly_div(dividend,divisor):
msg_out = list(dividend)
for i in range(0, len(dividend) - (len(divisor) - 1)):
coef = msg_out[i]
if coef != 0:
for j in range(1, len(divisor)):
if divisor[j] != 0:
msg_out[i + j] ^= gf_multiplication(divisor[j], coef)
separator = -(len(divisor) - 1)
return msg_out[:separator], msg_out[separator:]
def encode(m, nsym):
gen = gen_polynomial(nsym, 2)
revm = [0]*len(m)
for i in range(len(m)):
revm[i] = m[len(m)-i-1]
m= revm
_, remainder = poly_div(m+([0] * (len(gen) - 1)), gen)
resulta = m + remainder
result = [0]*len(resulta)
for i in range(0,len(resulta)):
result[i] = resulta[len(resulta) -i -1]
return result
# decoding
# syndromes
def syndromes(m, nsym):
result = [0] * nsym
for i in range(0, nsym):
result[i] = poly_eval(m, gf_pow(2, i+1))
return result
def syn_encode(syndromes):
result = [0]
for i in range(0, nsym):
result += polyscale(syndromes[i], gf_pow(2, i))
return result
def berlekamp_massey(syndromes, codelen):
# initial m
m = -1
lambda_m = [1]
lm = 0
msublm = -1
dm = 1
#print("Initial M: M = ", m, "; \u039B(m) = ", lambda_m, "; lm = ", lm, "; m-lm = ", msublm, "; dm = ", dm)
#initial r
r = 0
lambda_r = [1]
lr = 0
rsublr = 0
dr = syndromes[0]
#print("Initial R: R = ", r, "; \u039B(r) = ", lambda_m, "; lr = ", lr, "; r-lr = ", rsublr, "; dr = ", dr)
#print("target R is: ", len(syndromes))
for i in range(1, len(syndromes)+1):
#print(" Now fnding \u039Br(", i, ")")
#print(" Current M: M = ", m, "; \u039B(m) = ", lambda_m, "; lm = ", lm, "; m-lm = ", msublm,"; dm = ", dm)
#print(" Current R: R = ", r, "; \u039B(r) = ", lambda_r, "; lr = ", lr, "; r-lr = ", rsublr, "; dr = ",dr)
if (dr == 0 ):
rp1 = r + 1
lrp1 = lr
rp1sublrp1 = rp1-lrp1
lambda_rp1 = lambda_r
drp1 = 0
if i != len(syndromes):
for j in range(0, lrp1 + 1):
drp1 = gf_xor(drp1, gf_multiplication(lambda_rp1[j], syndromes[rp1 - j]))
if (rsublr >= msublm) and (dr != 0):
m = r
lambda_m = lambda_r
lm = lr
msublm = rsublr
dm = dr
r = rp1
lambda_r = lambda_rp1
lr = lrp1
rsublr = rp1sublrp1
dr = drp1
#print(" R to find (dr==0): ", rp1, "; Degree (lrp1): ", lrp1, "; (R+1)-l(r+1): ", rp1sublrp1,"; \u039B(", rp1, "): ", lambda_rp1, )
else:
# l sub (r+1)
rp1 = r + 1
lrp1 = max(lr, lm + r - m)
# rsublr
rp1sublrp1 = rp1 - lrp1
# lambda_rp1
interim_poly = [0] * (r - m + 1)
if dm == 0:
return [0]
interim_poly[r - m] = gf_multiplication(dr, gf_division(1, dm))
#print(" dr: ", dr, "; 1/dm:", gf_division(1, dm), "; interimpoly[r-m]:", interim_poly[r-m])
lambda_rp1 = poly_add(lambda_r, poly_mul(interim_poly, lambda_m))
#print(" \u039B(", rp1, "): ", lambda_rp1, "; \u039B(", r, "): ", lambda_r, "; polymulterm: ",poly_mul(interim_poly, lambda_m))
#print(" R to find: ", rp1, "; Degree (lrp1): ", lrp1, "; (R+1)-l(r+1): ", rp1sublrp1, "; \u039B(", rp1, "): ", lambda_rp1, )
#drp1
if (i != len(syndromes)):
drp1 = 0
#print(i)
for j in range(0, lrp1 + 1):
#print(" j: ",j , "; \u039B(", rp1, "): ", lambda_rp1, "; syndromes: ", syndromes, "; rp1-j: ", rp1-j)
drp1 = gf_xor(drp1, gf_multiplication(lambda_rp1[j], syndromes[rp1 - j]))
#print(" drp1: ", drp1)
#print(" d(r+1) :", drp1, "; rp1 : ", rp1, "; lrp1: ", lrp1)
if (rsublr >= msublm):
m = r
lambda_m = lambda_r
lm = lr
msublm = rsublr
dm = dr
r = rp1
lambda_r = lambda_rp1
lr = lrp1
rsublr = rp1sublrp1
dr = drp1
#print("expected result = ", [1,3,2])
return lambda_rp1
def error_loc_roots(elocpoly):
errors = [0] * 7
xmin1 = [0] * (len(elocpoly) - 1)
j = 0
for i in range(0, 7):
x = poly_eval(elocpoly, gf_pow(2, i))
if x == 0:
xmin1[j] = gf_pow(2, i)
j += 1
if i == 0:
errors[0] = "X"
else:
errors[7 - i] = "X"
#print(i, " ", 7 - i, " ", gf_pow(2, i), " ", gf_pow(2, 6 - i))
#print(xmin1)
if xmin1[0] == 1:
tempxmin = xmin1[1:]
#print(tempxmin)
tempxmin.reverse()
#print(tempxmin)
xmin1[1:] = tempxmin
else:
xmin1.reverse()
return [errors,xmin1]
def forney(s_x, l_x, e_x, xm1):
#Omega(x)
O_x = poly_mul(s_x, l_x)
#print(xm1)
#print("s_x", s_x, " ,l_x", l_x)
#print("long O_x:", O_x)
if len(O_x) > 4:
O_x = O_x[0:4]
#print("short O_x", O_x)
#Lambda' x
lambda_dash_x = [0]*(len(l_x)-1)
for i in range(1, len(l_x)):
if i % 2 == 1:
lambda_dash_x[i-1] = l_x[i]
#print(l_x)
#print("l'_x: ", lambda_dash_x)
#print("x^-1: ", xm1)
#let e_x be a list of the locations of the errors rathen than what eloc roots currently produces.
result = [0]*7
#this should be correct but not most useful form?
j=0
for i in range(0,len(e_x)):
if e_x[i] != 0:
dividend = poly_eval(O_x, xm1[j])
#print(" O(x) = ", dividend)
divisor = poly_eval(lambda_dash_x, xm1[j])
#print(" L(x) = ", divisor)
result[i] = gf_division(dividend, divisor)
j+=1
return result
for i in range(0,8):
print(i, ", ", gf_pow(2,i))
print(gf_multiplication(2,5))
print(gen_polynomial(4,2))
msg = [6,6,1]
print(msg)
originalcode = encode(msg, 4)
code = [0]*len(originalcode)
for i in range(0,len(originalcode)):
code[i] = originalcode[i]
print(code)
f = 0
if True:
for i in range(0, 6):
for j in range(0, 8):
for k in range(i + 1, 7):
for l in range(0, 8):
if i != k:
#f += 1
#print("")
code[i] = j
code[k] = l
#print("i: ", i, " k: ", k)
#print("Corrupted code: ", code)
syndrome = syndromes(code, 4)
if syndrome == [0]*len(syndrome):
repaired = code
else:
#print("Syndromes: ", syndrome)
bmresult = berlekamp_massey(syndrome, len(code))
#print("Error locator poly: ", bmresult)
locations = error_loc_roots(bmresult)[0]
xmin1 = error_loc_roots(bmresult)[1]
#print("Error locations: ", locations)
error_poly = forney(syndrome, bmresult, locations, xmin1)
#print("Error polynomial: ", error_poly)
repaired = poly_add(error_poly, code)
if (repaired == [5,2,1,2,6,6,1]) :
print(f)
f += 1
print("Corrupted code: ", code)
print("i: ", i, " k: ", k)
print(" Error Poly: ", error_poly)
print("X^-1: ", xmin1)
print(" Repaired code: ", repaired)
print(" Check: ", poly_add(repaired, code))
print(" Decrypted message: ", repaired[4:])
print("")
print("--------------------")
print("")
#print("Check: ", poly_add(repaired, code))
#print("Decrypted message: ", repaired[4:])
#print("")
#print("--------------------")
#print("")
code[i] = originalcode[i]
code[k] = originalcode[k]
for k in range(0, 7):
for l in range(0, 7):
if i != k:
pass
if False:
for i in range(0, 7):
for j in range(0, 8):
code[i] = j
print("i: ", i, "j", j)
print("code", code)
syn = syndromes(code, 4)
print("syndromes", syn)
bmresult = berlekamp_massey(syn, 7)
print("elocpoly", bmresult)
print("errorlocations", error_loc_roots(bmresult))
code[i] = originalcode[i]
|
f02c3f4c39690f1027918f14318b60c1eea896b3 | MickeysClubhouse/environment | /Playground.py | 1,418 | 3.5 | 4 | import numpy
from constant import *
class Playground:
"""
class playground is a dimension_x* dimension_y grid
mark the objects' position
be shown by show() in trustGame.py
"""
dimension_x = 0
dimension_y = 0
grid = numpy.zeros((1, 1), dtype=int)
apples = []
def __init__(self, dimension_x, dimension_y, principal, agent, storage):
self.dimension_x = dimension_x
self.dimension_y = dimension_y
self.grid = numpy.zeros((dimension_x, dimension_y), dtype=int)
# set P and A
self.principal = principal
self.agent = agent
self.storage = storage
self.update()
def update(self):
for i in range(len(self.grid)):
for j in range(len(self.grid[0])):
self.grid[i][j] = 0
self.grid[self.principal.x][self.principal.y] = CELL_HUMAN
self.grid[self.agent.x][self.agent.y] = CELL_AGENT
self.grid[self.storage.x][self.storage.y] = CELL_APPLE_STORAGE_CLOSE
for apple in self.apples:
self.grid[apple[0], apple[1]] = CELL_APPLE
def get(self, row, col):
return self.grid[row][col]
def add(self, object, row, col):
# this part need to be altered when add other fruits
self.apples.append([row, col])
self.update()
def remove(self, row, col):
self.apples.remove([row, col])
self.update()
|
b17a130e74e8278fb7bdb3d78eec979bfce79053 | ManojAdwin/100DaysofCode-Python | /Day 2/Ex3_ Life_in_weeks.py | 175 | 3.71875 | 4 | age = input("What is your age? ")
newage=90-int(age)
days=newage*365
months=newage*12
weeks=newage*52
print(f"You have {days} days, {weeks} weeks, and {months} months left.")
|
7eea6b7d336695f0efcb41c84669ae2212ad625e | ManojAdwin/100DaysofCode-Python | /Day 8/Ex1_ Paint Area Calculator.py | 305 | 4.03125 | 4 | import math
def paint_calc(height, width, cover):
num = height*width
num_of_cans = math.ciel(num/cover)
print(f"You'll need {num_of_cans} of paint")
test_h = int(input("Height of wall: "))
test_w = int(input("Width of wall: "))
coverage = 5
paint_calc(height=test_h, width=test_w, cover=coverage)
|
f8e6189d09a4ed48198474edb863a09eb7971034 | ManojAdwin/100DaysofCode-Python | /Day 9/PROJECT_ Blind Auction.py | 1,007 | 3.8125 | 4 | logo = '''
___________
\ /
)_______(
|"""""""|_.-._,.---------.,_.-._
| | | | | | ''-.
| |_| |_ _| |_..-'
|_______| '-' `'---------'` '-'
)"""""""(
/_________\\
.-------------.
/_______________\\
'''
print(logo)
dicti = {}
is_true = False
while not is_true:
name = input("What is your name?: ")
bid = int(input("What's your bid?: $"))
dicti[name] = bid
ques = input("Are there any other bidders? Type 'yes' or 'no': ")
if ques == "no":
is_true = True
high = 0
for i in dicti:
value = dicti[i]
if value > high:
high = value
win = i
print(f"\n|----The winner is {win} of bid {high}----|")
else:
print("\n")
|
dbcd8ada19c245fa04913d1b114a25e2812a1d00 | varun-deokar/Cipher-Algorithms | /playfair_cypher.py | 4,120 | 3.609375 | 4 | def input_function():
message = input("Enter a message\n")
key = input("Enter a key\n")
message = message.lower()
message = message.replace('j', 'i')
key = key.lower()
return message, key
def playfair_key_generation(key):
key = key.replace("j", "i")
a = 'a'
row, col = (5, 5)
matrix_key = [[None] * col for i in range(row)]
i, j, c = 0, 0, -1
while i < 5:
j = 0
while j < 5:
c += 1
if c == len(key):
while a <= 'z':
if a == 'j':
j -= 1
else:
for b in matrix_key:
if a in b:
j -= 1
break
else:
matrix_key[i][j] = a
if j == 4:
i += 1
j = 0
else:
j += 1
a = chr(ord(a) + 1)
break
for k in range(i + 1):
if key[c] in matrix_key[k]:
j -= 1
break
else:
matrix_key[i][j] = key[c]
j += 1
if c == len(key):
break
i += 1
print("\n", matrix_key)
return matrix_key
def encrypt(text, key):
encrypted_text, message, var1, var2, count = "", text[0], text[0], "", 1
c, j = 1, 0
for i in range(1, len(text)):
if count % 2 == 0:
var1 = text[i]
message = message + text[i]
else:
var2 = text[i]
if var1 == var2:
message = message + 'x' + text[i]
else:
message = message + text[i]
count += 1
print(message)
if not len(message) % 2 == 0:
message = message + 'x'
for i in message:
c += 1
if c % 2 == 0:
temp = i
continue
else:
j = 0
while j < 5:
if i in key[j]:
row_loc_2 = j
col_loc_2 = key[j].index(i)
if temp in key[j]:
row_loc_1 = j
col_loc_1 = key[j].index(temp)
j += 1
if row_loc_1 == row_loc_2:
encrypted_text = encrypted_text + key[row_loc_1][(col_loc_1 + 1) % 5] + key[row_loc_2][(col_loc_2 + 1) % 5]
elif col_loc_1 == col_loc_2:
encrypted_text = encrypted_text + key[(row_loc_1 + 1) % 5][col_loc_1] + key[(row_loc_2 + 1) % 5][col_loc_2]
else:
encrypted_text = encrypted_text + key[row_loc_1][col_loc_2] + key[row_loc_2][col_loc_1]
print("\nEncrypted message is " + "\" " + encrypted_text + " \"")
return encrypted_text
def decrypt(message, key):
decrypted_text = ""
c, j = 1, 0
for i in message:
c += 1
if c % 2 == 0:
temp = i
continue
else:
j = 0
while j < 5:
if i in key[j]:
row_loc_2 = j
col_loc_2 = key[j].index(i)
if temp in key[j]:
row_loc_1 = j
col_loc_1 = key[j].index(temp)
j += 1
if row_loc_1 == row_loc_2:
decrypted_text = decrypted_text + key[row_loc_1][(col_loc_1 - 1) % 5] + key[row_loc_2][(col_loc_2 - 1) % 5]
elif col_loc_1 == col_loc_2:
decrypted_text = decrypted_text + key[(row_loc_1 - 1) % 5][col_loc_1] + key[(row_loc_2 - 1) % 5][col_loc_2]
else:
decrypted_text = decrypted_text + key[row_loc_1][col_loc_2] + key[row_loc_2][col_loc_1]
print("\nDecrypted message is " + "\" " + decrypted_text + " \"")
def main():
message, key = input_function()
matrix_key = playfair_key_generation(key)
encrypted_message = encrypt(message, matrix_key)
decrypt(encrypted_message, matrix_key)
if __name__ == "__main__":
main()
|
f4247987858702440a4739dc84674cec373d9384 | league-python-student/level0-module1-dencee | /_02_variables_practice/circle_area_calculator.py | 1,345 | 4.53125 | 5 | import turtle
from tkinter import messagebox, simpledialog, Tk
import math
import turtle
# Goal: Write a Python program that asks the user for the radius
# of a circle and displays the area of that circle.
# The formula for the area of a circle is πr^2.
# See example image in package to check your output.
if __name__ == '__main__':
window = Tk()
window.withdraw()
# Ask the user for the radius in pixels and store it in a variable
# simpledialog.askinteger()
num = simpledialog.askinteger("Enter a radius",None)
# Make a new turtle
Shivam = turtle.Turtle()
# Have your turtle draw a circle with the correct radius
# my_turtle.circle()
Shivam.circle(num)
# Call the turtle .penup() method
Shivam.penup()
# Move your turtle to a new x,y position using .goto()
Shivam.goto(100,80)
# Calculate the area of your circle and store it in a variable
# Hint, you can use math.pi
arnum = math.pi*num*num
# Write the area of your circle using the turtle .write() method
# my_turtle.write(arg="area = " + str(area), move=True, align='left', font=('Arial',8,'normal'))
Shivam.write(arg="area = " + str(arnum), move=True, align='left', font=('Arial',8,'normal'))
# Hide your turtle
Shivam.hideturtle()
# Call turtle.done()
turtle.done() |
d79a211d4907bff6ee5c10473c71eaf021057729 | PaulKitonyi/Python-Practise-Programs | /testing_functions/odd_even.py | 94 | 3.796875 | 4 | def even_odd(n):
if n%2 == 0:
return True
return False
# print(even_odd(2))
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.