blob_id stringlengths 40 40 | repo_name stringlengths 5 119 | path stringlengths 2 424 | length_bytes int64 36 888k | score float64 3.5 5.22 | int_score int64 4 5 | text stringlengths 27 888k |
|---|---|---|---|---|---|---|
4d6463478ed3d8fa7b7d3dbe7e0136db48efed0f | hatamleh12/htu-ictc5-webapps-using-python | /W2/S1/CA04-solutions/problem7.py | 443 | 4.34375 | 4 | # Create a function `sum_or_max(my_list)`, given a list, if the length of the list is even return the sum of the list. If the length is odd, return the maximum value in that list.
# sum_or_max(my_list)
def sum_or_max(my_list):
if len(my_list) % 2 == 0:
return sum(my_list)
return max(my_list)
# Call sum_or_max(my_list)
print(sum_or_max([1, 2, 3, 4, 5]))
print(sum_or_max([1, 2, 3, 4, 5, 6]))
print(sum_or_max([1, 2, 3]))
|
d057c6883feded817ebe0fd8042e5da371d6116e | bpham2018/powerFunction | /powerFunctionMain.py | 1,214 | 4.40625 | 4 | # float_input function -------------------------------------------------------------------
def float_input( question ):
try:
baseNumber = float( raw_input( question ) ) # terminating case
return baseNumber
except ValueError: # if input is not a real number
float_input( "\nThats not a valid input, try again: " ) # recursive call
# int_input function -----------------------------------------------------------------------
def int_input( question ):
try:
exponent = int( raw_input( "\nEnter the integer exponent: " ) ) # terminating case
return exponent
except ValueError: # if input is not a positive integer
int_input( "\nThats not a valid input, try again: " ) # recursive call
# Main Program ---------------------------------------------------------------------------
import powerFunctionFunction # import file so I can call the function in it
baseNumber = float_input( "\nEnter the base number: " ) # argument is the string you want function to ask
exponent = int_input( "\nEnter the a positive integer exponent number: " ) # --
print ( "\n" + str( powerFunctionFunction.power_function( baseNumber, exponent ) ) + "\n" ) # prints answer as a formatted string |
97849d82edd698d6748423338e9f18ca7089d957 | Robooze/unittest_exe | /test_module.py | 1,143 | 3.8125 | 4 | import unittest
from functions import gen_to_list, division, int_division, dict_division
class TestFunctions(unittest.TestCase):
def setUp(self): # Initialized before every single test
self.number = 5
def test_gen_to_list(self):
self.number = 4 # overwrites the setup
self.assertEqual(gen_to_list(self.number), [0, 1.0, 2, 3])
self.assertNotEqual(gen_to_list(self.number), [0, 1, 2, 3, 4])
def test_division(self):
self.assertEqual(division(5, 1), 5)
self.assertEqual(division(4, 0),
None) # There is no result in dividing 4 by 0, hence comparing to none. See func definition
self.assertEqual(division(5, 2), 2.5)
def test_int_division(self):
self.assertEqual(int_division(5, 2), 2)
def test_dict_division(self):
dictionary = {"a": 4, "b": 2}
self.assertEqual(dict_division(**dictionary), {"a": 4, "b": 2, "r": 2})
def test_filter(self): # testing a lambda anonymous function
self.assertEqual(list(filter(lambda x: x > 3, range(7))), [4, 5, 6])
if __name__ == '__main__':
unittest.main()
|
79a5a1a485fd776e096cb59fee2d8d309517d36d | ra2003/Python-2 | /lecture8/fileread/add_numbers.py | 335 | 3.84375 | 4 | fileName = input("Enter the file name:")
total = 0
try:
with open(fileName) as f:
while(True):
l = f.readline()
if(not l):
break
total += int(l)
except ValueError:
print("Value error:", l.strip(), " is not a number")
except FileNotFoundError:
print("Could not find file:", fileName)
print("The total is:", total) |
657e9916cc79752dd8ae95311d67a42c99b35bd2 | zs-horvath/chatbot | /scriptlets/mapping.py | 2,398 | 4.28125 | 4 | #! usr/bin/env python3
base = [1,2,3,4,5]
exponent = [5,4,3,2,1]
def power(x, y):
return(x**y)
# The mapping function gives an iterable, not a list
result = list(map(power, base, exponent))
print(result)
#Now for something completely different: mapping with lambda function
resultLambda = list(map(lambda x,y: x**y, base, exponent))
print(resultLambda)
#use multiple functions on pi
from math import sin, cos, tan, pi
def func_lister(x, functions):
results = []
for func in functions:
results.append(func(x))
return results
functions = (sin, cos, tan)
resultFuncList = func_lister(pi, functions)
print(resultFuncList)
# Do the same with list comprehension, which is really cool
def func_list_comprehend(x, functions):
resultsListComprehend = [func(x) for func in functions]
print(resultsListComprehend)
func_list_comprehend(pi, functions)
# Filter out odd numbers
fibonacci = [0,1,1,2,3,5,8,13,21,34,55]
oddNumbers = list(filter(lambda x: x % 2 == 1, fibonacci))
print(oddNumbers)
# Filter out even numbers
evenNumbers = list(filter(lambda x: x % 2 == 0, fibonacci))
print(evenNumbers)
# Now do the same filtering with a mapping, just for funsies
# Odd numbers
mapNumbersOdd = map(lambda x: x % 2 == 1, fibonacci)
mappedOdd = []
for num, val in zip(fibonacci, mapNumbersOdd):
if val == True:
mappedOdd.append(num)
print(mappedOdd)
#Even numbers
mapNumbersEven = map(lambda x: x % 2 == 0, fibonacci)
mappedEven = []
for num, val in zip(fibonacci, mapNumbersEven):
if val == True:
mappedEven.append(num)
print(mappedEven)
# Lets do something more complicated
# add shipping cost to all orders less than 100EUR
import csv
# Iterate through the sublist, multiply the quantity with the price of each ordered book
def getPrice(orderList):
quantity = float(orderList[3])
priceEach = float(orderList[4])
priceOrder = quantity * priceEach
if priceOrder < 100:
priceFinal = priceOrder + 10
else:
priceFinal = priceOrder
print(priceFinal)
#Open a csv file, read the lines from the second row
filePath = "/home/zsuzsi/study/chatbot/scriptlets/books.csv"
with open(filePath) as books:
orders = csv.reader(books)
next(orders)
data = [r for r in orders]
# Finally, use the handy map function to iterate through all the sublists
dataMapped = list(map(getPrice, data))
print(dataMapped)
|
6bddc93d79b1f74fe13fedaa3b22fd8e793d1941 | yunbinni/CodeUp | /Python/1156.py | 45 | 3.84375 | 4 | print("odd" if int(input())%2!=0 else "even") |
c992bfc3c60dd0025220a001d8776d131f77f7b2 | yaoyaoding/lecture | /2017-09-05-nt-train/day1/data/kor/yyprod.py | 246 | 3.578125 | 4 | #!/usr/bin/python
from random import *
T = 5
print T
for t in range(T) :
n = randint(5,10)
U = (1<<randint(1,5)) - 1
s = randint(0,U)
print n, randint(1,n), s
for i in range(n - 1) :
print randint(0,U),
print s
|
8f237f1336de4491e98c85a8c62d9afb2d190ab0 | dongIhwa/Python_practice | /0715/conditionLab3_0715.py | 217 | 3.75 | 4 | # [실습 3]
import random
grade = random.randint(1,6)
if grade >= 1 and grade <= 3:
print(grade, "학년은 저학년입니다.")
elif grade>= 4 and grade<= 6:
print(grade, "학년은 고학년입니다.") |
a32f9b2238bc3dc9b3c4e7b115af4acd273950b6 | kyrsant34/exercises | /valid_braces.py | 1,087 | 4.34375 | 4 | # Write a function that takes a string of braces, and determines if the order of the braces is valid. It should
# return true if the string is valid, and false if it's invalid.
#
# This Kata is similar to the Valid Parentheses Kata, but introduces new characters: brackets [], and curly braces {}.
# Thanks to @arnedag for the idea!
#
# All input strings will be nonempty, and will only consist of parentheses, brackets and curly braces: ()[]{}.
#
# What is considered Valid?
# A string of braces is considered valid if all braces are matched with the correct brace.
def valid_braces(s):
d = {'(': ')', '{': '}', '[': ']'}
expected = []
for ch in s:
if ch in d:
expected.append(d[ch])
elif not expected or ch != expected.pop():
return False
return True
if __name__ == '__main__':
assert valid_braces('(){}[]') is True
assert valid_braces('([{}])') is True
assert valid_braces('(}') is False
assert valid_braces('[(])') is False
assert valid_braces('[({})](]') is False
assert valid_braces('))') is False
|
9fea95f7f7d3d3497c58bd157aaac22313de556c | GwenIves/Scripts | /src/hoi2_tech.py | 4,596 | 3.53125 | 4 | #!/bin/env python3
#
# Generate a report of different research teams performances for all available technologies
# in the Paradox Interactive's game Hearts of Iron 2
# usage: tech.py
# <country's research teams definition csv file>
# <list of all technology definition files>
#
import sys
def calc_research_time(team, tech):
length = 0
skill, specialisations = team
for type_val, difficulty_val, double_time_val in tech:
base_len = 0
if difficulty_val == 3:
base_len = 37
elif difficulty_val == 4:
base_len = 40
elif difficulty_val == 5:
base_len = 42
elif difficulty_val == 6:
base_len = 44
elif difficulty_val == 7:
base_len = 46
elif difficulty_val == 8:
base_len = 47
elif difficulty_val == 9:
base_len = 49
else:
base_len = 50
diff = skill - difficulty_val
if diff == -7:
base_len += 42
elif diff == -6:
base_len += 33
elif diff == -5:
base_len += 25
elif diff == -4:
base_len += 18
elif diff == -3:
base_len += 12
elif diff == -2:
base_len += 7
elif diff == -1:
base_len += 3
elif diff == 1:
base_len -= 3
elif diff == 2:
base_len -= 6
elif diff == 3:
base_len -= 8
elif diff == 4:
base_len -= 10
elif diff == 5:
base_len -= 12
elif diff == 6:
base_len -= 14
if double_time_val == True:
base_len *= 2
if type_val in specialisations:
base_len /= 2
length += base_len
return length
def get_teams(filename):
teams = {}
try:
with open(filename, encoding="ISO8859") as fh:
for lineno, line in enumerate(fh):
if lineno < 1:
continue
line = line.strip()
fields = line.split(";")
name = fields[1]
skill = int(fields[3])
specialisations = []
for s in fields[6:]:
if len(s) > 1:
specialisations.append(s)
teams[name] = (skill, specialisations)
except EnvironmentError as err:
print(err)
return teams
def get_technologies(filename):
techs = {}
components = []
prev_line = None
name = None
try:
with open(filename, encoding="ISO8859") as fh:
for line in fh:
line = line.strip()
if line == "application =":
if name is not None:
techs[name] = components
components = []
name = prev_line[2:].title()
if line.startswith("component"):
type_start = line.find("type = ")
type_end = line.find(" ", type_start + 7)
difficulty_start = line.find("difficulty =")
difficulty_end = line.find(" ", difficulty_start + 13)
double_time_start = line.find("double_time =")
type_val = line[type_start + 7:type_end]
difficulty_val = int(line[difficulty_start + 13:difficulty_end])
double_time_val = double_time_start != -1
components.append((type_val, difficulty_val, double_time_val))
prev_line = line
except EnvironmentError as err:
print(err)
if name is not None:
techs[name] = components
return techs
def main():
if len(sys.argv) <= 2:
print(
"usage: {0} <teams definition file> <technology definition files list>"
.format(sys.argv[0])
)
sys.exit(1)
teams = get_teams(sys.argv[1])
techs = {}
for f in sys.argv[2:]:
techs.update(get_technologies(f))
for tech in sorted(techs.keys()):
print(tech)
team_performances = []
for team in teams.keys():
team_performances.append((calc_research_time(teams[team], techs[tech]), team))
team_performances.sort()
for perf, team in team_performances:
print(team, perf)
print()
print()
if __name__ == '__main__':
try:
main()
except FileNotFoundError:
print("Error: unable to process definition files")
sys.exit(1)
|
bebdcad009f7e3d36b23dae37510ee05cf3f393c | alisonlauren/Catch-Charlie | /oldfile.py | 11,768 | 4.25 | 4 | #The import function down below uses time, random, and math.
#The import here goes into our library and uses those components to make our game work.
import pygame
import time
import random
import math
#The first thing is we have a parent class called Enemy, and it's going to have Monster and Goblins in here.
#Because our monster and goblin share really similar characteristics of movement.
#So, I used self, width, and height because it's going to help us understand the enemy movement.
#And it's going to be used when we want to manipulate how they move.
#self.x and self.y takes the width and i just chose 10 so it can choose a place on the map
#the timer is there to just change the direction of the monster
#the speed is kinda like velocity and its how fast something goes
class Enemy:
def __init__ (self, width, height):
self.x = width/10
self.y = height/10
self.timer = 0
self.speed = 2
self.xdirection = random.randint(0, 1)
self.ydirection = random.randint(0, 1)
self.caught = False
#By defining movement, we're able to dictate where the enemy goes.
#By using the if function and using width, and height.
#By doi
def move(self, width, height):
#If the monster is moving right, it will come out the other way from the left.
#And we named self.x because we are using the class enemy and gaining access to it's x properties.
#the self.x is saying that when it reaches t of width
#and the self.x puts the monster back to other side
if self.x > width:
self.x = 0
#If the monster is moving left, it will come out the other way from the right.
elif self.x < 0:
self.x = width
#If the monster is moving north, it will come out from the south.
#if your cordinate is less than 0, then you're gonna.
if self.y < 0:
self.y = height
#If the monster is moving south, it will come out from the north.
elif self.y > height:
self.y = 0
#In my code, for less confusion I have identitied that:
# y direciton is 0 is up and 1 is down (or 0 is north and 1 is south)
# x direction is 0 is east and 1 is west
# This here updates their direction and giving them new cordinates
if self.ydirection == 0:
self.y -= self.speed
elif self.ydirection == 1:
self.y += self.speed
if self.xdirection == 0:
self.x += self.speed
elif self.xdirection == 1:
self.x -= self.speed
#The classes here are taking from the parent class of Enemy.
#And I had to use pass or my code would scream at me.
#Since there was nothing under so it wouldn't run.
class Monster(Enemy):
pass
class Goblin(Enemy):
pass
#I had to make another class hero and I couldn't merge it with Monster
#Because although they moved in the same aspect
#The hero would have to be controlled
class Hero:
def __init__ (self, width, height):
self.x = width/2
self.y = height/2
self.timer = 0
self.speed = 2
self.caught = False
def move(self, width, height, xdirection, ydirection):
#If the hero is moving right, it will come out the other way from the left.
#We name is self.x because we are using the class Hero and accessing it's x properties.
#And we use the number 32 because schoology told us the images are 32 x 32?
#The origin number of the hero
if self.x + 32 > width:
self.x = width - 32
#If the hero is moving left, it will come out the other way from the right.
elif self.x < 0:
self.x = 0
#If the hero is moving up, it will come out from the south.
if self.y < 0:
self.y = 0
#If the monster is moving down, it will come out from the north.
elif self.y + 32 > height:
self.y = height - 32
#In my code, I had to identity for this:
#y direciton is 0 is up and 1 is down
#x direction is 0 is east and 1 is west
#I am confused by even my code logic on this.
if ydirection == 0:
self.y -= self.speed
elif ydirection == 1:
self.y += self.speed
if xdirection == 0:
self.x += self.speed
elif xdirection == 1:
self.x -= self.speed
#The width and height was the measurements of our screen game.
#So we called to the width and height so we'd keep our characters here.
def main():
width = 512
height = 480
pygame.init()
screen = pygame.display.set_mode((width, height))
pygame.display.set_caption('My Game')
clock = pygame.time.Clock()
#The loaded images here are from the other template.
#It will load the hero, monster and goblins.
# Load Images
background_image = pygame.image.load('images/background.png').convert_alpha()
hero_image = pygame.image.load('images/hero.png').convert_alpha()
monster_image = pygame.image.load('images/monster.png').convert_alpha()
goblin_image = pygame.image.load('images/goblin.png').convert_alpha()
#The trouble I had was to find the function to play the game.
#We apparently have to load the music first in order to play it.
#The win sound game is just what we play once the game wins.
#But we have to use the .Sound function for that (I don't know why).
win_sound = pygame.mixer.Sound ('sounds/win.wav')
# pygame.mixer.music.load('sounds/music.wav')
# pygame.mixer.music.play()
lose_sound = pygame.mixer.Sound ('sounds/lose.wav')
# Game initialization
#In here, I'm just creating the variables and we have 5 (1 hero, 1 monster, 3 goblins)
monster = Monster(width, height)
player = Hero(width, height)
goblin1 = Goblin(width, height)
goblin2 = Goblin (width, height)
goblin3 = Goblin (width, height)
#In this portion, I had to create a font and text.
#By using the formula given on schoology.
#The 32 is the font size.
#The surface literally creates a surface.
#The one in string is what's printing.
#The 255,0,255 is what definites the color
#I purposely removed out the option portion which would've read (255,255,0).
#Uhh mainly because it seemed confusing lol.
#RGB (255, 0, 255)
f = pygame.font.Font(None, 32)
surf = f.render("Press ENTER to play again", 1, (255,0,255))
surf_losetext = f.render("You lose! Hit ENTER to play again.", 1, (255,0,255))
#The false statement says that the game is going, and keeps going.
stop_game = False
while not stop_game:
monster.move(width, height)
goblin1.move(width, height)
goblin2.move(width, height)
goblin3.move(width, height)
for event in pygame.event.get():
#I believe this part is once we close out, the game just stops.
# Event handling
if event.type == pygame.QUIT:
stop_game = True
# Game logic
#The part here is step 14, and it is what happens when the hero catches the monster.
#So by using the distance function = sqrt(sqr(x1 - x2) + sqr(y1 - y2))
#The equation above we are determining when the characters will collide.
#So, we're calculating when the player or hero and monster have collided.
#And we will do the same for when the hero collides with the goblin.
#And hence, since they collided = true because images touched each other.
if math.sqrt((player.x - monster.x)**2 + (player.y - monster.y)**2) <= 32:
monster.caught = True
#And here, we use the win sound so that when hero and monster collide, music plays.
win_sound.play()
if math.sqrt((player.x - goblin1.x)**2 + (player.y - goblin1.y)**2) <= 32:
player.caught = True
lose_sound.play()
if math.sqrt((player.x - goblin2.x)**2 + (player.y - goblin2.y)**2) <= 32:
player.caught = True
lose_sound.play()
if math.sqrt((player.x - goblin3.x)**2 + (player.y - goblin3.y)**2) <= 32:
player.caught = True
lose_sound.play()
#And above near lines 98-101 I identitied the key and restated again:
#In my code, I had to identity for this:
#y direciton is 0 is up and 1 is down (north and south).
#x direction is 0 is east and 1 is west (right and left).
#I am confused by even my code logic on this.
#But essentially we are assigning keys to our movements.
#So, by using K_RIGHT K_LEFT K_DOWN K_UP we are literally accessing our arrow keys.
#The return is enter, and by pressing enter we restart the game.
#the x direction and y direction is = 2 is because the move direction gets called
# and 0 and 1 is equal to a direction, but when it isn't it doens't move
xdirection = 2
ydirection = 2
key = pygame.key.get_pressed()
if key [pygame.K_RIGHT]:
xdirection = 0
if key [pygame.K_LEFT]:
xdirection = 1
if key [pygame.K_UP]:
ydirection = 0
if key [pygame.K_DOWN]:
ydirection = 1
# if key [pygame.K_q]:
# stop_game = True
#So, now we are doing the same thing where if we literally press enter once we catch monster.
#We use the function monster.caught = False to say you didn't catch him.
#So he is being respawned in a different randomized location to start the game again.
if key [pygame.K_RETURN] and monster.caught:
monster.caught = False
monster.x = random.randint(0, width)
monster.y = random.randint(0, height)
elif key [pygame.K_RETURN] and player.caught:
monster.caught = False
monster.x = random.randint(0, width)
monster.y = random.randint(0, height)
#Uhh, here you just use the player.move function so it takes properties from his class.
player.move(width, height, xdirection, ydirection)
#The background and the blit just makes the image appear.
#So one for the background, one for hero, and three for the goblin.
#But you need to have an if statement here because of the game.
#So, then you use if statements of if you caught him or not.
#Ehh this part confused me so much I don't even really understand it.
# Draw background
screen.blit(background_image, [0, 0])
if not player.caught:
screen.blit(hero_image, [player.x, player.y])
if player.caught:
screen.blit(surf_losetext, [width/7, height/2])
screen.blit(goblin_image, [goblin1.x, goblin1.y])
screen.blit(goblin_image, [goblin2.x, goblin2.y])
screen.blit(goblin_image, [goblin3.x, goblin3.y])
if not monster.caught:
screen.blit(monster_image, [monster.x, monster.y])
if monster.caught:
screen.blit(surf, [width/5, height/2])
#I
# Game display
pygame.display.update()
monster.timer += clock.tick(60)
#If 2 seconds have gone by, it's just to check that the timer is running. So, you can put like any number.
if monster.timer >= 2000:
monster.timer = 0
#The random function will redirect the monster into another direction inside the box.
#It's what we did kinda up there
#If i've gone 2000 cycles, then we're going to give them a random cordinate to move them.
monster.xdirection = random.randint(0, 1)
monster.ydirection = random.randint(0, 1)
goblin1.xdirection = random.randint(0, 1)
goblin1.ydirection = random.randint(0, 1)
goblin2.xdirection = random.randint(0, 1)
goblin2.ydirection = random.randint(0, 1)
goblin3.xdirection = random.randint(0, 1)
goblin3.ydirection = random.randint(0, 1)
pygame.quit()
if __name__ == '__main__':
main() |
6eafaa8be33a4a9090e54c643c67e246bf778966 | TrellixVulnTeam/tic-tac-toe_P4BI | /controller.py | 3,788 | 3.609375 | 4 | from tkinter import *
from XO import XO
class Controller:
def __init__(self):
self.numOfClicks = 0
self.symbol = ""
self.root = Tk()
self.xo = XO()
self.root.title("tic tac toe")
self.symbolTexts = []
self.buttonList = []
for i in range(9):
self.symbolTexts.append(StringVar())
self.symbolTexts[i].set("")
self.buttonList.append(
Button(self.root, textvariable=self.symbolTexts[0], command=lambda: self.click(0),relief="sunken", padx=40, pady=40))
self.buttonList.append(
Button(self.root, textvariable=self.symbolTexts[1], command=lambda: self.click(1),relief="sunken", padx=40, pady=40))
self.buttonList.append(
Button(self.root, textvariable=self.symbolTexts[2], command=lambda: self.click(2),relief="sunken", padx=40, pady=40))
self.buttonList.append(
Button(self.root, textvariable=self.symbolTexts[3], command=lambda: self.click(3),relief="sunken", padx=40, pady=40))
self.buttonList.append(
Button(self.root, textvariable=self.symbolTexts[4], command=lambda: self.click(4),relief="sunken", padx=40, pady=40))
self.buttonList.append(
Button(self.root, textvariable=self.symbolTexts[5], command=lambda: self.click(5),relief="sunken", padx=40, pady=40))
self.buttonList.append(
Button(self.root, textvariable=self.symbolTexts[6], command=lambda: self.click(6),relief="sunken", padx=40, pady=40))
self.buttonList.append(
Button(self.root, textvariable=self.symbolTexts[7], command=lambda: self.click(7),relief="sunken", padx=40, pady=40))
self.buttonList.append(
Button(self.root, textvariable=self.symbolTexts[8], command=lambda: self.click(8),relief="sunken", padx=40, pady=40))
for i in range(9):
if i < 3:
self.buttonList[i].grid(row=1, column=i)
elif i < 6:
self.buttonList[i].grid(row=2, column=i - 3)
else:
self.buttonList[i].grid(row=3, column=i - 6)
self.root.mainloop()
def click(self, i):
self.buttonList[i]["command"] = 0
self.buttonList[i]['relief'] = 'sunken'
if self.numOfClicks % 2 == 0:
self.symbol = "X"
color = "red"
else:
self.symbol = "O"
color = "blue"
self.buttonList[i]["fg"]=color
self.xo.set(i, self.symbol)
self.symbolTexts[i].set(self.symbol)
if self.xo.isWinner(self.symbol):
self.popup("player "+self.symbol+" WINS !")
self.reset()
return
if self.numOfClicks == 8:
if self.xo.isTie():
self.popup("It's a TIE!")
self.reset()
return
self.numOfClicks += 1
def popup(self,text):
pu = Toplevel()
l = Label(pu,text=text).pack()
pu.title("result")
pu.geometry('200x100')
def reset(self):
self.xo = XO()
self.numOfClicks = 0
for i in range(9):
self.buttonList[i]["state"] = NORMAL
self.symbolTexts[i].set("")
self.buttonList[0]['command'] = lambda: self.click(0)
self.buttonList[1]['command'] = lambda: self.click(1)
self.buttonList[2]['command'] = lambda: self.click(2)
self.buttonList[3]['command'] = lambda: self.click(3)
self.buttonList[4]['command'] = lambda: self.click(4)
self.buttonList[5]['command'] = lambda: self.click(5)
self.buttonList[6]['command'] = lambda: self.click(6)
self.buttonList[7]['command'] = lambda: self.click(7)
self.buttonList[8]['command'] = lambda: self.click(8)
|
e25c390301c7f13870e52a1d06fa286b167f87d7 | Clint1080/databases | /process.py | 925 | 3.84375 | 4 | log_file = open("um-server-01.txt") # This line brings in the data to our python script so we can manipulate it
def sales_reports(log_file): # This is like creating a "View" or "Report" to view the data
for line in log_file: # Start of the for loop
line = line.rstrip() # rstrip is a methon that removes trailing characters that you specify in the argument like when we rstrip( \n)
day = line[0:3] # This is setting day equal to the first 3 characters of the line starting at zero.
if day == "Mon": # This is the condition
print(line) # This prints out the line if condition is met
# sales_reports(log_file) # Calling the function, basically running the report.
def melon_orders(log_file):
for line in log_file:
line = line.rstrip().split(' ')
count = line[2]
# print(count)
if line[2] > 10:
print(line)
melon_orders(log_file) |
8d84e67c9da1e6986ae0bfca661633da7b9b06cc | clhansen24/GP_analysis | /clustering.py | 7,400 | 3.5 | 4 | '''
Clustering approach
- Particles of each size are separately
For each size:
- Particles within a specific x,y are grouped
- The spread in the z is determined for each group
- The median spred in the z is set as the z threshold for de-convolution
- Particles within the x,y,z, threshold are represented as just the center point
'''
import sys
import scipy.stats
import statistics
import numpy
import csv
import math
if(sys.argv[1] == "C1.csv"): print("Clustering C1")
else: print("Clustering C2")
#Reading in all the x,y,z,size data for one channel
X = list(); Y = list(); Z = list(); S = list()
with open (sys.argv[1], 'r') as csv_file:
csv_reader = csv.reader (csv_file)
for line in csv_reader:
X.append(line[0])
Y.append(line[1])
Z.append(line[2])
S.append(line[3])
#Going through S and figuring out how many sizes there are
sizes = list()
for size in S:
if size not in sizes:
sizes.append(size)
#Creating individual lists for coordinates of each size
numLists = len(sizes)
sizeLists = []
for i in range(numLists):
sizeLists.append([[],[],[]])
# S1 S2 S3
#{[[x][y][z]], [[x][y][z]], [[x][y][z]]]- size lists
# 0 1 2
# 0 1 2 0 1 2 0 1 2
#Example: access list 3 with list[2], and the ith item of list 3 with list[2][i].
for i in range(0, len(sizes)): #Going through the coordinates 3 times
for j in range(0, len(X)-1):
if (sizes[i] == S[j]):
sizeLists[i][0].append(X[j])
sizeLists[i][1].append(Y[j])
sizeLists[i][2].append(Z[j])
'''
Given three numpy arrays x,y,z sorts the arrays consecutively and returns
sorted numpy arrays Xs, Ys, Zs
'''
def Sort(x,y,z):
#For sorted data
Xs = list(); Ys = list(); Zs = list()
Xs = numpy.array(Xs, dtype=float); Ys = numpy.array(Ys, dtype=float); Zs = numpy.array(Zs, dtype=float)
#Concatenating numpy arrays
data = numpy.concatenate((x[:, numpy.newaxis],
y[:, numpy.newaxis],
z[:, numpy.newaxis]),
axis=1)
#Sorting wrt x, y, z consecutively like excel
sortedData = data[numpy.lexsort(numpy.transpose(data)[::-1])]
#Separating the sorted data into numpy arrays
sortedArray = numpy.hsplit(sortedData, 3)
Xs = numpy.concatenate(sortedArray[0], axis=0)
Ys = numpy.concatenate(sortedArray[1], axis=0)
Zs = numpy.concatenate(sortedArray[2], axis=0)
return (Xs, Ys, Zs);
'''
Given numpy arrays with x,y,z coordinates and the radius of the particle
creates groups of particles to be clustered
'''
def Groups(x,y,z, radius):
XGroups = list(); YGroups = list(); ZGroups = list()
#Keeping track of the points that have been visited, to avoid adding the same point to two clusters
visited = numpy.zeros(x.size)
for i in range(0, len(x)):
#Refreshing the lists before generating another cluster
similarX = list()
similarY = list()
listofZ = list()
if(visited[i] == 1):
continue
visited[i] = 1
similarX.append(x[i]) #adding the first x to the list
similarY.append(y[i]) #adding the corresponding y to the list
listofZ.append(z[i]) #adding the corresponding z to the list
#Iterating through the rest of the array to find similar values that could be added to the group
for j in range(i, len(x)):
if (visited[j] == 1):
continue
if ((x[j]>=x[i]-radius and x[j]<=x[i]+radius) and (y[j]>=y[i]-radius and y[j]<=y[i]+radius)):
similarX.append(x[j])
similarY.append(y[j])
listofZ.append(z[j])
visited[j] = 1
#When you come out of the inner loop, you have one group of points
XGroups.append(similarX); YGroups.append(similarY); ZGroups.append(listofZ)
return(XGroups, YGroups, ZGroups)
'''
Given a specific group of points, generates the clustered points
'''
def generateCluster(xGroup, yGroup, zGroup, zThreshold):
xOfCluster = 0.0; yOfCluster = 0.0; zOfCluster = 0.0
maxz = numpy.amax(zGroup)
minz = numpy.amin(zGroup)
zlength = len(zGroup)
zdist = maxz - minz #How spread apart the points are
#In case I need to split up the arrays for recursion
xarrays = list(); yarrays = list();zarrays = list()
if (zdist<zThreshold): #Is one cluster
pointpos = int(math.floor((zlength/2.0)))
xOfCluster = xGroup[pointpos]
yOfCluster = yGroup[pointpos]
zOfCluster = zGroup[pointpos]
if (zdist>zThreshold):#More than one cluster
xarrays = numpy.array_split(xGroup, 2)
yarrays = numpy.array_split(yGroup, 2)
zarrays = numpy.array_split(zGroup, 2)
generateCluster(xarrays[0],yarrays[0],zarrays[0],zThreshold)
generateCluster(xarrays[1],yarrays[1],zarrays[1],zThreshold)
clusterCenter = [xOfCluster, yOfCluster, zOfCluster]
return (clusterCenter);
'''
Given x,y,z coordinates and the radius, groups them using the Groups method, generates clusters, and
returns the clustered x,y,z,s for the coordinates
'''
def Cluster(X,Y,Z, radius):
X = numpy.array(X, dtype = float); Y = numpy.array(Y, dtype = float); Z = numpy.array(Z, dtype = float)
#Sorting data
sortedData = Sort(X, Y, Z)
#Grouping points
groupedPoints = Groups(sortedData[0],sortedData[1],sortedData[2],radius)
#Getting the zThreshold
numberOfZSplits = list()
for i in range(0, len(groupedPoints[2])):
if(len(groupedPoints[2][i]) != 1):
numberOfZSplits.append(len(groupedPoints[2][i]))
if(len(numberOfZSplits) == 0):
MedianZSplits = 0
else:
MedianZSplits = math.ceil(statistics.median(numberOfZSplits))
zThreshold = MedianZSplits*Z[Z.size-1]
#print("Radius of RNP: ", radius)
#print("Median point spread: ", zThreshold)
#Creating lists to store the coordinates of clustered points
xPoints = list(); yPoints = list(); zPoints = list(); ClusterPoints = list()
#Going through each group and clustering points
for i in range(0, len(groupedPoints[0])):
ClusterPoints = generateCluster(groupedPoints[0][i], groupedPoints[1][i],groupedPoints[2][i], zThreshold)
if (ClusterPoints[0] <= 0 or ClusterPoints[1] <= 0 or ClusterPoints[2] <= 0 ):
continue
xPoints.append(ClusterPoints[0]); yPoints.append(ClusterPoints[1]); zPoints.append(ClusterPoints[2])
xPoints = numpy.array(xPoints, dtype = float); yPoints = numpy.array(yPoints, dtype = float); zPoints = numpy.array(zPoints, dtype = float)
return(xPoints, yPoints, zPoints)
#Clustering Points
cX = list(); cY = list(); cZ = list()
cX = numpy.array(cX, dtype = float); cY = numpy.array(cY, dtype = float); cZ = numpy.array(cZ, dtype = float)
for i in range (0, len(sizes)):
clusteredPoints = Cluster(sizeLists[i][0],sizeLists[i][1],sizeLists[i][2], float(sizes[i]))
clusteredPoints= numpy.array(clusteredPoints, dtype = float)
cX = numpy.concatenate((cX, clusteredPoints[0]), axis=0)
cY = numpy.concatenate((cY, clusteredPoints[1]), axis=0)
cZ = numpy.concatenate((cZ, clusteredPoints[2]), axis=0)
numpy.savetxt(sys.argv[2], numpy.column_stack((cX, cY, cZ)), delimiter=",", fmt='%s')
|
4a71eb3fffe4b73a2cf11b6daff09a7f11a610fa | chinchponkli/pyalgorithms | /search algorithms/linearSearch.py | 254 | 3.921875 | 4 | '''
Time Complexity : O(n)
Auxiliary Space : O(1)
'''
def linearSearch(arr, k):
for i in range(len(arr)):
if arr[i] == k:
return i
return -1
arr = [1, 2, 3, 4, 5, 6, 7, 8]
for i in range(10):
print (linearSearch(arr, i)) |
a5a5692aafe4bc822f59035e5fde620ca732f65f | jmseb3/bakjoon | /Prgrammers/lv2/배달.py | 829 | 3.515625 | 4 | from collections import defaultdict
import heapq
def solution(N, road, K):
INF = int(1e9)
graph = defaultdict(list)
road.sort()
for a, b, c in road:
graph[a].append((b, c))
graph[b].append((a, c))
distance =[INF] *(N+1)
def dijkstra(start):
distance[start] = 0
q = []
heapq.heappush(q, (0, start))
while q:
dist, now = heapq.heappop(q)
if distance[now] < dist:
continue
for next, next_dist in graph[now]:
cost = dist+next_dist
if cost < distance[next]:
distance[next] = cost
heapq.heappush(q, (cost, next))
dijkstra(1)
answer = 0
for x in distance:
if x <=K:
answer +=1
return answer
|
8127db4038684ed69ffd210c64fcdcd54452c76d | archanakul/ThinkPython | /Chapter11-Dictionary/ReverserDict.py | 3,743 | 4.125 | 4 | #PROGRAM - 40
"""
creates a dictionary that maps from frequencies to letters
1. SINGLETON is a list that contains a single element
2. Lists can be values in a dictionary, as this example shows, but they
cannot be keys (TypeError: list objects are unhashable)
3. Basically have to be hashable/immutable as they can not be changing
because the value are always associated with keys. Hence lists canot be
used as key but can be used as value. Same is with DICTIONARIES as they
are MUTABLE too.
4. DEL OPERATOR: Remove dict[key] from dictionary when key is found else
Raises a KeyError when not found.
del dict[key]
5. Dictionary METHODS:
- CLEAR(): Remove all items from the dictionary.
dict.clear()
- COPY(): Return a shallow copy of the dictionary.
dict.copy()
- ITERITEMS(): Returns an iterator over the dict's key-value pairs.
dict.iteritems()
- ITERKEYS(): Returns an iterator over the dict's keys.
dict.iterkeys()
- ITERVALUES(): Returns an iterator over the dict's key-value pairs.
dict.itervalues()
Note: Are called with no intervening changes to the Dictionary, list
will directly correspond/append
- POP(): If key is in the dictionary, remove it & return its value,
else return default. If default is not given & key is not in
the dictionary, a KeyError is raised.
dict.pop(key[, default])
- POPITEMS(): Remove & return an arbitrary key-value pair from dict
If dict is empty, calling popitem() raises a KeyError
dict.popitems()
- UPDATE(): Update dictionary with a key/value pairs from other,
overwriting existing keys. Return None
Accepts either another dictionary object or an iterable of
key/value pairs
dict.update([other])
- SETDEFAULT(): If key is in the dictionary, return its value. If not,
insert key with a value of default & return default.
Default defaults to None
dict.setdefault(key[, default])
- GET(): Return the value for key if key is in the dictionary, else
default. If default is not given, it defaults to "None" so it
never raises any KeyError
dict.get(key[,default])
"""
def histogram(word):
my_dict = dict()
for c in word:
my_dict[c] = my_dict.get(c,0) + 1
return my_dict
hist = histogram('Archana Raghavendra Kulkarni')
def invert_dict(diction):
inv_dict = dict()
for key in diction:
val = diction[key]
if val not in inv_dict:
inv_dict[val] = [key] # create & assign a SINGLETON
else:
inv_dict[val].append(key)
return inv_dict
#print invert_dict(hist)
def concise_invert(diction):
inv = dict()
for key in diction:
val = diction[key]
inv.setdefault(val,[]).append(key)
return inv
print concise_invert(hist)
hist.update(x = 4,y = 5, z = 7) # add new 3 key-value pairs
print hist
print hist.pop('J', 10)
#print hist.pop('J') #KeyError
print hist.popitem() # remove an entry arbitrarily
lists = []
for (k,v) in hist.iteritems():
lists.append([k, v])
print lists
tuples = [(v,k)for (k,v) in hist.iteritems()]
print tuples |
6a1ecddd91818fa4e125d1eca5aada408b859dac | rajlath/rkl_codes | /Rosalind/algorithm_heights/sq.py | 937 | 3.5625 | 4 | def multiply(a, b):
lena = len(a)
c = [[0] * lena for _ in range(lena)]
for i in range(lena):
for j in range(lena):
for k in range(lena):
c[i][j] += a[i][k] * b[k][j]
return c
def has_sqr(adj):
mult_matrix = multiply(adj, adj)
print( any([i != j and mult_matrix[i][j] > 1 for j in len(mult_matrix) for i in len(mult_matrix)]))
def main():
ifile = open("rosalind_sq.txt", "r")
wfile = open("rosalind_sq_ans.txt", "w")
for _ in range(int(ifile.readline())):
ifile.readline()
n, e = [int(x) for x in ifile.readline.split()]
adj = [[0 for x in range(n)] for y in range(n)]
for _ in range(e):
u, v = [int(x) for x in ifile.readline.split()]
adj[u-1][v-1] = 1
adj[v-1][u-1] = 1
print( 1 if has_sqr(adj) else -1, end=" ")
print( 1 if has_sqr(adj) else -1, end=" ", file = wfile)
|
88105fea79dbd54f6e5368e4f56ce5e997e1d0c8 | phsh/potential-computing-machine | /phshpy/roman-numerals.py | 1,783 | 4.1875 | 4 | #!/usr/bin/python
'''
Roman numerals come from the ancient Roman numbering system. They are based on specific letters of the alphabet which are combined to signify the sum (or, in some cases, the difference) of their values. The first ten Roman numerals are:
I, II, III, IV, V, VI, VII, VIII, IX, and X.
The Roman numeral system is decimal based but not directly positional and does not include a zero. Roman numerals are based on combinations of these seven symbols:
Symbol Value
I 1 (unus)
V 5 (quinque)
X 10 (decem)
L 50 (quinquaginta)
C 100 (centum)
D 500 (quingenti)
M 1,000 (mille)
More additional information about roman numerals can be found on the Wikipedia article.
For this task, you should return a roman numeral using the specified integer value ranging from 1 to 3999.
Input: A number as an integer.
Output: The Roman numeral as a string.
checkio(6) == 'VI'
checkio(76) == 'LXXVI'
checkio(13) == 'XIII'
checkio(44) == 'XLIV'
checkio(3999) == 'MMMCMXCIX'
'''
def trans(num, one, five, ten):
'''
0 = ""
1 = "I"
2 = "II"
3 = "III"
4 = "IV"
5 = "V"
6 = "VI"
7 = "VII"
8 = "VIII"
9 = "IX"
'''
value = ""
if num > 0 and num < 4:
for x in range(num):
value += one
if num == 4:
value = one + five
if num > 4 and num < 9:
value = five
for x in range(5,num):
value += one
if num == 9:
value = one + ten
return value
def checkio(num):
strValue=""
one = num % 10
ten = (num // 10 ) % 10
hundred = (num // 100) % 10
thousand = (num // 1000) % 10
strValue += trans(thousand, "M", "M", "M")
strValue += trans(hundred, "C", "D", "M")
strValue += trans(ten, "X", "L", "C")
strValue += trans(one, "I", "V", "X")
return strValue
print checkio(6)
print checkio(76)
print checkio(13)
print checkio(44)
print checkio(3999)
|
e53546948c4ea0108a81ef46ee40861f95824db6 | GT-RAIL/derail-fetchit-public | /task_execution/task_executor/src/task_executor/ops.py | 4,645 | 3.71875 | 4 | #!/usr/bin/env python
# The operations that can be specified in the YAML
from __future__ import print_function, division
import rospy
# Private helper functions
def _get_heap_for_var_name(var_name, variables, params):
"""Given a variable name, return the 'heap' that contains it"""
if var_name in variables:
return variables
elif var_name in params:
return params
else:
return None
# The Operations. All operations receive a current_params and current_variables
def assign(var_name, value, current_params, current_variables):
"""
Assigns the indicated `value` to a variable with name `var_name`
Args:
var_name (str) : Name of the variable to assign the value to
value (any) : Value to assign to that variable
Returns:
A dictionary with :code:`{ var_name: value }`
"""
return { var_name: value }
def decrement(var_name, current_params, current_variables):
"""
Decrements the value of variable `var_name` in the `current_variables`. The
value must exist and must be an integer.
Args:
var_name (str) : Name of the variable to decrement
Returns:
A dictionary with :code:`{ var_name: var_name-1 }`
"""
heap = _get_heap_for_var_name(var_name, current_variables, current_params)
return { var_name: heap[var_name] - 1 }
def increment(var_name, current_params, current_variables):
"""
Increments the value of variable `var_name` in the `current_variables`. The
value must exist and must be an integer.
Args:
var_name (str) : Name of the variable to decrement
Returns:
A dictionary with :code:`{ var_name: var_name+1 }`
"""
heap = _get_heap_for_var_name(var_name, current_variables, current_params)
return { var_name: heap[var_name] + 1 }
def make_boolean(var_name, bool_name, current_params, current_variables):
"""
Make the value of a variable in the current variables a boolean.
Args:
var_name (str) : Name of the variable to binarize
bool_name (str) : Name of the binarized version of the variable
Returns:
A dictionary with :code:`{ bool_name: bool(var_name) }`
"""
heap = _get_heap_for_var_name(var_name, current_variables, current_params)
return { bool_name: bool(heap[var_name]) }
def negate(var_name, negate_name, current_params, current_variables):
"""
Negate the current value of var_name => not var_name
Args:
var_name (str) : Name of the variable to negate
negate_name (str) : Name of the variable to contain the negation
Returns:
A dictionary with :code:`{ negate_name: not var_name }`
"""
heap = _get_heap_for_var_name(var_name, current_variables, current_params)
return { negate_name: not heap[var_name] }
def get_index(var_name, idx_name, idx, current_params, current_variables):
"""
Assuming that var_name is an indexable array / dict, return the desired idx
from within the array
Args:
var_name (str): Name of the variable to get the index from
idx_name (str): Name of the output variable to contain the indexed item
idx (int, str): The desired index in var_name. Can be int or str
Returns:
A dictionary with :code:`{ idx_name: var_name[idx] }`
"""
heap = _get_heap_for_var_name(var_name, current_variables, current_params)
return { idx_name: heap[var_name][idx] }
def check_value(var_name, value, check_name, current_params, current_variables):
"""
Check if the value of var_name matches the one indicated, and return the
result in check_name.
Args:
var_name (str): Name of the variable to check the value of
value (*): The value to check
check_name (str): The name of the variable containing the check result
Returns:
A dictionary with :code:`{ check_name: var_name == value }`
"""
heap = _get_heap_for_var_name(var_name, current_variables, current_params)
return { check_name: heap[var_name] == value }
def print_var(var_name, current_params, current_variables):
"""
Print the variable with var_name
Args:
var_name (str): Name of the variable to print
"""
heap = _get_heap_for_var_name(var_name, current_variables, current_params)
rospy.loginfo("Op print_var: {} = {}".format(var_name, heap[var_name]))
return {}
def abort(current_params, current_variables):
"""
Abort the task
Raises:
Exception
"""
raise Exception("Task is aborted")
def noop(current_params, current_variables):
"""
Does nothing
"""
return {}
|
655c60af01012e532a9537bc8d147da6af6280ec | DKanyana/PythonProblems | /10_MinMaxDiff.py | 290 | 3.875 | 4 | def minmax_diff(nums):
min_num = nums[0]
max_num = nums[0]
for num in nums:
if num < min_num:
min_num = num
elif num >max_num:
max_num = num
return max_num - min_num
nums = [1,3,1,2,6,79,10]
print(minmax_diff(nums)) |
6d271e230658260af04899d5e7a783cf78a9c6ad | TarandeepSingh562/BasicTemperatureConverter | /TempConverter.py | 2,516 | 4.09375 | 4 | from tkinter import *
from tkinter import messagebox
#Creates a class
class MyGUI:
def __init__(self):
root = Tk()
root.geometry("400x200")
root.title("Temperature Conversion")
# creates a Frame
frame = Frame(root)
frame.pack(fill = BOTH, expand = True)
#creates a label
label1 = Label(frame, text="Enter number to convert")
label1.pack(side=TOP, expand=True, fill=BOTH)
# provides entry box for user
self.entry = Entry(frame)
self.entry.pack(side=TOP, expand=True, fill=BOTH)
# displays the first label
display1 = Label(frame)
display1.pack(side=TOP, expand=True, fill=BOTH)
# creates a button for Convert to convert fahrenheit into celsius
button1 = Button(frame, text="Convert to Celsius", command=self.convert)
button1.pack(side=TOP, expand=True, fill=BOTH)
# creates a button for Convert to convert celsius into fahrenheit
button2 = Button(frame, text="Convert to Fahrenheit", command=self.convert1)
button2.pack(side=TOP, expand=True, fill=BOTH)
# creates a button for Quit to quit the program
button3 = Button(text="Quit", fg="Red", command=quit)
button3.pack(side=TOP, expand=True, fill=BOTH)
root.mainloop()
def convert(self):
for char in self.entry.get():
if not char.isdigit() and char != ".":
return messagebox.showinfo("Error!", "Please enter a number")
else:
Tf = float(self.entry.get())
Tc = (5 / 9) * (Tf - 32)
C = "{:12.4f}".format(Tc)
# creates a messagebox for the answer
return messagebox.showinfo("Fahrenheit to Celsius conversion",
str(Tf) + " Fahrenheit to Celsius conversion is: " + str(C) + " Celsius")
def convert1(self):
for char1 in self.entry.get():
if not char1.isdigit() and char1 != ".":
return messagebox.showinfo("Error!", "Please enter a number")
else:
tc = float(self.entry.get())
tf = ((9 / 5) * tc) + 32
F = "{:12.4f}".format(tf)
# creates a messagebox for the answer
return messagebox.showinfo("Celsius to Fahrenheit conversion",
str(tc) + " Celsius to Fahrenheit conversion is: " + str(F) + " Fahrenheit")
my_gui = MyGUI()
|
dc2c9eb1e4c9b42ceb4c90865431c831680d8a6d | DincerDogan/Python-2 | /Visualizing Geographic Data-223.py | 2,495 | 3.515625 | 4 | ## 1. Geographic Data ##
import pandas as pd
airlines=pd.read_csv("airlines.csv")
airports=pd.read_csv("airports.csv")
routes=pd.read_csv("routes.csv")
print(airlines.iloc[0])
print(airports.iloc[0])
print(routes.iloc[0])
## 4. Workflow With Basemap ##
import matplotlib.pyplot as plt
from mpl_toolkits.basemap import Basemap
m = Basemap(projection="merc",llcrnrlat=-80,urcrnrlat=80,llcrnrlon=-180,urcrnrlon=180 )
## 5. Converting From Spherical to Cartesian Coordinates ##
m = Basemap(projection='merc', llcrnrlat=-80, urcrnrlat=80, llcrnrlon=-180, urcrnrlon=180)
latti=airports["latitude"].tolist()
longi=airports["longitude"].tolist()
x,y=m(longi,latti)
print(x)
print(y)
## 6. Generating A Scatter Plot ##
m = Basemap(projection='merc', llcrnrlat=-80, urcrnrlat=80, llcrnrlon=-180, urcrnrlon=180)
x, y = m(longitudes, latitudes)
m.scatter(x,y, s=1)
plt.show()
## 7. Customizing The Plot Using Basemap ##
m = Basemap(projection='merc', llcrnrlat=-80, urcrnrlat=80, llcrnrlon=-180, urcrnrlon=180)
longitudes = airports["longitude"].tolist()
latitudes = airports["latitude"].tolist()
x, y = m(longitudes, latitudes)
m.scatter(x, y, s=1)
m.drawcoastlines()
plt.show()
## 8. Customizing The Plot Using Matplotlib ##
# Add code here, before creating the Basemap instance.
m = Basemap(projection='merc', llcrnrlat=-80, urcrnrlat=80, llcrnrlon=-180, urcrnrlon=180)
longitudes = airports["longitude"].tolist()
latitudes = airports["latitude"].tolist()
x, y = m(longitudes, latitudes)
fig=plt.figure(figsize=(15,20))
chart=fig.add_subplot(1,1,1)
m.scatter(x, y, s=1)
m.drawcoastlines()
chart.set_title("Scaled Up Earth With Coastlines")
plt.show()
## 9. Introduction to Great Circles ##
import pandas as pd
geo_routes=pd.read_csv("geo_routes.csv")
geo_routes[0:5]
## 10. Displaying Great Circles ##
def create_great_circles(df):
for indes,row_list in df.iterrows():
if abs(row_list["end_lon"]-row_list["start_lon"])<180:
if abs(row_list["start_lat"]-row_list["end_lat"])<180:
# return(None)
m.drawgreatcircle(row_list["start_lon"],row_list["start_lat"], row_list["end_lon"],row_list["end_lat"])
df=geo_routes[(geo_routes["source"]=="DFW")][["start_lon","start_lat","end_lon","end_lat"]]
#print(df)
fig, ax = plt.subplots(figsize=(15,20))
m = Basemap(projection='merc', llcrnrlat=-80, urcrnrlat=80,llcrnrlon=-180,urcrnrlon=180)
m.drawcoastlines()
create_great_circles(df)
|
4e5f4a2032485b12db03776de3ddca39a458a47a | KaterinaMutafova/SoftUni | /Python Advanced/10. Exam_preparation/Exam_ex1_24_10_2020.py | 1,032 | 3.703125 | 4 | from collections import deque
def get_the_shortest_job(list_j):
shortest_j = list_j[0]
index_shortest_j = 0
for index in range(len(list_j)):
if list_j[index] < shortest_j and list_j[index] != 0:
shortest_j = list_j[index]
index_shortest_j = index
elif list_j[index] == shortest_j:
if index < index_shortest_j:
shortest_j = list_j[index]
index_shortest_j = index
elif shortest_j == 0:
shortest_j = list_j[index]
index_shortest_j = index
return shortest_j, index_shortest_j
list_jobs = deque([int(el) for el in input().split(", ")])
index_of_the_job = int(input())
job_at_index = list_jobs[index_of_the_job]
counter = 0
while not list_jobs[index_of_the_job] == 0:
shortest_job, shortest_index = get_the_shortest_job(list_jobs)
while not list_jobs[shortest_index] == 0:
list_jobs[shortest_index] -= 1
counter += 1
print(counter)
|
92a6c3d77f6cc878dc0e3a873f149f9b473bf1d2 | AngelFA04/practice_python_excercises | /excercise_8/main.py | 1,149 | 4.09375 | 4 | def menu():
print("""
SELECT ONE CHOICE:
1 - Rock
2 - Paper
3 - Scissors
""")
def ask_player_moves():
menu()
choices = {'1': 'ROCK', '2': 'PAPER', '3': 'SCISSORS'}
move_p1 = choices.get(input('Turn player 1: '))
move_p2 = choices.get(input('Turn player 2: '))
return move_p1.upper(), move_p2.upper()
def select_winner(m1, m2):
winner = None
# winners = [('ROCK', 'SCISSORS'),('SCISSORS', 'PAPER'),('PAPER', 'ROCK')]
if m2 == 'ROCK' and m1 == 'PAPER':
winner = 'Player 1'
elif m2 == 'PAPER' and m1 == 'ROCK':
winner = 'Player 2'
elif m1 == 'SCISSORS' and m2 == 'PAPER':
winner = 'Player 1'
elif m2 == 'SCISSORS' and m1 == 'PAPER':
winner = 'Player 2'
elif m1 == 'ROCK' and m2 == 'SCISSORS':
winner = 'Player 1'
elif m2 == 'ROCK' and m1 == 'SCISSORS':
winner = 'Player 2'
return winner
if __name__ == "__main__":
winner = None
while not winner:
m1, m2 = ask_player_moves()
winner = select_winner(m1, m2)
print(f'The winner is {winner}')
|
825b5e685b9e1336f43006a2478d217d01558a13 | staryjie/Full-Stack | /day9/auth.py | 192 | 3.5 | 4 | #!/usr/bin/env python
# -*- coding:utf-8 -*-
import getpass
username = input("Pls enter your username: ").strip()
passwd = getpass.getpass("Pls enter your password: ")
print(username,passwd) |
d6b14095db3c0502cb5cde47caad628e3f8085d4 | saharma/PythonExercises | /Lab2/lab2ex8.py | 157 | 3.53125 | 4 | grades = [9, 7, 7, 10, 3, 9, 6, 6, 2]
print(grades.count(7))
grades[len(grades)-1] = 4
print(max(grades))
grades.sort()
print(sum(grades)/float(len(grades))) |
1ddb0796dad90a69b7b63f020d46ce33627b7484 | Rodrigodebarros17/Livropython | /CAP11/11-1.py | 537 | 3.890625 | 4 | import sqlite3
conexao = sqlite3.connect("precos.db")
cursor = conexao.cursor()
cursor.execute('''
create table produtos(
produto text,
preco float
)
''')
while True:
produto = input("Favor, informe o nome do produto(enter para sair do programa):")
if produto == "":
break
preco = input("informe o preço do produto:")
cursor.execute('''
insert into produtos (produto, preco)
values(?, ?)
''', (produto, preco))
conexao.commit()
cursor.close()
conexao.close() |
4c83baad4e6a8cbac220ec6fc12282313d779886 | michelle100320206/programming_for_big_data_MC10032026 | /CA1/calccode.py | 1,924 | 3.953125 | 4 | import math
#import python module to run calculations
class mathcalc(object): #setting up class for calculator. can reference this class in seperate file to access functions
def add(self,x,y):
number_types = (int, long, float, complex)
if isinstance(x, number_types) and isinstance(y, number_types):
return x + y
else:
raise ValueError
def subtract(self, x, y):
number_types = (int, long, float, complex)
if isinstance(x, number_types) and isinstance(y, number_types):
return x - y
else:
raise ValueError
def multiply(self, x, y):
number_types = (int, long, float, complex)
if isinstance(x, number_types) and isinstance(y, number_types):
return x * y
else:
raise ValueError
def divide(self, x, y):
number_types = (int, long, float, complex)
if isinstance(x, number_types) and isinstance(y, number_types):
if x == 0 or y == 0:
return 'error'
else:
return x / y
else:
raise ValueError
def exp(self, x, y):
number_types = (int, long, float, complex)
if isinstance(x, number_types) and isinstance(y, number_types):
return x ** y
else:
raise ValueError
def sq(self, x,): #can only square one number
number_types = (int, long, float, complex)
if isinstance(x, number_types):
return x ** 2
else:
raise ValueError
def sqroot(self, x,):
number_types = (int, long, float, complex)
if isinstance(x, number_types):
return x ** (0.5)
else:
raise ValueError
def sin(self, x,):
number_types = (int, long, float, complex)
if isinstance(x, number_types) :
return math.sin(x,)
else:
raise ValueError
def cos(self, x,):
number_types = (int, long, float, complex)
if isinstance(x, number_types):
return math.cos(x,)
else:
raise ValueError
def tan(self, x,):
number_types = (int, long, float, complex)
if isinstance(x, number_types):
return math.tan(x,)
else:
raise ValueError
|
e5bf6281a63f38d85efa563a4fb6489dc6baa13a | sanddragon2004/python | /menu1.py | 536 | 4.5 | 4 | print "Enter a selection here. This is where you choose what function you want"
selection = raw_input("what is your selection?")
# this is an if statement file
#create a menu that will look at 3 different options and 2 different sub options.
if selection is == "1":
print "do you want to do this function"
#do stuff here!
elif selection is == "2":
print "do you want to do this function instead?"
#do stuff here!
elif selection is == "3":
print "do you want to do this function optionally?"
#do stuff here!
|
18c656d4e69e8c6ee881c0c9a4bd9af8908196c9 | GlenboLake/DailyProgrammer | /C204E_remembering_your_lines.py | 2,868 | 4.21875 | 4 | '''
I didn't always want to be a computer programmer, you know. I used to have
dreams, dreams of standing on the world stage, being one of the great actors
of my generation! Alas, my acting career was brief, lasting exactly as long as
one high-school production of Macbeth. I played old King Duncan, who gets
brutally murdered by Macbeth in the beginning of Act II. It was just as well,
really, because I had a terribly hard time remembering all those lines! For
instance: I would remember that Act IV started with the three witches brewing
up some sort of horrible potion, filled will all sorts nasty stuff, but except
for "Eye of newt", I couldn't for the life of me remember what was in it! Today,
with our modern computers and internet, such a question is easy to settle: you
simply open up the full text of the play and press Ctrl-F (or Cmd-F, if you're
on a Mac) and search for "Eye of newt".
And, indeed, here's the passage:
Fillet of a fenny snake,
In the caldron boil and bake;
Eye of newt, and toe of frog,
Wool of bat, and tongue of dog,
Adder's fork, and blind-worm's sting,
Lizard's leg, and howlet's wing,-
For a charm of powerful trouble,
Like a hell-broth boil and bubble.
Sounds delicious!
In today's challenge, we will automate this process. You will be given the full
text of Shakespeare's Macbeth, and then a phrase that's used somewhere in it.
You will then output the full passage of dialog where the phrase appears.
'''
import re
def get_line_number(lines, phrase):
for row in range(len(lines)):
if lines[row].find(phrase) >= 0:
return row
def get_passage(lines, phrase):
start = get_line_number(lines, phrase)
end = start + 1
while lines[start - 1].startswith(' '):
start -= 1
while lines[end].startswith(' '):
end += 1
passage = '\n'.join(lines[start:end])
speaker = "Spoken by {}:".format(lines[start - 1].strip(' .'))
sceneline = start
while not lines[sceneline].startswith("SCENE"):
sceneline -= 1
scene = lines[sceneline][0:lines[sceneline].index('.')]
actline = sceneline
while not lines[actline].startswith("ACT"):
actline -= 1
act = lines[actline].rstrip('.')
chars = set()
row = sceneline + 1
while not (lines[row].startswith("ACT") or lines[row].startswith("SCENE")):
match = re.match('^ (\w[^.]+)', lines[row])
if match: chars.add(match.group(1))
row += 1
characters = "Characters in scene: " + ', '.join(chars)
return '\n'.join([act, scene, characters, speaker, passage])
macbeth = [row.strip('\n') for row in open('input/macbeth.txt', 'r').readlines()]
# print get_passage(macbeth, 'break this enterprise')
# print get_passage(macbeth, 'Yet who would have thought')
print(get_passage(macbeth, 'rugged Russian bear'))
|
1deabf9dcc2a4f0b6a166c2b1b080249d0e95783 | upasek/python-learning | /string/sum_digit.py | 352 | 4.1875 | 4 | #Write a Python program to compute sum of digits of a given string.
#here x.isdidit() function also we can use
def char(string):
digit = "0123456789"
sum = 0
for m in string:
if m in digit:
sum = sum + int(m)
return sum
string = input("Input the string : ")
print("Sum of digits of a given string :",char(string))
|
63f0257b23344f3b8ea3ba5805cd562ba1c2edd5 | rk385/tathastu_week_of_code | /Day3/program1.py | 132 | 4.34375 | 4 | string=input('enter a string: ')
rev=''
for i in range(len(string)-1,-1,-1):
rev=rev+string[i]
print('reversed string is:',rev)
|
5b2d99e26438acf8182e97293011e245bbfd813e | AmandaCasagrande/Entra21 | /Aula 05/exercicio12.py | 689 | 4.21875 | 4 | # Exercicio 12
#
# Crie um programa que peça 2 números.
#
# Depois mostre um menu interativo contendo 5 operações matemáticas do python
# (adição, subtração, multiplicação, divisão e expoente)
#
# Peça para o usuário escolher uma destas opções e mostre o resultado da operação escolhida.
num1 = int(input("Digite um número: "))
num2 = int(input("Digite outro número: "))
print("\n")
adicao = num1 + num2
subtracao = num1 - num2
multiplicacao = num1 * num2
divisao = num1/num2
expoente = num1 ** num2
print("Adição: ", adicao)
print("Subtração: ", subtracao)
print("Multiplicação: ", multiplicacao)
print("Divisão: ", divisao)
print("Expoente: ", expoente)
|
e7ce6373df103dfcdf397f00e41013eb36aeeacf | Hety06/SNEL | /SNEL/caesar.py | 1,646 | 3.796875 | 4 | def shift(letter, shift_amount):
unicode_value = ord(letter) + shift_amount
if unicode_value > 126:
new_letter = chr(unicode_value - 95)
else:
new_letter = chr(unicode_value)
return new_letter
def encrypt(message, shift_amount):
result = ""
for letter in message:
result += shift(letter, shift_amount)
return result
def decrypt(message, shift_amount):
result = ""
for letter in message:
result += shift(letter, -shift_amount +95)
return result
message = "why is it wrong"
encrypted_message = '!>=.q_i>wMW-j%|A"`A"`GP""Y}P`{ACPw`b7G`:XHHAH}`JXZ`J{`"ZX{{`ZJ`V:AZPw`vP:P7"`"JGP`KFY}Y:A"G`{:JG`*ADAKPOAYa`$z%bj|JGP`82$z%b`YZ`|JGP29`A"`YH`bHZP:HPZqUY"PO`KXUFAI`CJFXHZPP:`IJGKXZAH}`K:JSPIZ`PGKFJNAH}`Z|P`l~b/;`"J{ZVY:P`KFYZ{J:G=`|J"ZPO`UN`Z|P`$KYIP`$IAPHIP"`,YUJ:YZJ:N=`YZ`Z|P`^HACP:"AZN`J{`;YFA{J:HAY=`lP:DPFPN=`AH`Z|P`^HAZPO`$ZYZP"w`$z%b`A"`YH`YI:JHNG`{J:`Z|P`$PY:I|`{J:`zBZ:Yq%P::P"Z:AYF`bHZPFFA}PHIPw`bZ"`KX:KJ"P`A"`ZJ`YHYFNMP`:YOAJ`"A}HYF"=`"PY:I|AH}`{J:`"A}H"`J{`PBZ:Y`ZP::P"Z:AYF`AHZPFFA}PHIP=`YHO`A"`JHP`J{`GYHN`YIZACAZAP"`XHOP:ZYDPH`Y"`KY:Z`J{`$z%bwxPn2B(;G[)(gUudK*Xk'
def count_characters(text, counts):
for c in text:
n = ord(c)
counts[n] += 1
counts = [0] * 127
count_characters(encrypted_message, counts)
max = 0
index = 0
for i in range(0, len(counts)):
if counts[i] > max:
max = counts[i]
index = i
freq = chr(index)
shift2 = (ord(freq) - 32)
decrypted_message = decrypt(encrypted_message, shift2)
print(encrypted_message)
print(decrypted_message)
|
87ae3c79274a7121f93e8f8fc70048d18f301f5b | Haseebvp/Anand-python | /chapter 1&2/triplets.py | 151 | 3.859375 | 4 | #a function triplets
def triplets(a,b):
return [(x,y,x+y) for x in a for y in b if a.index(x)==b.index(y)]
a=range(4)
b=[4,3,2,1]
print triplets(a,b)
|
025ff862069d73033c8a0b965ecfd23d9d87e057 | 01-Jacky/Python-Things | /python_features/generator.py | 1,219 | 4.15625 | 4 | import time
def some_function():
i = 1
while True:
yield i*i
i += 1
x = some_function()
print(next(x))
print(next(x))
print(next(x))
print(next(x))
''
def fibonacci_iterative(n):
a, b = 0, 1
for i in range(0, n):
a, b = b, a + b
return a
def fibonacci_generator():
"""Fibonacci numbers generator"""
a = 0
b = 1
while True:
a, b = b, a + b
yield a
if __name__ == "__main__":
# Fib 400000 iterative
start = time.time()
value = fibonacci_iterative(400000)
end = time.time()
print('Time for fib 400000 iteratively: {}'.format(end-start))
# Fib 400001 iterative
start = time.time()
value = fibonacci_iterative(400001)
end = time.time()
print('Time for fib 400001 iteratively: {}'.format(end-start))
# Fib 400000
start = time.time()
g = fibonacci_generator()
for _ in range(400000):
current_value = next(g)
# print(current_value)
end = time.time()
print('Time for fib 400000 using generator: {}'.format(end-start))
# Fib 400001
start = time.time()
# print(next(g))
end = time.time()
print('Time for fib 400001: {}'.format(end-start))
|
dd6b10f0ce310c0ac70c32f5d473e1e263217259 | Anshnema/Programming-solutions | /balanced_binary_tree.py | 484 | 3.6875 | 4 | """
Ques. Balanced Binary Tree
T.C. = O(n)
S.C. = O(n)
"""
class Solution:
def isBalanced(self, root) -> bool:
def dfs(root):
if(root is None):
return [True, 0]
left = dfs(root.left)
right = dfs(root.right)
balanced = (left[0] and right[0] and abs(left[1] - right[1]) <= 1)
return [balanced, 1 + max(left[1], right[1])]
return dfs(root)[0] |
9e54b27c51872589a0c48a8fd5c36a0ea0307e77 | kopchik/itasks | /round5/epi/18.9_word_stream.py | 397 | 3.953125 | 4 | #!/usr/bin/env python3
#find majority element
def find_majority_elem(stream):
candidate = None
count = 0
for w in stream:
if w == candidate:
count +=1
continue
else:
if count == 0:
count = 1
candidate = w
else:
count -= 1
return candidate
if __name__ == '__main__':
test = "1 2 1 2 2".split()
print(find_majority_elem(test))
|
7335c674baa2c28b0215714e058e8d29c6bb8eb2 | k0malSharma/Competitive-programming | /CHEALG.py | 295 | 3.546875 | 4 | for _ in range(int(input())):
s=input()
st=""
c=1
for i in range(len(s)-1):
if(s[i]==s[i+1]):
c+=1
else:
st+=s[i]+str(c)
c=1
st+=s[len(s)-1]+str(c)
if(len(st)<len(s)):
print("YES")
else:
print("NO")
|
ac5b65e6db3ca8e8ae96f9e411fc3eb542af96c1 | SeanM743/SmallProjects | /longest_pal.py | 1,019 | 3.609375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Thu May 16 19:26:50 2019
@author: snama
"""
def longest_subpalindrome_slice(text):
"Return (i, j) such that text[i:j] is the longest palindrome in text."
if text == '': return (0,0)
text = text.upper()
lens = [grow(text,start,end)
for start in range(len(text))
for end in (start,start+1)]
return max(lens, key = lambda args: args[1]-args[0])
def grow(text,start,end):
while start >0 and end < len(text) and text[start-1] == text[end]:
start -= 1; end +=1
return (start,end)
def test():
L = longest_subpalindrome_slice
assert L('racecar') == (0, 7)
assert L('Racecar') == (0, 7)
assert L('RacecarX') == (0, 7)
assert L('Race carr') == (7, 9)
assert L('') == (0, 0)
assert L('something rac e car going') == (8,21)
assert L('xxxxx') == (0, 5)
assert L('Mad am I ma dam.') == (0, 15)
return 'tests pass'
print(test()) |
aa35d19a5f16255708613b87af3c2c355fbf9066 | agnathomas/Python | /cycle5/rectangle.py | 1,436 | 4.21875 | 4 | class rectangle():
def __init__(self, breadth, length):
self.breadth = breadth
self.length = length
def area(self):
return self.breadth * self.length
def perimeter(self):
return 2 * (self.breadth + self.length)
print("Rectangle1")
a = int(input("Enter length of rectangle1: "))
b = int(input("Enter breadth of rectangle1: "))
obj1= rectangle(a, b)
print("Area of rectangle:", obj1.area())
print("Perimeter of rectangle:", obj1.perimeter())
print("Rectangle2")
a = int(input("Enter length of rectangle2: "))
b = int(input("Enter breadth of rectangle2: "))
obj2= rectangle(a, b)
print("Area of rectangle:", obj2.area())
print("Perimeter of rectangle:", obj2.perimeter())
if obj1.area() > obj2.area():
print("Area of rectangle1 grater than rectangle2")
elif obj1.area() == obj2.area():
print("Area of rectangle1 and rectangle2 are equal")
else:
print("Area of rectangle1 less than rectangle2")
if obj1.perimeter() > obj2.perimeter():
print("Perimeter of rectangle1 grater than rectangle2")
elif obj1.area() == obj2.area():
print("Perimeter of rectangle1 and rectangle2 are equal")
else:
print("Perimeter of rectangle1 less than rectangle2") |
a8f6de10660f6ce44972000773b564db14e470e8 | jjason/RayTracerChallenge | /ray_tracer/patterns/ring.py | 1,630 | 4.25 | 4 | import math
from patterns.pattern import Pattern
class Ring(Pattern):
"""
The ring pattern. A ring pattern has two colors and changes based upon
the x and z coordinates of the point. The color is determined based upon
the distance of the point from the point (x=0, y=?, z=0), i.e., circles
in the xz plane.
+- color_a if floor(distance to xz) mod 2 == 0
color @ point => |
+- color_b otherwise
The color is independent of the y coordinate.
"""
def __init__(self,
color_a=None,
color_b=None,
transform=None):
"""
Initialize the stripe pattern object.
:param color_a: The color between xz distances = [0, 1), [2, 3), [4, 5),
etc. If not provided, default is white.
:param color_b: The color between xz distances = [1, 2), [3, 4), [5, 6),
etc. If not provided, default is black
:param transform: The transform to be applied to the pattern. If None,
then the identity transform is used.
"""
super().__init__(color_a=color_a, color_b=color_b, transform=transform)
def color_at(self, position):
"""
Return the color (a or b) for the position provided. The color is
determined as described above.
:param position: The point for which color is to be determined.
:return: Color, the color for the point.
"""
distance = math.sqrt(position.x ** 2 + position.z ** 2)
return self.color_a if math.floor(distance) % 2 == 0 else self.color_b
|
bd37f4ea222b21e5b66738029501efd8269c47d3 | patchaiy/Python-1 | /pro40.py | 150 | 3.609375 | 4 | st1="dhoni"
st2=input()
val1=list(set(st1)-set(st2))
val2=list(set(st2)-set(st1))
val=len(val1)+len(val2)
if val==0:
print("yes")
else:
print("no")
|
62aba7dfc5a099a2915eaa1b00276f5f0adaf9be | weltonvaz/Primos | /fatorar1.py | 664 | 3.921875 | 4 | #!/usr/bin/python
import os
def cls():
os.system('cls' if os.name=='nt' else 'clear')
cls()
def get_prime_factors(number):
"""
Return prime factor list for a given number
number - an integer number
Example: get_prime_factors(8) --> [2, 2, 2].
"""
if number == 1:
return []
# We have to begin with 2 instead of 1 or 0
# to avoid the calls infinite or the division by 0
for i in range(2, number):
# Get remainder and quotient
rd, qt = divmod(number, i)
if not qt: # if equal to zero
return [i] + get_prime_factors(rd)
return [number]
print(get_prime_factors(42))
|
54ecc643c11545eaee3c64720cbd2a14f99e0527 | palathip/bbb_basic_python | /CH2-Condition/LAB 2-5 EX.py | 3,718 | 3.9375 | 4 |
print"Calculator"
def calculator():
input_1 = input("Enter Input 1 :")
switch = True
st_run = True
while switch:
#input_1 = input("Enter Input 1 :")
operand = raw_input("Enter Operator :")
input_2 = input("Enter Input 2 :")
if operand.lower() == "clear" or operand.lower() == "c": #Recursive // Clear Case
calculator()
if operand.lower() != "exit" or input_1.lower() != "exit" or input_2.lower() != "exit":
if operand == "+" or operand.lower() == "plus": #PLUS Process
if st_run == False:
result = p_sum+input_2
print "%d + %d = %d" % (p_sum, input_2, result)
p_sum = result
elif st_run == True:
result = input_1 + input_2
p_sum = result
print "%d + %d = %d" % (input_1, input_2, result)
st_run = False
elif operand == "-" or operand.lower() == "sub": #SUB Process
if st_run == False:
result = p_sum - input_2
print "%d - %d = %d" % (p_sum, input_2, result)
p_sum = result
elif st_run == True:
result = input_1 - input_2
p_sum = result
print "%d - %d = %d" % (input_1, input_2, result)
st_run = False
elif operand.lower() == "x" or operand.lower() == "mul": #MULTI Process
if st_run == False:
result = p_sum * input_2
print "%d x %d = %d" % (p_sum, input_2, result)
p_sum = result
elif st_run == True:
result = input_1 * input_2
p_sum = result
print "%d x %d = %d" % (input_1, input_2, result)
st_run = False
elif operand == "/" or operand.lower() == "divide": #DIVIDE Process
if st_run == False:
result = (p_sum*1.0) / input_2
print "%d / %d = %f" % (p_sum, input_2, result)
p_sum = result
elif st_run == True:
result = (input_1*1.0) / input_2
p_sum = result
print "%d / %d = %f" % (input_1, input_2, result)
st_run = False
elif operand == "%" or operand.lower() == "mod": # MOD Process
if st_run == False:
result = p_sum % input_2
print "%d / %d = %d" % (p_sum, input_2, result)
p_sum = result
elif st_run == True:
result = input_1 % input_2
print "%d / %d = %d" % (input_1, input_2, result)
p_sum = result
st_run = False
else:
print "Wrong Operator"
else:
switch = False
print ("Calculator End")
exit()
#####Function##### not used
def plusFunction ():
result = p_sum + input_2
print "%d + %d = %d" %(p_sum, num, result)
return result
def subFunction ():
result = p_sum - input_2
print "%d - %d = %d" %(p_sum, num, result)
return result
def mulFunction ():
result = p_sum * input_2
print "%d x %d = %d" %(p_sum, num, result)
return result
def divFunction ():
result = p_sum / input_2
print "%d / %d = %d" %(p_sum, num, result)
return result
def modFuntion ():
result = p_sum % input_2
print "%d mod %d = %d" %(p_sum, num, result)
return result
calculator() |
79ca241b02a85248abc3d4f6335a252219edc1cf | alehatsman/pylearn | /py/lists/insert_sorted.py | 714 | 4.25 | 4 | from lists.linked_list import Node
def insert_sorted(ll, value):
"""
Insert element in sorted linked list.
Find position and replace pointers.
Time complexity: O(N)
Space complexity: O(1)
"""
insert_node = Node(value)
current_node = ll.head
if not current_node:
ll.head = insert_node
return
while current_node:
next_node = current_node.next
if not next_node:
current_node.next = insert_node
return
if value > current_node.value and value < next_node.value:
insert_node.next = current_node.next
current_node.next = insert_node
return
current_node = next_node
|
3acd792dcf4d6510b5989e21ca9eae8d6b9daba8 | tnakaicode/jburkardt-python | /geometry/circles_intersect_area_2d.py | 2,376 | 4.28125 | 4 | #! /usr/bin/env python
#
def circles_intersect_area_2d ( r1, r2, d ):
#*****************************************************************************80
#
## CIRCLES_INTERSECT_AREA_2D: area of the intersection of two circles.
#
# Discussion:
#
# Circles of radius R1 and R2 are D units apart. What is the area of
# intersection?
#
# Licensing:
#
# This code is distributed under the GNU LGPL license.
#
# Modified:
#
# 15 January 2018
#
# Author:
#
# John Burkardt
#
# Parameters:
#
# Input, real R1, R2, the radiuses of the circles.
# R1 and R2 should be positive.
#
# Input, real D, the distance between the circular centers.
# D must be positive, and should be no greater than R1 + R2.
#
# Output, real AREA, the area of the intersection.
#
import numpy as np
from circle_lune_area_by_height_2d import circle_lune_area_by_height_2d
if ( r1 + r2 < d ):
area = 0.0
elif ( d == 0.0 ):
area = np.pi * ( min ( r1, r2 ) ) ** 2
else:
h1 = 0.5 * ( d ** 2 + r1 ** 2 - r2 ** 2 ) / d
area1 = circle_lune_area_by_height_2d ( r1, h1 )
h2 = 0.5 * ( d ** 2 - r1 ** 2 + r2 ** 2 ) / d
area2 = circle_lune_area_by_height_2d ( r2, h2 )
area = area1 + area2
return area
def circles_intersect_area_2d_test ( ):
#*****************************************************************************80
#
## CIRCLES_INTERSECT_AREA_2D_TEST tests CIRCLES_INTERSECT_AREA_2D
#
# Licensing:
#
# This code is distributed under the GNU LGPL license.
#
# Modified:
#
# 15 January 2018
#
# Author:
#
# John Burkardt
#
import numpy as np
ntest = 6
r1_test = np. array ( [ 1.0, 1.0, 1.0, 1.0, 1.0, 1.0 ] )
r2_test = np. array ( [ 0.5, 0.5, 0.5, 1.0, 1.0, 1.0 ] )
d_test = np. array ( [ 1.5, 1.0, 0.5, 1.5, 1.0, 0.0 ] )
print ( '' )
print ( 'CIRCLES_INTERSECT_AREA_2D_TEST' )
print ( ' CIRCLES_INTERSECT_AREA_2D determines the area of the' )
print ( ' intersection of two circes of radius R1 and R2,' )
print ( ' with a distance D between the centers.' )
print ( '' )
print ( ' R1 R2 D Area' )
print ( '' )
for i in range ( 0, ntest ):
r1 = r1_test[i]
r2 = r2_test[i]
d = d_test[i]
area = circles_intersect_area_2d ( r1, r2, d )
print ( ' %6f %6f %6f %6f' % ( r1, r2, d, area ) )
return
if ( __name__ == '__main__' ):
circles_intersect_area_2d_test ( )
|
9ea208216835c0d35e1fe4677044a6cd4a9850b6 | vuminhph/randomCodes | /DataStructure/merge_sorted_linked_lists.py | 1,539 | 4.09375 | 4 | def main():
list1 = Node(1)
list1.insert_last(Node(2))
list1.insert_last(Node(4))
list2 = Node(1)
list2.insert_last(Node(3))
list2.insert_last(Node(4))
print(merge_sorted_lists(list1, list2))
class Node:
def __init__(self, val):
self.value = val
self.next = None
def insert_last(self, node):
if self.next is None:
self.next = node
else:
ptr = self
while ptr.next is not None:
ptr = ptr.next
ptr.next = node
def __repr__(self):
ptr = self
list_str = ''
while ptr is not None:
list_str += str(ptr.value) + ' '
ptr = ptr.next
return list_str
def merge_sorted_lists(head1, head2):
ptr1 = head1
ptr2 = head2
merged_list = None
while ptr1 is not None or ptr2 is not None:
if ptr1 is None:
new_ptr.next = ptr2
break
elif ptr2 is None:
new_ptr.next = ptr1
break
min_value = min(ptr1.value, ptr2.value)
if merged_list is None:
merged_list = Node(min_value)
new_ptr = merged_list
else:
new_ptr.next = Node(min_value)
new_ptr = new_ptr.next
if (min_value == ptr1.value and min_value == ptr2.value) or min_value == ptr1.value:
ptr1 = ptr1.next
else:
ptr2 = ptr2.next
return merged_list
if __name__ == '__main__':
main()
|
e3df69fd0dff76dd7a73c26835902e1b97aeebaa | maze88/rubiks_shuffler_and_timer | /move_class.py | 2,192 | 4.3125 | 4 | """This module contains the class Move, for creating Rubik's cube moves.
For an explanation of Rubik's cube notation checkout the following article
in the Twisty puzzle wiki: https://ruwix.com/the-rubiks-cube/notation/
"""
import random
FACES = ('L', 'R', 'U', 'D', 'F', 'B')
CLOCKWISE_TURNS = (-1, 1, 2) # Negative means anti-clockwise.
class Move:
"""A move on a Rubik's cube. Main properties are face and amount of clockwise turns."""
def __init__(self, input_face=None, input_turns=None):
# Init face (char)
if not input_face:
self.face = random.choice(FACES)
elif input_face in FACES:
self.face = input_face
else:
print('Illegal face chosen for Move object. Please use one from {}.'.format(FACES))
exit()
# Init clockwise_turns (integer)
if not input_turns:
self.clockwise_turns = random.choice(CLOCKWISE_TURNS)
elif input_turns in CLOCKWISE_TURNS:
self.clockwise_turns = input_turns
else:
print('Illegal clockwise turn count chosen for Move object. Please use one from {}.'.format(CLOCKWISE_TURNS))
exit()
# Init direction (string), is_clockwise & is_prime (booleans) and half_turn (string)
self.half_turn = ''
if self.clockwise_turns == -1:
self.direction = '\''
self.is_clockwise = False
elif self.clockwise_turns > 0:
if self.clockwise_turns == 2:
self.half_turn = str(self.clockwise_turns)
self.direction = ''
self.is_clockwise = True
# Assemble the move's name in cube notation (examples: R', F2, U...).
self.name = self.cube_notation = self.face + self.direction + self.half_turn
def is_prime(self):
"""Returns a boolean determining if the move is prime (counter-clockwise)."""
return not self.is_clockwise
def is_similar_to(self, other_move):
"""Returns a boolean stating the move is similar (can cancel out with) to other_move."""
similar = False
if self.face == other_move.face:
similar = True
return similar
|
59df46c65a8f6255d277025f885bed0d948fece0 | zedzijc/advent_2018 | /Day_9/Advent_9a.py | 2,102 | 3.671875 | 4 |
class Marble(object):
def __init__(self, value, previous_marble, next_marble):
self.marble_value = value
self.previous_marble = previous_marble
self.next_marble = next_marble
def set_next(self, next_marble):
self.next_marble = next_marble
def next(self):
return self.next_marble
def set_previous(self, previous_marble):
self.previous_marble = previous_marble
def previous(self):
return self.previous_marble
def value(self):
return self.marble_value
def get_score(players, final_marble_value):
players = [0 for player in range(players)]
marble_value = 1
current_marble = Marble(0, None, None)
current_marble.set_next(current_marble)
current_marble.set_previous(current_marble)
while True:
player_index = 0
while player_index < len(players):
if marble_value % 23 == 0:
bonus_marble = current_marble
bonus_marble_distance = 7
while bonus_marble_distance > 0:
bonus_marble = bonus_marble.previous()
bonus_marble_distance -= 1
bonus_marble.previous().set_next(bonus_marble.next())
bonus_marble.next().set_previous(bonus_marble.previous())
players[player_index] += marble_value
players[player_index] += bonus_marble.value()
current_marble = bonus_marble.next()
else:
new_marble = Marble(marble_value,
current_marble.next(),
current_marble.next().next())
current_marble.next().next().set_previous(new_marble)
current_marble.next().set_next(new_marble)
current_marble = new_marble
if marble_value == final_marble_value:
return max([score for score in players])
marble_value += 1
player_index += 1
if __name__ == "__main__":
print("Winning score: {0}".format(get_score(439, 71307)))
|
47768f5d799434f896b095d07c256c81cbc52501 | KrasilnikovNikita/python | /3-4/array14.py | 190 | 3.796875 | 4 | N = int(input())
a = []
b = []
for i in range(N):
a.append(int(input()))
for i in range(0,N,2):
b.append(a[i])
for i in range(1,N,2):
b.append(a[i])
print(b)
|
82b2d2d234d6eaf7ffb3d9b687286b374d807944 | ruselll1705/home | /home_work3_1.py | 109 | 3.640625 | 4 | import sys
x=int(sys.argv[1])
y=int(sys.argv[2])
if x>y:
s=x-y
elif x<y:
s=x+y
else:
s=x
print(s) |
7ef84646ae3a697a2d581e15770fde5e6e5c2435 | whiterabbitPL/Mateusz | /test.py | 1,616 | 4 | 4 | import unittest
from world import World
class TestWorld(unittest.TestCase):
def test_constructor(self):
# Non-argument constructor is working
w = World()
self.assertEqual(w.world, 'Earth')
# Argument constructor is working
sw = World("Mars")
self.assertEqual(sw.world, 'Mars')
# Wrong argument raising exception
with self.assertRaises(ValueError) as error:
wrong_world = World("sun")
self.assertEqual(str(error.exception), "Don't known planet Sun!")
def test_validator(self):
w = World()
planets = ['Merkury','Venus','Earth','Mars','Jupiter','Saturn','Uranus','Neptune','Ceres','Pluto','Haumea','Makemake','Eris']
# Check if all planets from the list will be correctly validated
for planet in planets:
self.assertTrue(w.validate(planet))
# Check that empty value will be invalidated
self.assertFalse(w.validate(None))
# Check if wrong value will be invalidated
self.assertFalse(w.validate("Sun"))
# Check if not normalized value will be invalidated (expected)
self.assertFalse(w.validate("merkury"))
def test_normalizer(self):
w = World()
self.assertEqual(w.normalize("mars"), "Mars")
self.assertEqual(w.normalize("MARS"), "Mars")
self.assertEqual(w.normalize("mARS"), "Mars")
self.assertEqual(w.normalize("Mars"), "Mars")
self.assertEqual(w.normalize("mArS123"), "Mars123")
def test_printable_descrition(self):
w = World()
aw = World("Jupiter")
self.assertEqual(str(w), "Hello world!")
self.assertEqual(str(aw), "Welcome on Jupiter")
if __name__ == '__main__':
unittest.main() |
fada9cb25504e9898b813dece5d97875a912dc80 | seddon-software/python3 | /Python3/src/_Exercises/src/Basic/ex3-1.py | 277 | 3.921875 | 4 | """
Write a program that prints out the sum, difference, product
and dividend of two complex numbers.
"""
x = 5 + 3j
y = 4 - 2j
print( "sum = ", x + y )
print( "difference = ", x - y )
print( "product = ", x * y )
print( "dividend = ", x / y )
|
85be20cecff931c2831034b14fe262222d069d53 | xiaoyongaa/ALL | /函数和常用模块/装饰器2.py | 413 | 3.921875 | 4 | def outer(fu):
def inner(*args,**kwargs): #原来函数传参几个,装饰器的函数就要要几个传参
print("bro")
R=fu(*args,**kwargs) #取得原函数的返回值
print("after")
return R #原函数的返回值返回给inner
return inner
@outer
def f1(a):
print(a)
return "1111111111"
@outer
def f2(a,b):
print("F2")
return "222222222"
|
af8365520a99e9999d7c2e8422c958dfecce4a31 | wpyzik/motion | /Resizing etc/script1.py | 901 | 3.828125 | 4 | import cv2
#if color = 1, if black and white = 0,3rd parameter -1 = color image bt also alpha channel meaning you have transparency in the image
img=cv2.imread("galaxy.jpg",0)
print(type(img))
print(img)
print(img.shape)
#(1485 rows and 990 columns)
print(img.ndim)
#3 dimensions
cv2.imshow("Galaxy",img)
#it resized imagine in half. The zero index = 1485, 1 index =990
resized_image=cv2.resize(img,(int(img.shape[1]/2),int(img.shape[0]/2)))
#to display image on the screen
#here "Galaxy' is the window name, then what do you wanna show
cv2.imshow("Galaxy",resized_image)
#to specify how long it will be on the screen - if 0, it will close when user clicks any botton, 2000 - 2000mili seconds so 2 seconds
#first you give the new name of the image,then you provide the image you want to store in this file
cv2.imwrite("Galaxy_resized.jpg", resized_image)
cv2.waitKey(2000)
cv2.destroyAllWindows()
|
80fb30a2a9319ca4ff8a0abfd734afa0afac7c5d | shubam-garg/Python-Beginner | /Conditional_Expressions/11_practice_test6.py | 244 | 3.953125 | 4 | # 7) Write a program to find out whether a given post is talking about "Shubam" or not
post="My Name iS ShUbaM"
p=(post.lower())
if("shubam" in p):
print("shubam is present in the post")
else:
print("shubam is not present in the post") |
0bf6fbcaa9b70ecd46b246bf2caa5bdf5fb8913b | xiaomengyu/test | /购物车.py | 1,576 | 3.890625 | 4 | # Time : 2018/3/19 17:35
# Author : Jack
# File : 购物车.py
# Software: PyCharm
product_list = [
('Mac',9000),
('kindle',800),
('tesla',30000),
('python book',110),
('bike',2000),
]
saving = input('please input your saving:')
shopping_car = []
if saving.isdigit():
saving = int(saving)
# for i in product_list:
# print(product_list.index(i)+1,i)
# for i in enumerate(product_list,1): #后面加一个逗号和一个一是参数
# print(i)
while True:
for i,v in enumerate(product_list,1):
print(i,'>>>>>',v)
choice = input('请选择购买的商品编号[退出:q]')
if choice.isdigit():
choice=int(choice)
if choice>0 and choice<=len(product_list):
p_item = product_list[choice-1]
if p_item[1]<saving:
saving -= p_item[1]
shopping_car.append(p_item)
else:
print('余额不足,还剩%s'%saving)
print(p_item)
else:
print('商品编码不存在')
elif choice=='q':
print('------------------您已购买如下商品---------------')
for i in shopping_car:
print(i)
print('您还剩%s元钱'%saving)
break
else:
print('invalid ')
|
838b9c54436f93d1fe28701beb2eababb284f20e | morita657/Algorithms | /Leetcode_solutions/preorderTraversal.py | 1,685 | 3.796875 | 4 | # Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
import collections
class Solution:
def preorderTraversal(self, root: TreeNode) -> List[int]:
if root == None:
return []
output=[]
def search(node, o):
if node == None:
return
else:
o.append(node.val)
if node.left:
search(node.left, o)
if node.right:
search(node.right, o)
output=[root.val]
search(root.left, output)
search(root.right, output)
return output
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
import collections
class Solution:
def preorderTraversal(self, root: TreeNode) -> List[int]:
if root == None:
return []
stack,output =[root],[]
while len(stack)>0:
now = stack.pop()
if now is not None:
output.append(now.val)
if now.right:
stack.append(now.right)
if now.left:
stack.append(now.left)
return output
def inorder(root):
res = []
stack = []
curr = root
while curr is not None or len(stack) > 0:
while curr is not None:
stack.append(curr)
curr = curr.left
curr = stack.pop()
res.append(curr.val)
curr = curr.right
return res |
63b4264d0465379c31487866eaefe2d88e1a5813 | donzpixelz/psychic | /cgi-bin/answer_census.py | 12,114 | 3.578125 | 4 | import pymc as pm
import numpy as np
import pandas as pd
import re
import xml.etree.ElementTree as ET
import urllib2
import sqlite3
import answer as ans
from StringIO import StringIO
from zipfile import ZipFile
#Some helpful functions
def hasNumbers(strings):
'''Returns true if any of the strings in the 'strings' array have a digit in them.'''
for s in strings:
if any(char.isdigit() for char in s):
return True
return False
def dict_to_array(data):
'''Turns a hierarchy of dictionaries into a numpy array
returns:
- the numpy array
- a list of lists of labels (each list records the labels on that dimension)
example:
res, labs = dict_to_array({'aged 3-5':{'males':{'rabbits':3,'dogs':4,'cats':1},'females':{'rabbits':3,'dogs':0,'cats':2}},'aged 0-2':{'males':{'rabbits':4,'dogs':2,'cats':1},'females':{'rabbits':1,'dogs':0,'cats':4}}})
res array([[[1, 4, 2],[4, 1, 0]],[[1, 3, 4],[2, 3, 0]]])
labs [['aged 0-2', 'aged 3-5'], ['males', 'females'], ['cats', 'rabbits', 'dogs']]
'''
res = []
if not isinstance(data,dict):
return data, []
labels = []
for e in data:
if 'Total' not in e:
lower_dict, lower_labels = dict_to_array(data[e])
res.append(lower_dict)
labels.append(e)
if hasNumbers(labels): #automatically sorts labels containing numbers by the numerical value of the first number.
numbers = []
for lab in labels:
numbers.append(re.search(r'\d+', lab).group())
numbers, labels, res = (list(t) for t in zip(*sorted(zip(numbers, labels, res))))
lower_labels.insert(0,labels)
return np.array(res), lower_labels
class CensusAnswer(ans.Answer):
"""Census answer: handles gender & age"""
dataset = 'census';
religions = ['Christian','Buddhist','Hindu','Jewish','Muslim','Sikh','Other religion','No religion']
religion_text = ['Christian','Buddhist','Hindu','Jewish','Muslim','Sikh','religious (but I do\'t know which)','of no religion']
@classmethod
def ONSapiQuery(cls,geoArea, dataSet):
"""Performs an API query to the ONS database, for the given geo area and dataset
The data is stored in 'data' and is also converted into an N-dimensional 'matrix' using a hierarchy of dictionaries."""
pathToONS = 'http://data.ons.gov.uk/ons/api/data/dataset/';
apiKey = 'cHkIiioOQX';
geographicalHierarchy = '2011STATH';
url = ('%s%s/dwn.csv?context=Census&geog=%s&dm/%s=%s&totals=false&apikey=%s' %
(pathToONS,dataSet,geographicalHierarchy,geographicalHierarchy,geoArea,apiKey))
response = urllib2.urlopen(url);
xml_data = response.read();
root = ET.fromstring(xml_data);
href = root[1][0][0].text #TODO: Need to get the path to the href using names not indices.
url = urllib2.urlopen(href);
zipfile = ZipFile(StringIO(url.read()))
for filename in zipfile.namelist():
if (filename[-3:]=='csv'):
#Handle API change
#data = pd.read_csv(zipfile.open(filename),skiprows=np.append(np.array(range(8)),10))
data = pd.read_csv(zipfile.open(filename),skiprows=np.array(range(8)),skipfooter=1,header=0)
#Gets it into a N-dimensional hierarchy of dictionaries
values = data.ix[0,:]
matrix = {}
for col,v in zip(data.columns,values):
c = col.split('~')
if (len(c)>1):
temp = matrix
for ix in range(len(c)):
if ('Total' in c[ix]):
break
if c[ix] in temp:
temp = temp[c[ix]]
else:
if ix==len(c)-1:
temp[c[ix]] = v
else:
temp[c[ix]] = {}
temp = temp[c[ix]]
return data, matrix
@classmethod
def getAgeDist(cls,geoArea,returnList):
"""Gets the age distribution given the label of a particular geographical area"""
data, matrix = cls.ONSapiQuery(geoArea,'QS103EW') #QS103EW = age by year...
data = data.T
popages = data[0].values[3:]
# return popages
returnList[0] = popages #now return via the argument so this can be called as a thread
@classmethod
def getReligionDist(cls,geoArea,returnList):
"""Gets the religion distribution given the label of a particular geographical area"""
data,mat = cls.ONSapiQuery(geoArea,'LC2107EW') #LC2107EW = religion by age, gender, etc
arr,labs = dict_to_array(mat) #Convert the dictionary hierarchy to a numpy array
order = [[i for i,l in enumerate(labs[2]) if l==r][0] for r in cls.religions] #sort religion by the order we want it in.
arr = np.array(arr) #convert to numpy array
arr = arr[:,:,order] #put religions in correct order.
arr = arr * 1.0
for x in range(arr.shape[0]):
for y in range(arr.shape[1]):
arr[x,y,:] += 1.0
arr[x,y,:] = 1.0*arr[x,y,:] / np.sum(1.0*arr[x,y,:])
#gender is sorted by 'male', 'female', age by numerical-order and religion as specified in the cls.religions vector
returnList[0] = arr #now return via the argument so this can be called as a thread
def __init__(self,name,dataitem,itemdetails,answer=None):
"""Constructor, instantiate an answer...
Args:
name: The name of this feature
dataitem: 'agegender'
itemdetails: None
answer=None
"""
self.dataitem = dataitem
self.itemdetails = itemdetails
self.featurename = name
self.answer = answer
def question_to_text(self):
return "No questions"
def calc_probs_religion(self,facts):
if 'where' in facts:
oas = facts['where']['OAs']
else:
oas = ['K04000001'] #don't know where we are, just use whole of England and Wales to get a prior.
from threading import Thread
threadData = []
threads = []
# oas.append('K04000001') #last OA is whole of England+Wales #DON'T NEED THAT HERE
for oa in oas:
data = [0]
threadData.append(data)
t = Thread(target=CensusAnswer.getReligionDist,args=(oa,data))
threads.append(t)
t.start()
for t in threads:
t.join()
localDists = [td[0] for td in threadData[:-1]]
shape = localDists[0].shape
#self.rel_probs = np.empty((len(localDists),shape[0],shape[1],shape[2],2))
self.rel_probs = np.empty((len(localDists),shape[0],shape[1],shape[2]))
for i,p in enumerate(localDists):
#self.rel_probs[i,:,:,:,0] = 1-p
#self.rel_probs[i,:,:,:,1] = p
self.rel_probs[i,:,:,:] = p
#Probabilities are p(religion|outputarea,gender,age)
#organised as: [oa,genderi,agei,religioni]
#so sum[0,0,0,:,1]=1
def calc_probs_age(self,facts):
if 'where' in facts:
oas = facts['where']['OAs']
else:
# print "WARNING: WE DON'T KNOW ANY GEOGRAPHICAL INFORMATION" ##DELETE
oas = ['K04000001'] #don't know where we are, just use whole of England and Wales to get a prior.
from threading import Thread
threadData = []
threads = []
oas.append('K04000001') #last OA is whole of England+Wales
for oa in oas:
# print "Starting thread: %s" % oa
data = [0]
threadData.append(data)
t = Thread(target=CensusAnswer.getAgeDist,args=(oa,data))
threads.append(t)
t.start()
for t in threads:
t.join()
localAgeDists = [td[0] for td in threadData[:-1]]
nationalAgeDist = threadData[-1][0]
#we want p(postcode|age), which we assume is equal to p(output area|age)
#if n = number of people in output area
# N = number of people
# na = number of people of age a in output area
# Na = number of people of age a
#
#p(output area|age) = p(age|output area) x p(output area) / p(age)
#
#we can write the three terms on the right as:
#
#p(age|output area) = na/n
#p(output area) = n/N
#p(age) = Na/N
#
#substituting in... na/n x n/N / (Na/N) = (na/N) / (Na/N) = na/Na
#so localAgeDist/nationalAgeDist
# print "API queries complete..."
self.age_probs = np.zeros([101,len(localAgeDists),2]) #age, in or not in the output area
for i,dist in enumerate(localAgeDists):
p = (0.0001+dist)/nationalAgeDist
self.age_probs[:,i,0] = 1-p
self.age_probs[:,i,1] = p
def get_pymc_function_age(self,features):
"""Returns a function for use with the pyMC module:
Args:
features (dictionary): Dictionary of pyMC probability distributions.
Returns:
function (@pm.deterministic): outputs probability given the parameters.
"""
probs = self.age_probs
@pm.deterministic
def givenAgeGender(age=features['factor_age'],oa=features['oa']):
pAgeGender = probs
return pAgeGender[age,oa]
return givenAgeGender
def get_pymc_function_religion(self,features):
probs = self.rel_probs
@pm.deterministic
def givenReligion(age=features['factor_age'],oa=features['oa'],gender=features['factor_gender']):
pReligion = probs
#the religion dataset is only split into a few bins of age, so handling that here:
if (age<16):
age_p = 0
elif (age<25):
age_p = 1
elif (age<35):
age_p = 2
elif (age<50):
age_p = 3
elif (age<65):
age_p = 4
elif (age<75):
age_p = 5
else:
age_p = 6
return pReligion[oa,gender,age_p]
return givenReligion
def append_features(self,features,facts):
"""Alters the features dictionary in place, adds:
- age
- gender
- this instance's feature
Args:
features (dictionary): Dictionary of pyMC probability distributions.
Raises:
DuplicateFeatureException: If an identically named feature already exists that clashes with this instance
"""
#age: 0-100
self.calc_probs_age(facts)
self.calc_probs_religion(facts)
if not 'factor_age' in features:
p = np.ones(101) #flat prior
p = p/p.sum()
features['factor_age'] = pm.Categorical('factor_age',p);
if not 'oa' in features:
if 'where' in facts:
p = facts['where']['probabilities'] #prior is weighted by how likely each OA is
p = p/p.sum() #not necessary.
# print facts['where']
features['oa'] = pm.Categorical('oa',p);
else:
features['oa'] = pm.Categorical('oa',np.array([1]));
if self.featurename+"_age" in features:
raise DuplicateFeatureException('The "%s" feature is already in the feature list.' % self.featurename+"_age");
if "religion" in features:
raise DuplicateFeatureException('The "%s" feature is already in the feature list.' % "religion");
features[self.featurename+"_age"]=pm.Categorical(self.featurename+"_age", self.get_pymc_function_age(features), value=True, observed=True)
features["religion"]=pm.Categorical("religion", self.get_pymc_function_religion(features)) #, value=True, observed=False)
@classmethod
def pick_question(self,questions_asked):
return 'None','agegender'
|
46d04e00b89e2417b35d2f86602f464acf0a2d12 | miguelex/Universidad-Python | /POO/lee_archivo.py | 527 | 3.515625 | 4 | archivo = open("prueba.txt", "r")
#print(archivo.read())
#Leer algunos caracteres
#print(archivo.read(5)) #Si no comento el print anterior no se me mostrara nada porque ya leyo el archivo
#print(archivo.read(3))
#Leer lienas completas. Tengo que comenbtar lo anterior
#print(archivo.readline())
#print(archivo.readline())
#for linea in archivo:
# print(linea)
#print(archivo.readlines())
#print(archivo.readlines()[1])
archivo2 = open("copia.txt", "w")
archivo2.write(archivo.read())
archivo2.close()
archivo.close() |
e7c8230bdfd5b25a563b9bdba2a9ca1ac4a33ec1 | BlakeERichey/University-Projects | /Python/Library Repo/BTree.py | 3,346 | 4.125 | 4 | ##Blake Richey
#Used to create a binary tree that is sorted
#when a value is added to the binary tree that already exists in the tree,
#that value is always added to the right of the corresponding node
class BTNode():
def __init__(self, val):
self.data = val
self.left = None
self.right = None
def getData(self):
return self.data
def getLeft(self):
return self.left
def getRight(self):
return self.right
def setLeft(self, newVal):
self.left = BTNode(newVal)
def setRight(self, newVal):
self.right = BTNode(newVal)
def isLeaf(self):
return self.left == None and self.right == None
class BTree():
def __init__(self, rootNode):
self.root = (None, rootNode)[rootNode != None]
def getRoot(self):
return self.root
def setRoot(self, Node):
self.root = Node
#inserts a node that contains `val`
def insert(self, val):
if self.root == None:
self.root=BTNode(val)
else:
currentNode = self.helperAddNode(self.root, val)
if val > currentNode.getData(): #add to right of node
currentNode.setRight(BTNode(val))
elif val < currentNode.getData(): #add to left of node
currentNode.setLeft(BTNode(val))
elif val == currentNode.getData(): #node has same value
tempNode = BTNode(val)
if currentNode.getRight():
tempNode.setRight(currentNode.getRight())
currentNode.setRight(tempNode)
else:
currentNode.setRight(tempNode)
#gets node to insert onto, returns node
def helperAddNode(self, currentNode, val):
if(currentNode.getData() > val): #go left
if(currentNode.isLeaf() or currentNode.getLeft() == None):
return currentNode
else:
return self.helperAddNode(currentNode.getLeft(), val)
elif(currentNode.getData() < val): #go right
if(currentNode.isLeaf() or currentNode.getRight() == None):
return currentNode
else:
return self.helperAddNode(currentNode.getRight(), val)
elif(currentNode.getData() == val): #adding existing value
return currentNode
#prints entire tree using inorder traversal
def inorder(self):
self.helperInorder(self.root)
print('')
#to get whole tree call using root as tempNode
def helperInorder(self, tempNode):
if not tempNode:
return
self.helperInorder(tempNode.getLeft())
print(tempNode.getData(), end = ' ')
self.helperInorder(tempNode.getRight())
#returns true if val is contained in binary tree
def contains(self, val):
node = self.find(val)
if node != None:
return True
return False
#returns Node that contains val as its `data` field using entire tree
def find(self, val):
return self.helperFind(self.root, val)
#returns node of tree that contains `val`
def helperFind(self, currentNode, val):
#---exit conditions---
if currentNode == None:
return None
if currentNode.isLeaf():
if currentNode.getData() == val:
return currentNode
else:
return None
#continue searching
data = currentNode.getData()
if data == val:
return currentNode
else:
if data > val:
return self.helperFind(currentNode.getLeft(), val)
elif data < val:
return self.helperFind(currentNode.getRight(), val) |
2fde6515a4576929b0d26bf44695af803752f23e | lukasbasista/Daily-coding-problem | /012/main.py | 1,140 | 4.375 | 4 | """
This problem was asked by Amazon.
There exists a staircase with N steps, and you can climb up either 1 or 2 steps at a time. Given N, write a function
that returns the number of unique ways you can climb the staircase. The order of the steps matters.
For example, if N is 4, then there are 5 unique ways:
1, 1, 1, 1
2, 1, 1
1, 2, 1
1, 1, 2
2, 2
What if, instead of being able to climb 1 or 2 steps at a time, you could climb any number from a set of positive
integers X? For example, if X = {1, 3, 5}, you could climb 1, 3, or 5 steps at a time.
"""
def factorial(x):
if x == 0 or x == 1:
return 1
return x * factorial(x-1)
def comb(n, k):
return factorial(k) / (factorial(k - n) * factorial(n))
def foo(n):
if n == 0:
return 0
if n == 1:
return 1
count = 1
for i in range(1, n//2 + 1):
md = n - (i * 2)
count += comb(i, i + md)
return round(count)
def foo2(n, X):
s = [0 for _ in range(n + 1)]
s[0] = 1
for i in range(1, n + 1):
s[i] += sum(s[i - x] for x in X if i - x >= 0)
return s[n]
print(foo(7))
print(foo2(4, [1,2,3]))
|
f267c1c2904f7d62803a7189c6d14da9f946190d | kenzzuli/hm_15 | /01-04_python基础/08_面向对象基础/hm_05_初始化方法.py | 261 | 3.703125 | 4 | class Cat:
def __init__(self):
print("调用初始化方法")
self.name = "Tom"
def eat(self):
print("%s eats fish" % self.name)
# 创建对象时,会自己调用初始化方法__init__
tom = Cat()
print(tom.name)
tom.eat()
|
7ddbdf6c2df16cbe246732592edef367fa162c47 | matheustxaguiar/Programming-Period-1 | /apnp23.py | 1,487 | 3.90625 | 4 | #C:\Users\mathe\PycharmProjects\exerciciosifes\venv
# -*- coding: utf-8 -*-
#
# apnp23.py
#
# Copyright 2021
# Autor: Matheus Teixeira de Aguiar
# Matricula: 20202BSI0322
#
# Este programa:
# a) Definir uma função em Python 3 que calcule o valor do máximo divisor comum (mdc) entre dois números inteiros
# positivos. Esta função recebe como parâmetro dois números inteiros positivos e retorna o valor do mdc calculado.
# Para realizar o cálculo do máximo divisor comum entre dois números utilize o algoritmo de Euclides.
# b) Faça um programa principal que leia 25 conjuntos com 3 números inteiros positivos. Para cada conjunto de três
# números lidos, imprima os números lidos na ordem em que foram lidos e o valor do mdc calculado. A saída deste
# programa deverá ser EXATAMENTE conforme o modelo apresentado nos casos de teste abaixo.
# c) Invocar o programa principal.
###########################
#Código fonte em Python 3
###########################
#Declaração de variáveis
# Programa principal - arquivo 2
# função com o programa principal
import moduloapnp23
def main():
#Declaração de Variáveis
n = int()
#Processamento
for i in range(0, 25):
num1 = int(input())
num2 = int(input())
num3 = int(input())
mdc1 = moduloapnp23.mdc(num1, num2)
n = moduloapnp23.mdc2(mdc1, num3)
#Saida de Dados
print("MDC(%d, %d, %d)=%d" % (num1, num2, num3, n))
if __name__ == "__main__":
main()
#fim
|
99c73ffcaf830b9812f86b71899b9bf144d83423 | joelburton/bst-practice | /contains.py | 1,118 | 3.65625 | 4 | """Does binary search tree contain node?"""
from bst import bst
def contains(node, val):
"""Does tree starting at node contain node with val?
>>> contains(bst, 5)
True
>>> contains(bst, 1)
True
>>> contains(bst, 2)
False
>>> contains(bst, 6)
True
"""
while node is not None:
if node.data == val:
return True
if val < node.data:
node = node.left
else:
node = node.right
return False
def rcontains(node, val):
"""Does tree starting at node contain node with val?
>>> rcontains(bst, 5)
True
>>> rcontains(bst, 1)
True
>>> rcontains(bst, 2)
False
>>> rcontains(bst, 6)
True
"""
if node is None:
return False
if node.data == val:
return True
if val < node.data:
return rcontains(node.left, val)
else:
return rcontains(node.right, val)
if __name__ == "__main__":
import doctest
if doctest.testmod().failed == 0:
print "w00t!" |
4fad63f4fabfcd86e643ab9d497ef25ee0599086 | dualfame/YZUpython | /0506 lesson 5/def 7.py | 232 | 3.796875 | 4 | # 高階函數 advenced function
def add(x):
return x + 1
def subs(x):
return x - 1
def adv_func(func, x):
return func(x)
x = 20
x = adv_func(add, x)
print(x)
z = [add, subs]
for z in func:
print(adv_func(z, x))
|
c65ba04bf422f4b174f3afd1541cf125a94ef03d | Aasthaengg/IBMdataset | /Python_codes/p02660/s248987384.py | 608 | 3.53125 | 4 | def prime_factorize(n):
a = []
while n % 2 == 0:
a.append(2)
n //= 2
f = 3
while f * f <= n:
if n % f == 0:
a.append(f)
n //= f
else:
f += 2
if n != 1:
a.append(n)
return a
dum = prime_factorize(int(input()))
dum_len = len(dum)
num = 0
ans = 0
cnt = 0
check = 0
for i in range(dum_len):
if num == dum[i]:
cnt += 1
if cnt >= check:
check += 1
ans += 1
cnt = 0
else:
num = dum[i]
ans += 1
cnt = 0
check = 2
print(ans) |
90d70a86e0d75329c0e2b784f779c84a0dd440f7 | VineeshaKasam/Leetcode | /isPalindromeLL.py | 667 | 3.96875 | 4 | '''
Given a singly linked list, determine if it is a palindrome.
Example 1:
Input: 1->2
Output: false
'''
# Definition for singly-linked list.
class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
class Solution(object):
def isPalindrome(self, head):
strs = []
while head:
strs.append(head.val)
head = head.next
if strs == [] or len(strs) == 1:
return True
i = 0
j = len(strs) - 1
while i <= len(strs) / 2:
if strs[i] != strs[j]:
return False
i += 1
j -= 1
return True
|
3c2ca7c14755331e1ea8b7eccb82a29db99daf07 | EricMontague/Leetcode-Solutions | /medium/problem_63_unique_paths_2.py | 3,648 | 3.890625 | 4 | """This file contains my solutions to Leetcode problem 63: Unique Paths 2."""
# Bottom Up Solution more space efficient
# time complexity: O(mn), where 'm' is the number of rows and 'n'
# is the number of columns
# space complexity: O(m)
class Solution:
def uniquePathsWithObstacles(self, grid: List[List[int]]) -> int:
if not grid:
return 0
num_rows = len(grid)
num_cols = len(grid[0])
if grid[num_rows - 1][num_cols - 1] == 1:
return 0
num_paths = [0] * num_cols
num_paths[-1] = 1
for row in range(num_rows -1, -1, -1):
for col in range(num_cols - 1, -1, -1):
if grid[row][col] == 1:
num_paths[col] = 0
elif col < num_cols - 1:
num_paths[col] += num_paths[col + 1]
return num_paths[0]
# Bottom Up Solution
# time complexity: O(mn), where 'm' is the number of rows and 'n'
# is the number of columns
# space complexity: O(mn)
class Solution:
def uniquePathsWithObstacles(self, grid: List[List[int]]) -> int:
if not grid:
return 0
num_rows = len(grid)
num_cols = len(grid[0])
if grid[num_rows - 1][num_cols - 1] == 1:
return 0
num_paths = [[-1] * num_cols for row in range(num_rows)]
for row in range(num_rows - 1, -1, -1):
for col in range(num_cols - 1, -1, -1):
# Base case
if row == num_rows - 1 and col == num_cols - 1:
num_paths[row][col] = 1
# Obstacle
elif grid[row][col] == 1:
num_paths[row][col] = 0
# Last row
elif row == num_rows - 1:
num_paths[row][col] = num_paths[row][col + 1]
# Last column
elif col == num_cols - 1:
num_paths[row][col] = num_paths[row + 1][col]
else:
num_paths[row][col] = (
num_paths[row + 1][col]
+ num_paths[row][col + 1]
)
return num_paths[0][0]
# time complexity: O(mn), where 'm' is the number of rows and 'n'
# is the number of columns
# space complexity: O(mn)
class Solution:
def uniquePathsWithObstacles(self, grid: List[List[int]]) -> int:
if not grid:
return 0
num_rows = len(grid)
num_cols = len(grid[0])
num_paths = [[-1] * num_cols for row in range(num_rows)]
return self.count_unique_paths(
(0, 0),
(num_rows - 1, num_cols - 1),
grid,
num_paths
)
def count_unique_paths(self, current, dest, grid, num_paths):
if not self.is_valid_cell(current, grid):
return 0
row, col = current
if num_paths[row][col] >= 0:
return num_paths[row][col]
if grid[row][col] == 1:
paths = 0
elif current == dest:
paths = 1
else:
paths = (
self.count_unique_paths((row + 1, col), dest, grid, num_paths)
+ self.count_unique_paths((row, col + 1), dest, grid, num_paths)
)
num_paths[row][col] = paths
return paths
def is_valid_cell(self, current_cell, grid):
row, col = current_cell
num_rows = len(grid)
num_cols = len(grid[0])
if (
row >= num_rows
or row < 0
or col >= num_cols
or col < 0
):
return False
return True |
9447091ef7de3195b13ae90fa8bb0d02151ed219 | bitwoman/curso-em-video-python | /Curso de Python 3 - Mundo 3 - Estruturas Compostas/#078.py | 927 | 4.09375 | 4 | # Exercício Python 078: Faça um programa que leia 5 valores numéricos e guarde-os em uma lista.
# No final, mostre qual foi o maior e o menor valor digitado e as suas respectivas posições na lista.
randomNumbers = []
bigger = smaller = 0
for n in range(0,5):
number = int(input('Enter a number: '))
randomNumbers.append(number)
for n in range(0, len(randomNumbers)):
if randomNumbers[n] > 0:
if randomNumbers[n] == 1:
bigger = randomNumbers[n]
smaller = randomNumbers[n]
else:
if randomNumbers[n] > bigger:
bigger = randomNumbers[n]
if randomNumbers[n] < smaller:
smaller = randomNumbers[n]
indexBigger = randomNumbers.index(bigger, 0, len(randomNumbers))
indexSmaller = randomNumbers.index(smaller, 0, len(randomNumbers))
print(f'\nBigger number: {bigger} and his position: {indexBigger}')
print(f'Smaller number: {smaller} and his position: {indexSmaller}')
|
01fca0a0da3e619c8742e75be677835b6d9d0386 | GefestLAB/pyrex | /pyrex/earth_model.py | 3,676 | 3.546875 | 4 | """
Module containing earth model functions.
The earth model uses the Preliminary Earth Model (PREM) for density as a
function of radius and a simple integrator for calculation of the slant
depth along a straight path through the Earth.
"""
import logging
import numpy as np
logger = logging.getLogger(__name__)
EARTH_RADIUS = 6371.0e3 # meters
def prem_density(r):
"""
Calculates the Earth's density at a given radius.
Density from the Preliminary reference Earth Model (PREM). Supports passing
an array of radii or a single radius.
Parameters
----------
r : array_like
Radius (m) at which to calculate density.
Returns
-------
array_like
Density (g/cm^3) of the Earth at the given radii.
Notes
-----
The density calculation is based on the Preliminary reference Earth Model
[1]_.
References
----------
.. [1] A. Dziewonski & D. Anderson, "Preliminary reference Earth model."
Physics of the Earth and Planetary Interiors **25**, 297–356 (1981). :doi:`10.1016/0031-9201(81)90046-7`
"""
r = np.array(r)
return np.piecewise(
r/EARTH_RADIUS,
(r < 1221.5e3,
(1221.5e3 <= r) & (r < 3480.0e3),
(3480.0e3 <= r) & (r < 5701.0e3),
(5701.0e3 <= r) & (r < 5771.0e3),
(5771.0e3 <= r) & (r < 5971.0e3),
(5971.0e3 <= r) & (r < 6151.0e3),
(6151.0e3 <= r) & (r < 6346.6e3),
(6346.6e3 <= r) & (r < 6356.0e3),
(6356.0e3 <= r) & (r < 6368.0e3),
(6368.0e3 <= r) & (r < EARTH_RADIUS)),
(lambda x: 13.0885 - 8.8381 * (x**2),
lambda x: 12.5815 - x * (1.2638 + x * (3.6426 + x * 5.5281)),
lambda x: 7.9565 - x * (6.4761 - x * (5.5283 - x * 3.0807)),
lambda x: 5.3197 - x * 1.4836,
lambda x: 11.2494 - x * 8.0298,
lambda x: 7.1089 - x * 3.8045,
lambda x: 2.691 + x * 0.6924,
2.9,
2.6,
1.02,
0) # Last value is used if no conditions are met (r >= EARTH_RADIUS)
)
def slant_depth(angle, depth, step=500):
"""
Calculates the material thickness of a chord cutting through Earth.
Integrates the Earth's density along the chord. Uses the PREM model for
density.
Parameters
----------
angle : float
Nadir angle (radians) of the chord's direction.
depth : float
(Positive-valued) depth (m) of the chord endpoint.
step : float, optional
Step size (m) for the integration.
Returns
-------
float
Material thickness (g/cm^2) along the chord starting from `depth` and
passing through the Earth at `angle`.
See Also
--------
prem_density : Calculates the Earth's density at a given radius.
"""
# Starting point (x0, z0)
x0 = 0
z0 = EARTH_RADIUS - depth
# Find exit point (x1, z1)
if angle==0:
x1 = 0
z1 = -EARTH_RADIUS
else:
m = -np.cos(angle) / np.sin(angle)
a = z0-m*x0
b = 1+m**2
if angle<0:
x1 = -m*a/b - np.sqrt(m**2*a**2/b**2 - (a**2 - EARTH_RADIUS**2)/b)
else:
x1 = -m*a/b + np.sqrt(m**2*a**2/b**2 - (a**2 - EARTH_RADIUS**2)/b)
z1 = z0 + m*(x1-x0)
# Parameterize line integral with t from 0 to 1, with steps just under the
# given step size (in meters)
l = np.sqrt((x1-x0)**2 + (z1-z0)**2)
ts = np.linspace(0, 1, int(l/step)+2)
xs = x0 + (x1-x0)*ts
zs = z0 + (z1-z0)*ts
rs = np.sqrt(xs**2 + zs**2)
rhos = prem_density(rs)
x_int = np.trapz(rhos*(x1-x0), ts)
z_int = np.trapz(rhos*(z1-z0), ts)
return 100 * np.sqrt(x_int**2 + z_int**2)
|
69aea9de4c459e07655126c034f377972a2eb40b | Vanditg/Leetcode | /Best_Time_Buy_Sell_Stock_II/EfficientSolution.py | 1,721 | 3.984375 | 4 | ##==================================
## Leetcode
## Student: Vandit Jyotindra Gajjar
## Year: 2020
## Problem: 122
## Problem Name: Best Time to Buy and Sell Stock II
##===================================
#
#Say you have an array prices for which the ith element is the price of a given stock on day i.
#
#Design an algorithm to find the maximum profit.
#You may complete as many transactions as you like
#(i.e., buy one and sell one share of the stock multiple times).
#
#Note: You may not engage in multiple transactions at the same time
#(i.e., you must sell the stock before you buy again).
#
#Example 1:
#
#Input: [7,1,5,3,6,4]
#Output: 7
#Explanation: Buy on day 2 (price = 1) and sell on day 3 (price = 5), profit = 5-1 = 4.
# Then buy on day 4 (price = 3) and sell on day 5 (price = 6), profit = 6-3 = 3.
#Example 2:
#
#Input: [1,2,3,4,5]
#Output: 4
#Explanation: Buy on day 1 (price = 1) and sell on day 5 (price = 5), profit = 5-1 = 4.
# Note that you cannot buy on day 1, buy on day 2 and sell them later, as you are
# engaging multiple transactions at the same time. You must sell before buying again.
#Example 3:
#
#Input: [7,6,4,3,1]
#Output: 0
#Explanation: In this case, no transaction is done, i.e. max profit = 0.
class Solution:
def maxProfit(self, prices):
tmp = 0 #Initialze tmp
for i in range(1, len(prices)): #Loop through prices from 1 to prices
if prices[i - 1] < prices[i]: #Condition-check: If price[i-1] is less than price[i]
tmp += (prices[i] - prices[i-1]) #We update tmp by adding tmp and difference of price from i to i-1 untill we reach the end of array
return tmp #We return tmp which is max Profit |
16fbb6af6eef35d2af3b8d192509546150d23750 | raf-espanol/pythonTest | /d2.py | 294 | 3.75 | 4 | import os
list=['dog','cat','frog','turtle','cat','frog','cat','dove']
def countwords(list):
dict={}
for i in range(len(list)):
if list[i] in dict.keys():
dict[list[i]]+=1
else:
dict[list[i]]=1
for k,v in dict.items():
print "%d,%s" % (v, k)
countwords(list)
|
4b6aed931e00a0f2d01433019df20ef6765e3626 | argysamo/InvertedIndex | /Map.py | 1,101 | 3.609375 | 4 | #!/usr/bin/python
"""This Map is written using Python iterators and generators for better performance."""
import sys, os
def read_input(file):
for line in file:
#delete spaces from line
line = line.strip()
# split the line into words
yield line.split()
def getFileName():
# I use configuration variables of hadoop to determine
# The name of the file that Map is processing
if 'map_input_file' in os.environ:
return os.environ['map_input_file'].split("/")[-1]
else:
return 'none'
def main(separator='\t'):
# input comes from standard input
data = read_input(sys.stdin)
try:
for words in data:
# write the results to standard output
# tab-delimited
# Before printing I remove some useless characters
for word in words:
word = filter(lambda x: x not in "\n|~()!;.,-\'\#_\"{}[]*$@%^&",word)
if word :
print '%s%s%s' % (word.strip("\n"), separator, getFileName().strip("\n"))
except:
pass
if __name__ == "__main__":
main()
|
810ef9c57dca05962762f386a2455ad576e70a92 | MarthaSamuel/foundation | /areacalculations.py | 524 | 4.125 | 4 | # Author: Dimgba Martha O
# @martha_samuel_
# 03 finding area of a rectangle
length = 10
width = 2
Area = length * width
print('The area of the rectangle is ' + str(Area))
# finding sum of two areas using definitions
def area_triangle(base, height):
return base * height / 2
area_a = area_triangle(5, 4)
area_b = area_triangle(7, 3)
sum_area = area_a + area_b
print('The sum of both areas are : ' + str(sum_area))
# Area of a cirle
def area_circle(radius):
pi = 3.14
return pi*(radius**2)
print(area_circle(5))
|
bc926b95d2e450f384c167a83bd0c78b3e42d4ab | OlegSudakov/Programming-Problems | /hackerrank/coding_interview/strings_anagrams.py | 733 | 3.765625 | 4 | # https://www.hackerrank.com/challenges/ctci-making-anagrams
def number_needed(a, b):
aLetters = {}
bLetters = {}
for char in a:
if char in aLetters:
aLetters[char] += 1
else:
aLetters[char] = 1
for char in b:
if char in bLetters:
bLetters[char] += 1
else:
bLetters[char] = 1
dif = 0
for char in aLetters:
if char in bLetters:
dif += abs(aLetters[char] - bLetters[char])
else:
dif += aLetters[char]
for char in bLetters:
if char not in aLetters:
dif += bLetters[char]
return dif
a = input().strip()
b = input().strip()
print(number_needed(a, b))
|
5ee64f70940ee4abc0f91b68a4f5cd2edd161a03 | akimi-yano/algorithm-practice | /lc/review2_718.MaximumLengthOfRepeatedSubarr.py | 1,383 | 3.734375 | 4 | # 718. Maximum Length of Repeated Subarray
# Medium
# 4714
# 114
# Add to List
# Share
# Given two integer arrays nums1 and nums2, return the maximum length of a subarray that appears in both arrays.
# Example 1:
# Input: nums1 = [1,2,3,2,1], nums2 = [3,2,1,4,7]
# Output: 3
# Explanation: The repeated subarray with maximum length is [3,2,1].
# Example 2:
# Input: nums1 = [0,0,0,0,0], nums2 = [0,0,0,0,0]
# Output: 5
# Constraints:
# 1 <= nums1.length, nums2.length <= 1000
# 0 <= nums1[i], nums2[i] <= 100
# This solution works:
class Solution:
def findLength(self, nums1: List[int], nums2: List[int]) -> int:
if len(nums1) > len(nums2):
nums1, nums2 = nums2, nums1
def helper(size):
nonlocal nums1, nums2
subarrays = set([])
for i in range(len(nums1) - size + 1):
subarray = nums1[i:i+size]
subarrays.add(tuple(subarray))
for i in range(len(nums2) - size + 1):
subarray = nums2[i:i+size]
if tuple(subarray) in subarrays:
return True
return False
left, right = 0, len(nums1)
while left < right:
mid = (left + right + 1) // 2
if helper(mid):
left = mid
else:
right = mid - 1
return left |
3484c9805ea5cc1e06f9b3e2760064c36995503e | UB68DF/pythontrainings | /listcomprehension.py | 425 | 3.953125 | 4 | #list comprehension
list = []
for letter in 'word':
list.append(letter)
print(list)
print('\n')
list = [letter for letter in 'word']
print(list)
print('\n')
list1 = [x**3 for x in range(1,11)]
print(list1)
print('\n')
list2 = [number for number in range(1,11) if number%2 == 1]
print(list2)
celsius = [-10,-5,0, 10, 20,40,50,60,70,100]
farenhiet = [((number*9/5.0) + 32) for number in celsius]
print(farenhiet)
|
9d170cd340ce40b26668a11103b38355c8c93007 | eBetcel/contact-list-linked-list | /main.py | 1,319 | 3.953125 | 4 | from Contact import Contact
from LinkedList import LinkedList
from Node import Node
import os
if __name__ == "__main__":
aux = -1
new_list = LinkedList()
while(aux != 0):
aux = int(input("1 - Add contact\n2 - Delete contact by name\n3 - Delete contact by index\n4 - Show Phone Book\n0 - Exit\n"))
if(aux == 1):
os.system('cls' if os.name == 'nt' else 'clear')
name = input("Insert name: ")
number = int(input("Insert number: "))
new_list.append(Contact(number, name))
os.system('cls' if os.name == 'nt' else 'clear')
elif(aux == 2):
name = input("Insert name to be deleted: ")
new_list.remove_by_name(name)
elif(aux == 3):
new_list.print()
id = int(input("Insert ID to be deleted: "))
new_list.remove_by_id(id)
os.system('cls' if os.name == 'nt' else 'clear')
elif(aux == 4):
os.system('cls' if os.name == 'nt' else 'clear')
new_list.print()
elif(aux == 0):
os.system('cls' if os.name == 'nt' else 'clear')
print("Goodbye!")
else:
os.system('cls' if os.name == 'nt' else 'clear')
print("Wrong value")
|
1b85739b38e89a682afbe13615220ca80c7d8937 | TerryLun/Code-Playground | /lcm_using_gcd.py | 166 | 3.5625 | 4 | """
https://en.wikipedia.org/wiki/Least_common_multiple
"""
from euclidean_gcd import gcd
def lcm(num1, num2):
return abs(int(num1 * num2 / gcd(num1, num2)))
|
c3247a8417cde1ff814bda09ee92aa2b45cecfd5 | Vinay-Harke/codemonk-solutions | /Monk and Suffix Sort.py | 183 | 3.84375 | 4 | # Write your code here
s1,pos=input().split()
pos = int(pos)
all_suffix = []
for i in range(len(s1)-1,-1,-1):
all_suffix.append(s1[i:])
all_suffix.sort()
print(all_suffix[pos-1])
|
632829d9fea1b4c434bb0ce6c60219a9715237fc | veronikakovalisko/classes | /main.py | 4,513 | 4.15625 | 4 | '''
Task 1
A Person class
Make a class called Person. Make the __init__() method take firstname, lastname,
and age as parameters and add them as attributes.
Make another method called talk() which makes prints a greeting from the person containing,
for example like this: “Hello, my name is Carl Johnson and I’m 26 years old”.
class Person:
def __init__(self, firstname, lastname, age):
self.f = firstname
self.l = lastname
self.a = age
def talk(self, f, l, a):
print(f'Hello my name is {f} {l} and I am {a} years old')
if __name__ == '__main__':
person = Person(input("enter your firstname"), input("enter your lastname"), input("enter your age"))
person.talk(person.f, person.l, person.a)
'''
"""
Task 2
Doggy age
Create a class Dog with class attribute `age_factor` equals to 7.
Make __init__() which takes values for a dog’s age.
Then create a method `human_age` which returns the dog’s age in human equivalent.
class Dog:
age_factor = 7
def __init__(self, dog_age):
while True:
try:
dog_age = int(dog_age)
break
except ValueError:
print("age should be digital")
dog_age = input("enter dogs age")
self.d_a = dog_age
def human_age(self, d_a, age_factor):
self.h_a = d_a * age_factor
return self.h_a
if __name__ == '__main__':
dog = Dog(input("enter dogs age"))
print(dog.human_age(dog.d_a, dog.age_factor))
"""
"""
Task 3
TV controller
Create a simple prototype of a TV controller in Python. It’ll use the following commands:
first_channel() - turns on the first channel from the list.
last_channel() - turns on the last channel from the list.
turn_channel(N) - turns on the N channel. Pay attention that the channel numbers start from 1, not from 0.
next_channel() - turns on the next channel. If the current channel is the last one, turns on the first channel.
previous_channel() - turns on the previous channel.
If the current channel is the first one, turns on the last channel.
current_channel() - returns the name of the current channel.
is_exist(N/'name') - gets 1 argument -
the number N or the string 'name' and returns "Yes", if the channel N or 'name'
exists in the list, or "No" - in the other case.
The default channel turned on before all commands is №1.
Your task is to create the TVController class and methods described above.
"""
CHANNELS = ["BBC", "Discovery", "TV1000"]
class TVController:
ch = 0
def __init__(self, channels):
self.ch = channels
def first_channel(self):
self.ch = CHANNELS[0]
return self.ch
def last_channel(self):
self.ch = CHANNELS[len(CHANNELS) - 1]
return self.ch
def turn_channel(self, N):
while True:
try:
N = int(N)
break
except ValueError:
print("number of channel should be digital")
N = input("enter number of channel")
N -= 1
if N < len(CHANNELS) and N >= 0:
self.ch = CHANNELS[N]
return self.ch
def next_channel(self):
channel = str(self.ch)
n = CHANNELS.index(channel)
if n == len(CHANNELS) - 1:
self.ch = CHANNELS[0]
else:
self.ch = CHANNELS[n + 1]
return self.ch
def previous_channel(self):
channel = str(self.ch)
n = CHANNELS.index(channel)
if n == 0:
self.ch = CHANNELS[len(CHANNELS) - 1]
else:
self.ch = CHANNELS[n - 1]
return self.ch
def current_cannel(self):
return self.ch
def is_exist(self, n):
try:
n = int(n)
n -=1
if n in range(len(CHANNELS)):
return "Yes"
else:
return "No"
except ValueError:
if n in CHANNELS:
return "Yes"
else:
return "No"
if __name__ == '__main__':
controller = TVController(CHANNELS)
controller.first_channel()
controller.last_channel()
print(controller.turn_channel(input("enter number of channel")))
print(controller.next_channel())
print(controller.current_cannel())
print(controller.is_exist(input("enter number or name")))
|
e627b6178f654c35224ac16dc3b503a08036aa05 | amoghrajesh/Coding | /transpose_matrix.py | 226 | 3.859375 | 4 | matrix = [[1,2,3],[4,5,6]]
m = len(matrix)
n = len(matrix[0])
ans = []
for i in range(n):
temp = []
for j in range(m):
print(j,i,matrix[j][i])
temp.append(matrix[j][i])
ans.append(temp)
print(ans)
|
d68e0b39320b0b464169aa1be0244e18e317d87a | anudeike/CSCI_201-HelperFile | /CSCI_201_HW_helpers/HW-7/convertToIEEE.py | 3,833 | 4.21875 | 4 | import math
# goal is to convert a decimal to floating point
"""
[ISSUES]
1. Something weird and annoyingly recursive happens when you input anything with "0.3" [FIXED]
2. Right now, it rounds to 10 in the separate function. Be careful.
"""
def run():
decimal = input("Enter the base-10 decimal number: >>")
mantissa_limit = int(input("Enter the mantissa limit: >> "))
bias = int(input("Enter the bias: "))
# decide whether the number is negative or positive
if decimal[0] == "-":
sign = 1
else:
sign = 0
# get the decimal and whole numbers
left, right = separate(str(abs(float(decimal))))
# gets the number in binary using the multiplication method
binFrac = fractionToBinary(right, mantissa_limit)
binWhole = intToBinary(left)
# display in raw binary
bin_raw = str(binWhole) + "." + str(binFrac)
print("Straight Binary is: " + bin_raw)
# MoveTheDecimalPlace
moved, exp, sig = moveDecimal(bin_raw)
# add the bias to the exp and convert it to binary
decimal_bias_exponent = (bias-1) + exp
binBiasExp = intToBinary(decimal_bias_exponent)
print("This is the moved: " + str(moved))
#lets join the whole thing! sign + binBiasExp + the significand
IEEE_format = str(sign) + " " + str(binBiasExp) + " " + str(sig)
print("Sign bit: " + str(sign))
print("Exponent Bias bits: " + str(binBiasExp))
print("Significand bits: " + str(sig))
print("COMPLETE IEEE Format: " + IEEE_format)
"""
Move the decimal place to the right place
RETURNS: Exponent,
"""
def moveDecimal(rawBin):
rawBin_float = float(rawBin)
rawBin_list = list(rawBin)
exp = 0 # holds the exponent
moved = ""
# if greater than 0, just move the point to the front
if (rawBin_float > 0):
# calculate the amount of spaces to move
for i in range(len(rawBin)):
if (rawBin[i] == "."):
break
exp = i # this is the 2^x (the x part)
rawBin_list.remove(".")
rawBin_list.insert(1, ".")
moved = "".join(rawBin_list)
# if less than 0 ->
if (rawBin_float < 0):
afterOne = False
for w in range(len(rawBin_list)):
if (afterOne):
break
if (rawBin_list[w] == "1"):
afterOne = True
# save the exponent
exp = -(w - 2)
# move the decimal point to where it needs to be
rawBin_list.remove(".")
rawBin_list.insert(w - 1, ".")
moved = "".join(rawBin_list)
#get the relevant portion
rel = moved.split(".")
return moved, exp, rel[1]
# returns a tuple (left, right)
def separate(num):
print("Separation...")
# get the numbers to the right and left of the decimal point
# if 5.672, then a = 5 and b = 0.672
left = math.floor(float(num))
right = round(float(num) - left, 10)
return left, right
# uses the multiplication method
def fractionToBinary(frac, limit):
running = True
frac_binary = []
k = 0
while (running):
frac = frac * 2
whole, new_frac = separate(str(frac)) # get the whole and fractional part of result
frac_binary.append(str(whole))
print("")
# check whether the new fraction is 0 -> if it is stop
if (int(new_frac == 0)):
running = False
frac = new_frac
# fail safe
if (len(frac_binary) > limit):
#print("[Warning] Binary is too long. Losing Precision...")
running = False
k += 1
# join the list to make it a string
binFracString = "".join(frac_binary)
return binFracString
# int to binary -- helluva lot easier
def intToBinary(integer):
a = bin(integer)
return a[2:]
if __name__ == "__main__":
run()
|
35a64d7ea90d57c72d05c6050b17063f080db21a | ravi4all/PythonFebOnline_21 | /ExceptionHandling/05-example.py | 487 | 3.796875 | 4 | def atm():
total = 10000
pin = input("Enter PIN : ")
if (pin == "1234"):
print("Login Success")
else:
raise ValueError("Login Failed")
amount = int(input("Enter amount : "))
if (amount < total):
total -= amount
print("Remaining balance is",total)
else:
raise ValueError("Insufficient Balance")
try:
atm()
except ValueError as err:
print(err)
finally:
print("Thanks for using this ATM") |
ff20347bd91795b337c687936798f0b75d353698 | wesenu/Project-Euler-1 | /python/Euler22.py | 897 | 3.546875 | 4 | #!/usr/bin/env python
# Project Euler - Problem 22
# Using names.txt, begin by sorting it into alphabetical order.
# Then working out the alphabetical value for each name, multiply
# this value by its alphabetical position in the list to obtain a name score.
#
# solution by nathan dotz
# nathan (period) dotz (at sign) gmail (period) com
#
import string # for string.ascii_uppercase... i'm lazy
def getValue(aStr):
aSum = 0
for letter in aStr:
for value, char in zip(range(1,27), string.ascii_uppercase):
if char == letter:
# print(char,"=",value)
aSum += value
return aSum
f = open ("names.txt", 'r')
names = [ name.strip('"' for name in f.read().split(',') ]
names = sorted(names)
superTotal=0
for iterCount,name in enumerate(names):
superTotal += (iterCount+1)*getValue(name)
print(superTotal)
|
1856f6053ead4251fd8b11255c0c714792b84cf1 | ideahitme/contest | /hackerrank/contest/world_codesprint_april/kmp_4/code.py | 1,161 | 3.609375 | 4 | def toString(xs):
result = []
col = [[el for _ in range(rep)] for (rep, el) in xs]
for arr in col:
result += arr
return result
def starting_point_of_char(xs, what_to_insert):
result = 0
for (rep, el) in xs:
if el == what_to_insert: break
result += rep
return result
def swap(mystring, pos1, pos2):
tmp = mystring[pos1]
mystring[pos1] = mystring[pos2]
mystring[pos2] = tmp
def construct(mystring, xs):
if xs[0][0] <= 2:
return mystring
else:
to_swap = xs[1][1]
from_where = starting_point_of_char(xs, to_swap)+(xs[0][0] + 1) % 2
cur = 2
while cur <= xs[0][0] - 1:
swap(mystring, cur, from_where)
cur += 2
from_where += 2
return mystring
xs = [(int(x), chr(97+index)) for index, x in enumerate(raw_input().split()) if int(x) > 0]
_min = 0
for i in range(1, len(xs)):
if xs[_min][0] > xs[i][0]:
_min = i
if len(xs) == 0:
print ""
elif len(xs) == 1:
print "".join(toString(xs))
elif _min != 0:
answer = toString(xs)
at = starting_point_of_char(xs, xs[_min][1])
toInsert = answer.pop(at)
answer.insert(0, toInsert)
print "".join(answer)
else:
mystring = toString(xs)
print "".join(construct(mystring, xs))
|
2ebd975f54007353cb043987b5e438accc6722c6 | SKPannem/PythonTraining | /Python/Chapter02/controlLoop.py | 521 | 4.0625 | 4 |
def main():
print("Hello")
msg = "WelcNomne to Nun the Python Cournse"
for c in msg:
if c == 'N' or c == 'n' :
continue #continue will continue for one iteration and skip one iteration of the loop
#break #break will simply break the entire circuit of the loop and jumps out of the loop
print(c, end=' ')
#print("\n I am out of the loop")
if __name__ == "__main__": main()
|
f5ded81c0a003cb0422e48411467855eacf3d09f | MatheusKlebson/Python-Course | /TERCEIRO MUNDO - THIRD WORLD/Funções para sortear e somar - 100.py | 694 | 4.15625 | 4 | # Exercício Python 100: Faça um programa que tenha uma lista chamada números
# duas funções chamadas sorteia() e somaPar(). A primeira função vai sortear 5 números
# vai colocá-los dentro da lista e a segunda função vai mostrar a soma entre
# todos os valores pares sorteados pela função anterior.
def randomNumbers():
from random import randint
for cont in range(0,5):
num = randint(1,10)
numbers.append(num)
def sumPairs():
soma = 0
for cont in range(0,5):
if numbers[cont] % 2 == 0:
soma += numbers[cont]
print(f"Numbers drawn: {numbers}")
print(f"Sum Pairs: {soma}")
numbers = []
randomNumbers()
sumPairs()
|
bf4d0232485244f01c9bebf511139a8af957dbb7 | Future-Aperture/Python | /exercícios_python/exercicios_theo/Exercicios 61-75/ex071.py | 597 | 3.90625 | 4 | print('='*30)
print('Banco do Xesque')
print('='*30)
valor = int(input('\nQual a quantidade que você quer sacar?\n> '))
cedula = 50
totalCedula = 0
while True:
if valor >= cedula:
valor -= cedula
totalCedula += 1
else:
if totalCedula > 0:
print(f'Total de {totalCedula} cédulas de R${cedula}')
if cedula == 50:
cedula = 20
elif cedula == 20:
cedula = 10
elif cedula == 10:
cedula = 1
totalCedula = 0
if valor == 0:
break |
707a50c0d4e9fe3e9a558b7decd7b18299666fe8 | TrinityChristiana/py-classes | /city.py | 588 | 4.125 | 4 | class City:
def __init__(self, name, mayor, year):
# Name of the city.
self.name = name
self.mayor = mayor
self.year = year
self.buildings = list()
def add_building(self, building):
self.buildings.append(building)
def print_building_details(self):
buildings = self.buildings
for building in buildings:
build = building.__dict__
print(f"{build['address']} was designed By {build['designer']} on {build['date_constructed']} is owned by {build['owner']} and has {build['stories']} floors") |
fdb9916e1e0cd063c2db59a2a379653730097e50 | JesusGarcia23/PythonKatas | /SumOfStrings/sumOfStrings.py | 109 | 3.59375 | 4 | def sum_str(a, b):
if(a == ""):
a = 0
if(b == ""):
b = 0
return str(int(a) + int(b))
|
f1f490198e7fcd2322ae38a112aa65ae12733bb9 | shen-huang/selfteaching-python-camp | /exercises/1901050013/1001S02E03_calculator.py | 1,256 | 4.15625 | 4 | def COUNT(count_one,count_two,operation):
if operation == '+':
print(count_one, "+" ,count_two, "=" ,(count_one + count_two))
elif operation =="-":
print(count_one,"-",count_two,"=",(count_one - count_two))
elif operation =="*" or operation =='x':
print(count_one,'*',count_two,"=",(count_one * count_two))
elif operation == '/' :
print(count_one,'/',count_two,"=",(count_one / count_two))
elif operation == '%':
print(count_one,'%',count_two,'=',(count_one % count_two))
else:
print("error")
while_condition = True
while while_condition:
count_one = int(input("请输入第一个数:"))
count_two = int(input("请输入第二个数:"))
operation = input("请输入要执行的四则运算(+-*/):")
if COUNT(count_one,count_two,operation) == 1:
print("error operation")
else:
while True:
Continue = input("是否继续? y/n: ")
if Continue == 'y':
print("user continue")
break
elif Continue == "n":
print("user termination")
while_condition = False
break
else:
print("user input the error option") |
d7e7418339de09ef772f2c15b3752c44b1780b3a | hayeonk/algospot | /solong.py | 1,439 | 3.703125 | 4 | class TrieNode(object):
def __init__(self, chr):
self.chr = chr
self.first = -1
self.terminal = -1
self.children = [None for i in range (26)]
def insert(self, key, id):
if self.first == -1:
self.first = id
if key == "":
self.terminal = id
else:
next = ord(key[0]) - ord('A')
if self.children[next] == None:
self.children[next] = TrieNode(key[0])
self.children[next].insert(key[1:], id)
def find(self, key):
if key == "":
return self
next = ord(key[0]) - ord('A')
if self.children[next] == None:
return None
return self.children[next].find(key[1:])
def type(self, key, id):
if key == "":
return 0
if self.first == id:
return 1
next = ord(key[0]) - ord('A')
return 1 + self.children[next].type(key[1:], id)
def countKeys(trie, word):
node = trie.find(word)
if node == None or node.terminal == -1:
return len(word)
return trie.type(word, node.terminal)
def readInput(n):
input = []
for _ in xrange(n):
s, freq = raw_input().split()
freq = int(freq)
input.append((-freq, s))
input.sort()
trie = TrieNode("")
for i in xrange(n):
trie.insert(input[i][1], i)
trie.first = -1
return trie
for _ in xrange (input()):
n, m = map(int, raw_input().split())
trie = readInput(n)
words = raw_input().split()
ret = 0
for i in xrange (m):
ret += countKeys(trie, words[i])
print ret + m - 1 |
a84d90bfa5802e2f154cff73a4877177a15efa09 | whigon/Founder | /Check.py | 1,684 | 3.625 | 4 | def check(filePath, sel, SN='', BN=''):
with open(filePath, 'r', encoding='UTF-8') as read_file:
# 记录行数
lineCount = 0
# 记录检查的项的正确个数
count = 0
while 1:
line = read_file.readline()
# 文件结束
if not line:
break
lineCount += 1
# 去掉换行符 和 回车
line = line.replace("\n", "")
line = line.replace("\r", "")
if sel == 1:
# 检查站点名
if line[:3] == 'SN:':
val = checkSN(line, SN)
# 检查返回值
if val:
count += 1
pass
else:
print('Line ' + str(lineCount) + ': SN error')
elif sel == 2:
if line[:3] == 'BN:':
val = checkBN(line, BN)
# 检查返回值
if val == 0:
print('Line ' + str(lineCount) + ': BN miss')
elif val == 1:
count += 1
pass
else:
print('Line ' + str(lineCount) + ': BN error')
return count
# 检查BN
def checkBN(str_bn, bn):
str = str_bn[3:]
if str == '':
return 0
if str == bn:
return 1
else:
return -1
# 检查SN
def checkSN(str_sn, sn):
str = str_sn[3:]
if str == sn:
return True
else:
return False
|
137119eb89e882493312de179e740bba6a3a236b | dusty736/DS_400 | /DustinBurnham-L09-AccuracyMeasures.py | 5,613 | 3.578125 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Dustin Burnham
Data Science 400
3/5/19
Assignment 9: Accuracy Measures
Summary:
The goal was to classify/predict whether a car was made in Asia based on
other factors like mpg, cylinders, horsepower, etc.. I decided since the
asia column was one-hot-encoded, that I would use a random forrest classifier
to make the predictions of the host nation. Once I trained my model and
created my probabilities, I used a threshold of 0.5 to create predictions.
Next I calculated the TPR, FPR, precision, recall, accuracy score, ROC
curve, and finally the AUC of that ROC curve.
Results (These numbers slightly vary after each run):
Accuracy Score: 0.82
Precision: 0.72
Recall: 0.43
f1 score: 0.54
Area Under Curve: 0.90
My model predicted whether a vehicle was made in Asia quite well with an
accuracy score of 0.82 and an area under the curve 0f 0.9.
"""
##############################################################################
# Import statements for necessary packages
##############################################################################
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.linear_model import LogisticRegression
from sklearn.ensemble import RandomForestClassifier
from sklearn.model_selection import train_test_split
from sklearn.metrics import *
import matplotlib
##############################################################################
# Read in the dataset from a freely and easily available source on the internet.
##############################################################################
# Read in data, add header, drop useless column
url = "https://archive.ics.uci.edu/ml/machine-learning-databases/auto-mpg/auto-mpg.data"
Auto = pd.read_csv(url, delim_whitespace=True, header=None)
names = ["mpg", "cylinders", "displacement", "horsepower",
"weight", "acceleration", "model_year", "origin", "car_name"]
Auto.columns = names
Auto = Auto.drop("car_name", axis=1)
# The horsepower column is the only one with missing values, so I will
# impute the missing values ('?') with the numeric mean of the other
# values in that column.
Auto.loc[:, "horsepower"] = pd.to_numeric(Auto.loc[:, "horsepower"], errors='coerce')
HasNan = np.isnan(Auto.loc[:,"horsepower"])
Auto.loc[HasNan, "horsepower"] = np.nanmean(Auto.loc[:,"horsepower"])
Auto.loc[:, "horsepower"] = pd.to_numeric(Auto.loc[:, "horsepower"])
# One-Hot-Encode the origin column into the columns North America, Europe, and Asia.
# Drop the now redundant column.
Auto.loc[:, "North America"] = (Auto.loc[:, "origin"] == 1).astype(int)
Auto.loc[:, "Europe"] = (Auto.loc[:, "origin"] == 2).astype(int)
Auto.loc[:, "Asia"] = (Auto.loc[:, "origin"] == 3).astype(int)
Auto = Auto.drop("origin", axis=1)
##############################################################################
# Split your data set into training and testing sets using the proper function
# in sklearn (include decision comments).
##############################################################################
# 70% training data, 30% test data
r = 0.3
TrainSet, TestSet = train_test_split(Auto, test_size=r)
# Predict whether a car was made in Asia
Target = "Asia"
Inputs = list(Auto.columns)
Inputs = Inputs[:-3] # Remove columns that cause leakage
# Create/fit random forest classifier
mss = 2 # mininum samples split parameter
estimitors = 10
clf = RandomForestClassifier(n_estimators=10, min_samples_split=mss) # default parameters are fine
clf.fit(TrainSet.loc[:,Inputs], TrainSet.loc[:,Target])
# Generate probabilites for each prediction using predict_proba function
BothProbabilities = clf.predict_proba(TestSet.loc[:,Inputs])
probabilities = BothProbabilities[:,1]
##############################################################################
# 1. Confusion Matrix
##############################################################################
# I will set a threshold of 0.5 because I think that is a good point to maximize
# TPR and minimize FPR.
threshold = 0.5
# Generate predictions, confusion matrix
predictions = (probabilities > threshold).astype(int)
CM = confusion_matrix(TestSet.loc[:,Target], predictions)
tn, fp, fn, tp = CM.ravel()
##############################################################################
# 2. Precision, Recall, f1 score
##############################################################################
AR = accuracy_score(TestSet.loc[:,Target], predictions)
print("accuracy score:", AR)
precision = precision_score(TestSet.loc[:,Target], predictions)
print("precision:", precision)
recall = recall_score(TestSet.loc[:,Target], predictions)
print("recall:", recall)
f1 = f1_score(TestSet.loc[:,Target], predictions)
print("f1 score:", f1)
##############################################################################
# 3. ROC Curve, Area Under Curve (AUC) Score, and Plot
##############################################################################
# Generate True Positive Rate, Fale Positive Rate
fpr, tpr, th = roc_curve(TestSet.loc[:,Target], probabilities)
# Generate Area Under the ROC Curve
AUC = auc(fpr, tpr)
print("Area Under Curve:", AUC)
# Generate ROC Plot
plt.rcParams["figure.figsize"] = [8, 8] # Square
plt.figure()
plt.title('ROC Curve')
plt.xlabel('FPR')
plt.ylabel('TPR')
plt.plot(fpr, tpr, LW=3, label='ROC curve (AUC = %0.2f)' % AUC)
plt.plot([0, 1], [0, 1], color='navy', LW=3, linestyle='--') # reference line for random classifier
plt.legend(loc="lower right")
plt.show() |
188c344ff0db03b18222fa1a76758c20baf9e5cf | sreshna10/assignments | /L9-set of operations.py | 1,001 | 4.4375 | 4 | # set of operators allowed in expression
Operators=set(['','-','+','%','/','*'])
def evaluate_postfix(expression):
# empty stack for storing numbers
stack=[]
for i in expression:
if i not in Operators:
stack.append(i) #This will contain numbers
else:
a=stack.pop()
b=stack.pop()
if i=='+':
res=int(b)+int(a)
elif i=='-':
res=int(b)-int(a)
elif i=='*':
res=int(b)*int(a)
elif i=='%':
res=int(b)%int(a)
elif i=='/':
res=int(b)/int(a)
elif i=='**':
res=int(b)**int(a)
# final result
stack.append(res)
return(''.join(map(str,stack)))
expression = input('Enter the postfix expression ')
print()
print('postfix expression entered: ',expression)
print('Evaluation result: ',evaluate_postfix(expression))
|
d893304a35ffc050e9925924b4a0cf212b005e41 | zed1025/coding | /coding-old/Codechef/long-challenge/NOV19B_HRDSEQ.py | 880 | 3.546875 | 4 | '''
https://www.codechef.com/NOV19B/problems/HRDSEQ
Accepted
'''
try:
t = int(input())
except:
pass
def util(nums):
'''
if the last element of the list does not occour anywhere previously, method returns -1
else method returns, diff between the positions of the last element and the first occourence of the last element scanning from the end of the list
'''
t = nums[-1]
x = len(nums)-1
if nums.index(t) == len(nums)-1:
return 0
else:
for i in range(len(nums)-2, -1, -1):
if nums[i] == t:
return (x-i)
while t > 0:
t = t-1
n = int(input())
if n == 1:
print('1')
continue
nums = [0, 0]
for i in range(2, n):
x = util(nums)
nums.append(x)
# print(nums)
print(nums.count(nums[-1]))
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.