blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
8076fc00362f6e4fffa62c4eada5a6b018815490 | kaichimomose/CS-2-Tweet-Generator | /Challenges/rearrange.py | 533 | 3.859375 | 4 | import random, sys
def rearrange(params):
word_List = params
length = len(params)
rearrange_order = ""
for i in range(0, length):
number = random.randint(0, len(word_List)-1)
if rearrange_order == "":
rearrange_order = word_List[number]
else:
rearrange_order += " " + word_List[number]
word_List.remove(word_List[number])
return rearrange_order
if __name__ == '__main__':
params = sys.argv[1:]
rearrange = rearrange(params)
print(rearrange)
|
81c6ba6d86ac953a5cde2011f92eaa71e2802159 | PowerfulCheese/COMP9021_19T1 | /quiz_4.py | 2,292 | 3.640625 | 4 | # Uses Heath Nutrition and Population statistics,
# stored in the file HNP_Data.csv.gz,
# assumed to be located in the working directory.
# Prompts the user for an Indicator Name. If it exists and is associated with
# a numerical value for some countries or categories, for some the years 1960-2015,
# then finds out the maximum value, and outputs:
# - that value;
# - the years when that value was reached, from oldest to more recents years;
# - for each such year, the countries or categories for which that value was reached,
# listed in lexicographic order.
#
# Written by *** and Eric Martin for COMP9021
import sys
import os
import csv
import gzip
filename = 'HNP_Data.csv.gz'
if not os.path.exists(filename):
print(f'There is no file named {filename} in the working directory, giving up...')
sys.exit()
indicator_of_interest = input('Enter an Indicator Name: ')
first_year = 1960
number_of_years = 56
max_value = None
countries_for_max_value_per_year = {}
with gzip.open(filename) as csvfile:
reader = csv.reader(line.decode('utf8').replace('\0', '') for line in csvfile)
next(reader)
linenum = 0
for i in reader:
if len(i) == 0:
continue
linenum += 1
if i[2] != indicator_of_interest:
continue
for j in range(number_of_years):
if i[j+4] is '':
continue
t_int = float(i[j+4])
if max_value is None:
max_value = t_int
elif t_int < max_value:
continue
elif t_int > max_value:
max_value = t_int
countries_for_max_value_per_year.clear()
countries_for_max_value_per_year.setdefault(j+first_year, list()).append(i[0])
max_value = round(max_value) if round(max_value, 1) == round(max_value) else round(max_value, 1)
if max_value is None:
print('Sorry, either the indicator of interest does not exist or it has no data.')
else:
print('The maximum value is:', max_value)
print('It was reached in these years, for these countries or categories:')
print('\n'.join(f' {year}: {countries_for_max_value_per_year[year]}'
for year in sorted(countries_for_max_value_per_year)
)
)
|
d35a2becbe1cfe364da351179d1c3bcc96dee08f | wfgiles/P3FE | /Week 12 Chapter 10/CH 10 slides2.py | 1,065 | 3.90625 | 4 | ##counts = {'chuck' : 1, 'annie' : 42, 'jan' : 100}
##lst = counts.keys()
##print lst
##lst.sort()
##for key in lst:
## print key, counts[key]
##-------------
##d = {'a':10, 'b':1, 'c':22}
##print d.items()
##
##print sorted(d.items())
##--------------
##SORT BY VALUE
##d = {'a':10, 'b':1, 'c':22}
##
##print d.items()
##
##print sorted(d.items())
##
##for k, v in sorted(d.items()):
## print k, v
##-------------------
##SORT BY VALUE INSTEAD OF KAY
##c = {'a':10, 'b':1, 'c':22}
##tmp = list()
##for k, v in c.items():
## tmp.append((v, k))
##print tmp
##
##tmp = sorted(tmp,reverse=True)
##print tmp
##-------------
##*****KNOW THIS******
##TOP 10 COMMON WORDS IN A FILE
##fhand = open('romeo.txt')
##counts = dict()
##for line in fhand:
## words = line.split()
## for word in words:
## counts[word] = counts.get(word,0) + 1
##
##lst = list()
##for key, val in counts.items():
## newtup = (val, key)
## lst.append(newtup)
##
##lst = sorted(lst, reverse=True)
##
##for val, key in lst[:10]:
## print(key, val)
|
4debe7a25bebf1fe8657f0d969942ab468bcebe5 | lembuss/My-Python-Codes | /ownsplit.py | 754 | 3.875 | 4 | # program performs a split on a sentence into individual words
def mysplit(strng):
new = []
splitword = []
spaces = 0
lngth = len(strng)
for i in range(lngth):
if ord(strng[i]) == 32:
spaces +=1
else:
continue
start = 0
space = ''
for i in range(spaces+1):
new.insert(i, [])
for j in range(start, lngth):
if ord(strng[j]) == 32:
start = j + 1
break
else:
new[i].append(strng[j])
inter = space.join(new[i])
splitword.append(inter)
return splitword
# code starts here
sentence = input("Enter sentence to be split: ")
print(mysplit(sentence))
|
5823262448e085ef699c18a3a5c3894b0fc933b2 | Takashiidobe/learnPythonTheHardWayZedShaw | /ex15.py | 706 | 4.0625 | 4 |
#imports from the system arguments
from sys import argv
#the script is always the first arg, and then the filename is the second
script, filename = argv
#simplifies the open(filename) command
txt = open(filename)
#a little line that says what we're doing
print(f"Here's your file {filename}:")
#prints out the contents of the file
print(txt.read())
#make sure to close files after you open them.
txt.close()
#asks for the filename again
print("Type the filename again:")
#saves whatever input you give it
file_again = input("> ")
#uses the input to open the file again
txt_again = open(file_again)
#opens the file
print(txt_again.read())
#always close files after you're done using them
txt.close() |
85e80af755ba6b7eea23f3c1a28ada68d6e10ab8 | jasminecronin/intro-to-cs-I | /Coursework/Assignments/Assignment 3/assignment3.py | 8,428 | 4.40625 | 4 | """Assignment 3: AI Training
This program plays a game of nuts. There are a number of nuts on a table, and
two players take turns picking up 1-3 nuts. The player to pick up the last nut
loses. This game can be played with 2 human players, one player against an
untrained AI, or one player against a trained AI.
Author: Jasmine Roebuck, November 6, 2017"""
import random
def main():
"""Main module. Prints the menu and calls the game choice."""
print("Welcome to the game of nuts!")
nuts = start_nuts() #Prompt for initial number of nuts
print("Options:") # Print out the options menu
print(" Play against a friend (1)")
print(" Play against the computer (2)")
print(" Play against the trained computer (3)")
# Get the player's option choice
opt = int(input("Which option do you take (1-3)? "))
while opt < 1 or opt > 3:
opt = int(input("Invalid input. Please enter a number from 1 to 3 "))
# Run the appropriate game
if opt == 1:
option1(nuts)
elif opt == 2:
option2(nuts)
elif opt == 3:
option3(nuts)
def option1(n) :
"""Runs a human v. human game. Takes in the inital number of nuts. Prints
out game statuses."""
player = 1
while True: # Continue until there are < 1 nuts on the board
print("\nThere are ", n, " nuts on the board.")
pickup = player_nuts(player) # Get the player's pickup choice
n -= pickup
if n < 1:
print("Player {}, you lose.".format(player))
break
if player == 1: # Swap the current player to the opposite player
player = 2
else :
player = 1
def option2(n):
"""Runs human v. AI games. Can play multiple games. The AI makes its choices
randomly, and it will build a probability table of optimal choices as it plays
more games."""
# Initializes probability table. Each row in the table corresponds to
# the number of nuts currently in the game.
hats = create_table(n)
play_again = 1
initial_nuts = n # Remember starting nut count
while play_again != 0: # Play games until player enters 0
human_v_ai(hats, n) # Run a human v. AI game
n = initial_nuts # Reset the nut counter
# Prints the probability table after winning/losing. Uncomment these lines to view.
# Note that hats[0] is unused, hats[row][0] is used for tracking winning moves.
# print()
# print( hats )
play_again = int(input("Play again (1 = yes, 0 = no)? "))
def option3(n):
"""Trains the AI, then runs human v. AI games. Option for multiple games.
Builds probability tables for 2 AIs. The first AI achieves far more wins
than the second AI, so AI1 is then used as the opponent for the player."""
ai1 = create_table(n) # Initialize the probability tables
ai2 = create_table(n)
play_again = 1
initial_nuts = n # Remember starting nut count
training_sessions = 100000 # Number of AI v AI games to run
print("Training AI, please wait...")
for i in range(training_sessions):
ai_v_ai(ai1, ai2, n)
# Note that ai1[0] and ai2[0] are unused, ai[row][0] is used for tracking winning moves.
# print()
# print(ai1)
# print(ai2)
while play_again != 0: # Play games until player enters 0
human_v_ai(ai1, n) # Run a human v. AI game
n = initial_nuts # Reset the nut counter
play_again = int(input("Play again (1 = yes, 0 = no)? "))
def human_v_ai(hats, n):
"""Runs a single human v. AI game given the probability table for the AI
and the initial nut number. Prompts the user for pickup choice, directs
the AI to make its selection randomly."""
player = 1 # Start with the human player
while True: # Continue until there are < 1 nuts on the board
print("\nThere are ", n, " nuts on the board.")
if player == 1:
pickup = player_nuts(player) # Get the player's move
n -= pickup # Reduce the nuts on the table
player = 2 # Swap to AI
else:
pickup = ai_nuts(hats, n, True) # Get the AI's move
n -= pickup # Reduce the nuts on the table
player = 1 # Swap to player
if n < 1:
if player == 1: # Last move was the AI's
print("AI loses.")
win = False # AI lost
else: # Last move was player's
print("You lose.")
win = True # AI won
adjust_table(hats, win) # Adjust the probabilities in the table
break
def ai_v_ai(ai1, ai2, n):
"""Runs a single AI v. AI game given two probability tables and the initial
number of nuts on the board. Directs both AIs to choose their moves
randomly using the weights in their respective tables."""
player = 2 # Start with the second AI
win1 = False
win2 = False
while True: # Continue until there are < 1 nuts on the board
if player == 1:
pickup = ai_nuts(ai1, n, False) # Make move choice
n -= pickup # Reduce nuts on the board
player = 2 # Swap to AI 2
else:
pickup = ai_nuts(ai2, n, False) # Make move choice
n -= pickup # Reduce nuts on the board
player = 1 # Swap to AI 1
if n < 1:
if player == 1 : # AI 2 made final move
win1 = True
else : # AI 1 made final move
win2 = True
adjust_table(ai1, win1) # Adjust probabilities in both tables
adjust_table(ai2, win2)
break
def start_nuts():
"""Gets the initial number of nuts from the player. Must be an integer
between 10 and 100. Non-integer inputs are invalid. Returns the number
to the main module."""
num = int(input("How many nuts are there on the table initially (10-100)? "))
while num < 10 or num > 100:
print("Please enter a number between 10 and 100.")
num = int(input("How many nuts are there on the table initially (10-100)? "))
return num
def player_nuts(p):
"""Gets and returns the player's choice of the number of nuts to pick up.
must be an integer between 1 and 3 inclusive. Non-integer inputs are
invalid."""
num = int(input("Player {}: How many nuts do you take (1-3)? ".format(p)))
while num < 1 or num > 3:
print("Please enter a number between 1 and 3.")
num = int(input("Player {}: How many nuts do you take (1-3)? ".format(p)))
return num
def ai_nuts(hats, row, player):
"""Determines and returns the AI's pickup choice given the AI's probability
table and number of nuts currently on the board. Prints status messages
only if the opposing player is human."""
i = [1, 2, 3] # List of the available move choices
# Randomizes based on the current weights in the probability table
pick = random.choices(i, weights=hats[row][1:])
hats[row][0] = pick[0] # Record the move choice
if player == True: # If we have a human player
print("AI selects ", pick[0]) # Tell what the AI chose
return pick[0]
def create_table(n):
"""Initializes a probability table for the AI given the initial number of
nuts. Creates n + 1 rows such that the row index refers directly to the
current number of nuts (the first row is unused). Each row contains a sublist
with index 1, 2, and 3 referring to the nut pickup choice. Index 0 is used for
tracking winning moves."""
table = []
for i in range(n + 1):
row = [0, 1, 1, 1]
table.append(row)
return table
def adjust_table(h, win):
"""Adjusts the probability of the given table depending on if the AI
won or lost."""
for row in range(len(h)): # Go through the whole table
pick = h[row][0] # Look at the move choice
if pick != 0: # Only adjust if the AI made a move
if win == True: # If the AI won
h[row][pick] += 1 # Increase the probability of this move
elif win == False and h[row][pick] > 1: # If AI lost
h[row][pick] -= 1 # Decrease the probability (can't go below 1)
h[row][0] = 0 # Erase the stored move
main()
|
f152e68bf28c50ba1803d19aa797d2f88669bf29 | m-strasser/gutenpy | /guten.py | 6,203 | 3.71875 | 4 | #!/usr/bin/env python3
"""
Scrapes books from gutenberg.spiegel.de
"""
import click
import requests
from bs4 import BeautifulSoup
class Book:
"""
Stores information about a book.
"""
def __init__(self, url):
self.url = url
self.author = None
self.title = None
self.year = None
self.chapters = []
def _find_chapter(self, soup, url):
chapter_ = soup.find('h1')
if chapter_:
chapter = Chapter(chapter_.text, url)
self.chapters.append(chapter)
subtitle = soup.find('h2')
if subtitle:
chapter.subtitle = subtitle.text
return (chapter, True)
else:
return (self.chapters[-1], False)
def _find_subchapter(self, soup, chapter, url, level=2):
subchap_ = soup.find('h{}'.format(level))
if subchap_:
subchapter = Chapter(subchap_.text, url)
chapter.subchapters.append(subchapter)
subtitle = soup.find('h{}'.format(level+1))
subchapter.subtitle = subtitle.text
return (subchapter, True)
elif len(chapter.subchapters) > 0:
return (chapter.subchapters[-1], False)
else:
return (None, False)
def parse_site(self, soup, url, is_first=False):
if not is_first:
chapter, created = self._find_chapter(soup, url)
if created:
return chapter.parse_paragraph(soup, url)
subchapter, created = self._find_subchapter(soup, chapter, url)
if created:
return subchapter.parse_paragraph(soup, url)
ssubchapter, created = self._find_subchapter(soup, chapter, url,
level=3)
if created:
return ssubchapter.parse_paragraph(soup, url)
else:
author = soup.find(class_='author')
title = soup.find(class_='title')
year = soup.find('h4')
self.author = author.text
self.title = title.text
self.year = year.text.lstrip('(').rstrip(')')
chapter = Chapter('Backtext', url)
chapter.parse_paragraph(soup, url)
class Chapter:
"""
Stores information about a chapter.
"""
def __init__(self, name, url, parent = None, prev_=None, next_=None, subchapters=[]):
self.name = name
self.subtitle = None
self.url = url
self.subchapters = subchapters
self.parent = parent
self.prev = prev_
self.next = next_
self.paragraphs = []
def __repr__(self):
return '{}: {}'.format(self.name, self.subtitle)
def parse_paragraph(self, soup, url, is_first=False):
"""
Parses a paragraph (i.e. a site from Gutenberg).
:param soup: The BeautifulSoup instance containing
the paragraph.
:param url: The URL to the paragraph's site.
:param is_first: True for the first site of the book
(to correctly extract chapter names).
"""
self.paragraphs.append(
Paragraph(url, soup.find_all('p')))
class Paragraph:
"""
Stores information about a paragraph (i.e. a page on the Project
Gutenberg site).
"""
def __init__(self, url, text):
self.url = url
self.text = text
def get_chapter_list(soup, parent=None):
"""
Parse the chapter list contained in the given element.
:param soup: A BeautifulSoup instance containing a Table of Contents element.
:returns: A list of chapter names and their subchapters.
"""
chapters = []
prev_chapter = None
for c in soup.children:
if c.name == 'li':
subchapters = c.find('ol')
if subchapters:
chapter = Chapter(name=c.contents[0].text,
prev_=prev_chapter,
parent=parent)
chapter.subchapters = get_chapter_list(subchapters,
chapter)
else:
chapter = Chapter(name=c.text,
prev_=prev_chapter,
parent=parent)
if prev_chapter:
prev_chapter.next = chapter
chapters.append(chapter)
prev_chapter = chapter
return chapters
def get_toc(soup):
"""
Searches for the Table of Contents element in the given element.
:param soup: A BeautifulSoup instance.
:returns: A list of chapter names and their subchapters.
"""
toc = soup.find(class_='toc')
prev_chapter = None
chapters = []
found_first_list = False
chapter_list = None
for c in toc.children:
if c.name == 'p':
chapter = Chapter(c.text, prev_chapter)
if prev_chapter:
prev_chapter.next = chapter
chapters.append(chapter)
prev_chapter = chapter
if c.name == 'ol':
chapter_list = c
chapters.extend(get_chapter_list(chapter_list))
return chapters
def scrape(url, book, is_first=False):
"""
Scrapes the given URL and stores the result in the given `Book`
instance.
:param url: The URL to the first page of a Project Gutenberg book.
:param book: An instance of `Book` storing the scraping results.
"""
print('Scraping {}...'.format(url))
r = requests.get(url)
soup = BeautifulSoup(r.content, 'html.parser')
content = soup.find(id='gutenb')
book.parse_site(content, url, is_first)
# Find the link to the next page.
next_link = content.next_sibling.next_sibling
if next_link.name == 'a':
if '<<' in next_link.text:
next_link = next_link.next_sibling.next_sibling
if next_link.name != 'a' or '>>' not in next_link.text:
# Last page, return.
return
scrape('{}{}'.format('http://gutenberg.spiegel.de',
next_link['href']),
book)
@click.command()
@click.argument('URL')
def main(url):
book = Book(url)
scrape(url, book, True)
if __name__ == '__main__':
main()
|
d2f43274936e7f233b434e561b5ada086e8ad66d | rhj0970/C200-Intro-to-Computing-Python | /Assignment11/fullbfs.py | 2,031 | 3.6875 | 4 |
import random as rn
class Stack:
def __init__(self):
self.stack=[]
def empty(self):
return self.stack == []
def pop(self):
if not self.empty():
return self.stack.pop(0)
def push(self,x):
self.stack.insert(0,x)
def __str__(self):
return str(self.stack)
class Queue:
def __init__(self):
self.queue = []
def empty(self):
return self.queue == []
def dequeue(self):
if not self.empty():
return self.queue.pop(0)
def enqueue(self,x):
self.queue.append(x)
return self
def __str__(self):
return str(self.queue)
class Graph:
def __init__(self,nodes):
self.nodes = nodes
self.edges = {}
for i in self.nodes:
self.edges[i] = []
def add_edge(self, pair):
start,end = pair
self.edges[start].append(end)
def children(self,node):
return self.edges[node]
def nodes(self):
return str(self.nodes)
def __str__(self):
return str(self.edges)
def bfsfull(g,node):
edge = g.edges
visited = []
que = Queue()
que.enqueue(node)
while not que.empty():
Node = que.dequeue()
if Node not in visited:
print(Node)
visited.append(Node)
childlist = g.children(Node)
for n in childlist:
if n in g.nodes:
if n not in visited:
que.enqueue(n)
else:
break
unvisited = []
for node in g.nodes:
if node not in visited:
unvisited +=[node]
remaining = Graph(unvisited)
for i in remaining.nodes:
remaining.edges[i] = edge[i]
if remaining.nodes != []:
j = unvisited[rn.randrange(0,len(unvisited))]
bfsfull(remaining, j)
g = Graph([1,2,3,4,5,6,7,8])
elst = [(1,2),(1,3),(2,8),(3,5),(3,4),(5,6),(6,4),(6,7)]
for i in elst:
g.add_edge(i)
print(g.edges)
bfsfull(g,5)
|
c97e20616a9ab2253e7bea03e1582fbd66b82798 | karthikeyansa/python-placements-old | /python-day-2/prob21.py | 50 | 3.515625 | 4 | n=str(input("enter the string: "))
print(n[::-1])
|
6e655cf3e290a93d2a3eda9fd540ff8871715423 | sydneykleingartner/darkpixels | /step1.py | 616 | 3.953125 | 4 | #step one of the project
#goal: python program that loads image and prints it
#>>>from PIL import Image
#>>>im = Image.open('grace-hopper.png', ' r')
def main ():
#importing the Image module of PIl
from PIL import Image
#creating an Image object
#opening the image for reading mode (so then we can do stuff with it!)
im = Image.open('grace-hopper.png', 'r')
if __name__ == '__main__':
main()
#extract all pixel values from the image
#store all the pixels in a two dimensional array
#each pixel is a three dimensional array on its own
#for loop through the array
#goal: to find the darkest pixel
|
d36aa4310a3c50c13edd9e5177c5601ade1a9747 | indrajithbandara/uri-questions | /uri_2486.py | 414 | 3.796875 | 4 | #UNDONE
while(True):
number = input()
xs, ys = [],[]
status = 0 #0 => function, 1 => not revertble, 2 => not a function
if(number == 0):
break
for i in range(number):
listaxy = raw_input().split()
x,y = listaxy[0], listaxy[2]
if(x in xs):
status = 2
if(y in ys and status != 2):
status = 1
xs.append(x)
ys.append(y)
print ("Invertible.", "Not invertible.", "Not a function.")[status]
|
b0d8e290335b154ab3949d301d7a3516100c40ef | gnuwind/LearnPython | /LearnPythonTheHardWay_Exercise(Python3)/ex5.py | 721 | 3.765625 | 4 | def inches2cm(inches):
return inches * 2.54
my_name = 'Zed A, Shaw'
my_age = 35 # not a lie
my_height = 74 # inches
my_height_cm = inches2cm(my_height)
my_weight = 180 # lbs
my_eyes = 'Blue'
my_teeth = 'White'
my_hair = 'Brown'
print("Let's talk about %s." % my_name)
print("He's %d inches tall." % my_height)
print("He's %d cm tall." % my_height_cm)
print("He's %d pounds heavy." % my_weight)
print("Actually that's not too heavy.")
print("He's got %s eyes and %s hair." % (my_eyes, my_hair))
print("His teeth are usully %s depending on th coffee." % my_teeth)
# this line is tricky, try to get it exctly right
print("If I add %r, %d, and %d I get %d." % (my_age, my_height, my_weight, my_age + my_height + my_weight))
|
a9ceebfda6179b006879615a4ec5e4e3cd497ee7 | FlyingMedusa/PythonELTIT | /Python from scratch/003PrimeNumbers.py | 399 | 4.1875 | 4 | #Write a program that prints the prime numbers from 1 to 100.
#A prime number is a number that is divisible only by 1 and itself.
not_prime = []
prime = []
for i in range(2,101):
for j in range(2,i):
if i%j == 0:
not_prime.append(i)
break
if i not in not_prime:
prime.append(i)
print("\n\tPrime numbers from 1 to 100:")
print(*prime, sep = ", ")
|
fa407414041b19ceaace9db20329207053222181 | Samruddhi9369/Real-Time-Facial-Expression-Recognition | /FacialExpressionRecognizer-CNN/model/fer2013DataGenerator.py | 4,302 | 3.625 | 4 | from keras.utils.np_utils import to_categorical
import pandas as pd
import numpy as np
import random
import sys
# This file separate training and validation data. While generating data, we classified Disgust as Angry.
# So resulting data will contains 6-class balanced dataset that contains Angry, Fear, Happy, Sad, Surprise and Neutral
# fer2013 dataset:
# It comprises a total of 35887 pre-cropped, 48-by-48-pixel grayscale images of faces each
# labeled with one of the 7 emotion classes: anger, disgust, fear, happiness, sadness, surprise, and neutral.
# Training 28709
# PrivateTest 3589
# PublicTest 3589
# emotion labels from FER2013:
original_emo_classes = {'Angry': 0,
'Disgust': 1,
'Fear': 2,
'Happy': 3,
'Sad': 4,
'Surprise': 5,
'Neutral': 6}
final_emo_clasees = ['Angry',
'Fear',
'Happy',
'Sad',
'Surprise',
'Neutral']
# Reconstruct original image to size 48X48. Returns numpy array of image pixels
def fnReconstruct(original_pixels, size=(48, 48)):
arrPixels = []
for pixel in original_pixels.split():
arrPixels.append(int(pixel))
arrPixels = np.asarray(arrPixels)
return arrPixels.reshape(size)
#This function merge disgust emotion label to anger label and returns count of each emotion class
def fnGetEmotionCount(y_train, emoClasses, verbose=True):
emo_classcount = {}
#fer2013 dataset contains only 113 samples of "disgust" class compared to many other classes.
#Therefore we merge disgust into anger to prevent this imbalance.
print ('Disgust classified as Angry')
y_train.loc[y_train == 1] = 0
emoClasses.remove('Disgust')
for newNum, className in enumerate(emoClasses):
y_train.loc[(y_train == original_emo_classes[className])] = newNum
class_count = sum(y_train == (newNum))
if verbose:
print ('{}: {} with {} samples'.format(newNum, className, class_count))
emo_classcount[className] = (newNum, class_count)
return y_train.values, emo_classcount
#loads data from fer2013.csv
def fnLoadData(Sample_split_fraction=0.3, usage='Training', boolCategorize=True, verbose=True,
default_classes=['Angry', 'Happy'], filepath='../data/fer2013.csv'):
# read .csv file using pandas library
df = pd.read_csv(filepath)
df = df[df.Usage == usage]
arrFrames = []
default_classes.append('Disgust')
for _class in default_classes:
class_df = df[df['emotion'] == original_emo_classes[_class]]
arrFrames.append(class_df)
data = pd.concat(arrFrames, axis=0)
rows = random.sample(list(data.index), int(len(data) * Sample_split_fraction))
data = data.ix[rows]
print ('{} set for {}: {}'.format(usage, default_classes, data.shape))
data['pixels'] = data.pixels.apply(lambda x: fnReconstruct(x))
x = np.array([mat for mat in data.pixels])
X_train = x.reshape(-1, 1, x.shape[1], x.shape[2])
Y_train, new_dict = fnGetEmotionCount(data.emotion, default_classes, verbose)
print (new_dict)
if boolCategorize:
Y_train = to_categorical(Y_train)
return X_train, Y_train, new_dict
# Save X_train (images) and Y_train (labels) to local folder for training
def fnSaveData(X_train, Y_train, fname='', folder='../data/'):
np.save(folder + 'X_train' + fname, X_train)
np.save(folder + 'Y_train' + fname, Y_train)
if __name__ == '__main__':
# makes the numpy arrays ready to use:
print ('Making moves...')
final_emo_clasees = ['Angry',
'Fear',
'Happy',
'Sad',
'Surprise',
'Neutral']
X_train, Y_train, emo_dict = fnLoadData(Sample_split_fraction=1.0,
default_classes=final_emo_clasees,
usage='Training',
verbose=True)
print ('Saving...')
fnSaveData(X_train, Y_train, fname='_train')
print (X_train.shape)
print (Y_train.shape)
print ('Done!')
|
650912dfeabb54aa1626b875056902198b547349 | pavankumarag/ds_algo_problem_solving_python | /practice/hard/_45_max_path_sum_in_binarytree.py | 1,138 | 4.1875 | 4 | """
Given a binary tree, find the maximum path sum. The path may start and end at any node in the tree.
Example:
Input: Root of below tree
1
/ \
2 3
Output: 6
See below diagram for another example.
1+2+3
Reference: https://www.geeksforgeeks.org/find-maximum-path-sum-in-a-binary-tree/
"""
class Node:
def __init__(self, data):
self.data = data
self.right = None
self.left = None
def find_max_path(root):
def find_max_path_util(root):
if root is None:
return 0
l = find_max_path_util(root.left)
r = find_max_path_util(root.right)
max_single = max(max(l,r)+root.data, root.data)
max_top = max(max_single, l+r+root.data)
find_max_path_util.res = max(find_max_path_util.res, max_top)
return max_single
find_max_path_util.res = float('-inf')
find_max_path_util(root)
return find_max_path_util.res
if __name__ == "__main__":
root = Node(10)
root.left = Node(2)
root.right = Node(10)
root.left.left = Node(20)
root.left.right = Node(1)
root.right.right = Node(-25)
root.right.right.left = Node(3)
root.right.right.right = Node(4)
print "Max path sum is ", find_max_path(root); |
22e69663629513ecb24133238e9522805f20e2f4 | mylessbennett/python_fundamentals2 | /exercise7.py | 716 | 3.796875 | 4 | runner_speeds = []
count = 1
i = "y"
while i == "y":
distance = float(input("How far did person {} run (in metres)? ".format(count)))
time = float(input("How long did it take for person {} to run {} metres? ".format(count, distance)))
speed = distance / (time*60)
runner_speeds.append(speed)
count += 1
i = input("Keep going? (y/n) ")
def fastest_person(runner_speeds):
fastest_so_far = 0
for speed in runner_speeds:
if speed > fastest_so_far:
fastest_so_far = speed
return fastest_so_far
winner = fastest_person(runner_speeds)
winner_number = runner_speeds.index(winner) + 1
print("Person {} was the fastest at {:.2f} m/s".format(winner_number, winner))
|
462c2ca454c929dc627b7214bc2da7155a883427 | johnathan-dev/codingbat-solution | /python/String-2/end_other.py | 285 | 3.640625 | 4 | def end_other(a, b):
checker = ""
if(len(a) >= len(b)):
i = -len(b)
while(i < 0):
checker += a[i].lower()
i += 1
return checker == b.lower()
else:
i = -len(a)
while(i < 0):
checker += b[i]
i += 1
return checker.lower() == a.lower() |
3339f87f62653ea740d4f8d94604c79bbe7686d7 | SamuelDodet/Belgian_Houses_Price_Prediction | /utils/utils.py | 4,620 | 3.90625 | 4 | import warnings
import numpy as np
import sklearn
def drop_row_without_value(arg, database):
"""
delete row with empty value in df data
arg = name of the columns
"""
nan_value = float("NaN")
database.replace("", nan_value, inplace=True)
database.dropna(subset=[arg], inplace=True)
def replace_string_by_value(column, numbers, replaces, database="data"):
"""Replace String by int for machine learning training
columns = name of the column
number = int to replace the string
replace = name of the string to replace
inplace : True"""
for number, replace in zip(numbers, replaces):
database[column].replace(number, replace, inplace=True)
def change_to_province(postal_code):
if postal_code >= 1000 and postal_code < 1300:
return "Brussel","Brussel",1,1
elif postal_code >= 1300 and postal_code < 1500:
return "Brabant Wallon","Wallonia",2,2
elif (postal_code >= 1500 and postal_code < 2000) or (postal_code >= 3000 and postal_code < 3500):
return "Brabant Flamand","Flanders",3,3
elif postal_code >= 2000 and postal_code < 3000:
return "Anvers","Flanders",4,3
elif postal_code >= 3500 and postal_code < 4000:
return "Limbourg","Flanders",5,3
elif postal_code >= 4000 and postal_code < 5000:
return "Liège","Wallonia",6,2
elif postal_code >= 5000 and postal_code < 6000:
return "Namur","Wallonia",7,2
elif (postal_code >= 6000 and postal_code < 6600) or (postal_code >= 7000 and postal_code < 8000):
return "Hainaut","Wallonia",8,2
elif postal_code >= 6600 and postal_code < 7000:
return "Luxembourg","Wallonia",9,2
elif postal_code >= 8000 and postal_code < 9000:
return "Flandre Occidental","Flanders",10,3
elif postal_code >= 9000:
return "Flandre Oriental","Flanders",11,3
def get_feature_names(column_transformer):
"""Get feature names from all transformers.
Returns
-------
feature_names : list of strings
Names of the features produced by transform.
"""
# Remove the internal helper function
# check_is_fitted(column_transformer)
# Turn loopkup into function for better handling with pipeline later
def get_names(trans):
# >> Original get_feature_names() method
if trans == 'drop' or (
hasattr(column, '__len__') and not len(column)):
return []
if trans == 'passthrough':
if hasattr(column_transformer, '_df_columns'):
if ((not isinstance(column, slice))
and all(isinstance(col, str) for col in column)):
return column
else:
return column_transformer._df_columns[column]
else:
indices = np.arange(column_transformer._n_features)
return ['x%d' % i for i in indices[column]]
if not hasattr(trans, 'get_feature_names'):
# >>> Change: Return input column names if no method avaiable
# Turn error into a warning
warnings.warn("Transformer %s (type %s) does not "
"provide get_feature_names. "
"Will return input column names if available"
% (str(name), type(trans).__name__))
# For transformers without a get_features_names method, use the input
# names to the column transformer
if column is None:
return []
else:
return [name + "__" + f for f in column]
return [name + "__" + f for f in trans.get_feature_names()]
### Start of processing
feature_names = []
# Allow transformers to be pipelines. Pipeline steps are named differently, so preprocessing is needed
if type(column_transformer) == sklearn.pipeline.Pipeline:
l_transformers = [(name, trans, None, None) for step, name, trans in column_transformer._iter()]
else:
# For column transformers, follow the original method
l_transformers = list(column_transformer._iter(fitted=True))
for name, trans, column, _ in l_transformers:
if type(trans) == sklearn.pipeline.Pipeline:
# Recursive call on pipeline
_names = get_feature_names(trans)
# if pipeline has no transformer that returns names
if len(_names) == 0:
_names = [name + "__" + f for f in column]
feature_names.extend(_names)
else:
feature_names.extend(get_names(trans))
return feature_names |
110edba851495174b45363b539c3741eb1273288 | raulperod/La-cena-de-los-filosofos | /filosofo.py | 1,814 | 3.515625 | 4 | import threading
import time
import random
class Filosofo(threading.Thread):
def __init__(self, id_filosofo, lista_de_palillos):
threading.Thread.__init__(self)
self.id_filosofo = id_filosofo
self.lista_de_palillos = lista_de_palillos
self.palillo_izquierdo = (self.id_filosofo+1) % len(self.lista_de_palillos)
self.palillo_derecho = self.id_filosofo
def obtener_tenedor_izquierdo(self):
self.lista_de_palillos[self.palillo_izquierdo].acquire()
print(f"El filosofo {self.id_filosofo} obtiene el tenedor izquierdo")
def obtener_tenedor_derecho(self):
self.lista_de_palillos[self.palillo_derecho].acquire()
print(f"El filosofo {self.id_filosofo} obtiene el tenedor derecho")
def liberar_tenedor_izquierdo(self):
self.lista_de_palillos[self.palillo_izquierdo].release()
print(f"El filosofo {self.id_filosofo} libera el tenedor izquierdo")
def liberar_tenedor_derecho(self):
self.lista_de_palillos[self.palillo_derecho].release()
print(f"El filosofo {self.id_filosofo} libera el tenedor derecho")
def comer(self):
print(f"El filosofo {self.id_filosofo} tiene hambre")
self.obtener_tenedor_izquierdo()
self.obtener_tenedor_derecho()
print(f"El filosofo {self.id_filosofo} come")
time.sleep( random.randint(1, 10) / 100 )
self.liberar_tenedor_derecho()
self.liberar_tenedor_izquierdo()
print(f"El filosofo {self.id_filosofo} termino de comer")
def pensar(self):
print(f"El filosofo {self.id_filosofo} piensa")
time.sleep( random.randint(1, 10) / 100 )
def run(self):
limite = 1000
for i in range(0, limite):
self.pensar()
self.comer() |
2f63c153ddd8bf757016c9286ba314bb93b3d1ff | essie-prog/This-is-Jeopardy-codecademy-project | /script.py | 697 | 3.65625 | 4 | import pandas as pd
pd.set_option('display.max_colwidth', -1)
project_data = pd.read_csv("jeopardy.csv")
print(project_data.head())
project_data.rename(columns =
{'Show Number' : "show_number",
' Air Date' : "air_date",
' Round' : "round",
' Category' : "category",
' Value' : "value",
' Question' : "question",
' Answer' : "answer"},
inplace = True)
print(project_data.head())
def filter_strings(word_list):
filtered_df = project_data[ project_data.apply(lambda row: all([word in row['question'] for word in word_list]), axis=1)]
return filtered_df
filtered_df = filter_strings(['King', 'England'])
print(filtered_df.head())
print('filtered_df.index: ' + str(len(filtered_df.index))) |
64bd34801ec0a09f2f745d0acdd3bc2832a53ee7 | san042/python-dsa | /mergeSort.py | 1,262 | 4.0625 | 4 | # MergeSort
datas = [ 12,19,31,4,23]
print("Initial State: ", datas)
def mergeSort(datas):
if len(datas) > 1:
mid = len(datas) //2
#breaking by left from offset:mid position
data_left = datas[:mid]
#breaking by right from offset:mid position
data_right = datas[mid:]
#TODO recursive call of each parts of the dataset
mergeSort(data_left)
mergeSort(data_right)
#TODO
i=0 # left array index
j=0 # right array index
k=0 # merged array index
# While both part has values
while i < len(data_left) and j<len(data_right):
if data_left[i] < data_right[j]:
datas[k] = data_left[i]
i += 1
else:
datas[k] = data_right[j]
j += 1
k += 1
#while left has value
while i < len(data_left):
datas[k] = data_left[i]
i += 1
k += 1
#while right has value
while j < len(data_right):
datas[k] = data_right[j]
j += 1
k += 1
mergeSort(datas)
print("Resultant state: ", datas)
|
1cb8870211c31a7a32dfe894f90ce032a076e41f | alyssonalvaran/kaizend | /session-6/test_lower.py | 196 | 3.59375 | 4 | def lowercase(x):
return x.lower()
def test_lowercase():
assert lowercase("TEAM KAIZEND") == "team kaizend"
def test_lowercase2():
assert lowercase("Team Kaizend") == "team kaizend"
|
5b3af7476665df38d47e9618df056fa80bd2b593 | jkopczyn/WEwUT-python | /ch4_overspecific/src/movie.py | 2,286 | 3.546875 | 4 | TYPE_NEW_RELEASE="New Release"
TYPE_REGULAR = "Regular"
TYPE_CHILDREN = "Children"
TYPE_UNKNOWN = "Unknown"
MOVIE_TYPES = set([TYPE_NEW_RELEASE, TYPE_REGULAR, TYPE_CHILDREN, TYPE_UNKNOWN])
class Movie(object):
def __init__(self, name, movietype=TYPE_UNKNOWN, actors=None):
self.name = name
self.actors = actors or []
if movietype not in MOVIE_TYPES:
raise TypeError("invalid movie type")
self.price = self.price_code(movietype)
def get_title(self, format="{0}", actor_count=0):
return format.format(self.name, *self.actors[:actor_count])
#In python the actor_count param is usually superfluous.
# Possibly always. But left in for example_porting clarity.
# if not, this would be: format.format(self.name, *self.actors)
def price_code(self, price_type):
if price_type is TYPE_CHILDREN:
return ChildrensPrice()
elif price_type is TYPE_NEW_RELEASE:
return NewReleasePrice()
elif price_type is TYPE_REGULAR:
return RegularPrice()
else:
raise TypeError("invalid movie type")
def get_charge(self, days_rented):
return self.price.get_charge(days_rented)
def get_points(self, days_rented):
return self.price.get_points(days_rented)
class Price(object):
def __init__(self):
self.min_days = 1
self.daily_rate = 1.5
self.min_price = self.daily_rate
def get_charge(self, days_rented):
if days_rented <= self.min_days:
return self.min_price
else:
return self.min_price+(days_rented - self.min_days)*self.daily_rate
def get_points(self, days_rented=1):
return 1
class ChildrensPrice(Price):
def __init__(self):
super(ChildrensPrice, self).__init__()
self.min_days = 2
class RegularPrice(Price):
def __init__(self):
super(RegularPrice, self).__init__()
self.min_days = 2
self.min_price = 2.0
class NewReleasePrice(Price):
def __init__(self):
super(NewReleasePrice, self).__init__()
self.daily_rate = 3.0
self.min_days = 0
self.min_price = 0
def get_points(self, days_rented):
return 2 if days_rented > 1 else 1
|
bef486db710139a36b42b619828392c4e6c0a57c | VitrSantos/cursoemvideo | /ex035.py | 540 | 4.15625 | 4 | #Exercício Python 35: Desenvolva um programa que leia o comprimento de três retas e diga ao usuário se elas podem ou não formar um triângulo.
print(20*"-=")
print('Analizador de triângulos')
print(20*"-=")
x = float(input('Digite o cumprimento da primeira reta: '))
y = float(input('Digite o cumprimento da segunda reta: '))
z = float(input('Digite o cumprimento da terceira reta: '))
if x < y + z and y < x + z and z < y + x:
print('As retas podem formar um triângulo')
else:
print('Não é possível formar um triângulo')
|
d570c013aa49ba58f43e39c4b34cb0dda91a0a43 | goodluckparis/Louplus | /jump7.py | 102 | 3.734375 | 4 | a = 0
while a < 100:
a += 1
if a % 7 ==0 or a % 10 == 7 or a //10 == 7:
pass
else:
print(a)
|
2d52c0218e2c248d3adcdb92701907d65d422726 | sumitshyamsukha/nets213-final-project | /src/analysis/analysis.py | 1,061 | 3.59375 | 4 | import csv
from math import sqrt
import operator
def ratings(ratings):
confidence = []
for i in ratings:
u = 0
d = 0
for j in ratings[i]:
if 'up' in j.lower():
u = u + 1
if 'down' in j.lower():
d = d + 1
confidence.append((i, _confidence(u, d)))
sorted_ratings = sorted(confidence, key=operator.itemgetter(1), reverse=True)
return sorted_ratings
# Source: http://www.evanmiller.org/how-not-to-sort-by-average-rating.html
def _confidence(ups, downs):
n = ups + downs
if n == 0:
return 0
z = 1.96 #1.44 = 85%, 1.96 = 95%
phat = float(ups) / n
return ((phat + z*z/(2*n) - z * sqrt((phat*(1-phat)+z*z/(4*n))/n))/(1+z*z/n))
with open('f901679.csv', 'rb') as csvfile:
reader = csv.reader(csvfile)
users = {}
for row in reader:
if row[17] not in users:
users[row[17]] = [row[15]]
else:
users[row[17]].append(row[15])
ratings = ratings(users)
for rating in ratings:
print rating[0].strip() + " " + str(rating[1])
|
bd1abd26c8096cf7a12f44c5f5a5cb7de1dd0ece | hyoging/CodingTest | /예제1.py | 130 | 3.671875 | 4 | a = "life is too short."
print(a[3:7])
print(a[2:])
print(a[:9])
print(a[:])
list1 = [1,2,3,4,5]
for a in list1:
print(a+1)
|
631768ba74b765b5956bf91067eccf5117c920b9 | jianhui-ben/leetcode_python | /445. Add Two Numbers II.py | 2,693 | 4 | 4 | #445. Add Two Numbers II
#You are given two non-empty linked lists representing two non-negative integers. The most significant digit comes first and each of their nodes contain a single digit. Add the two numbers and return it as a linked list.
#You may assume the two numbers do not contain any leading zero, except the number 0 itself.
#Follow up:
#What if you cannot modify the input lists? In other words, reversing the lists is not allowed.
#Example:
#Input: (7 -> 2 -> 4 -> 3) + (5 -> 6 -> 4)
#Output: 7 -> 8 -> 0 -> 7
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def reverse(self,l):
if not l:
return l
else:
first, second=l, l.next
cur= ListNode(first.val)
cur.next=None
while second:
temp=cur
cur=ListNode(second.val)
cur.next=temp
second=second.next
return cur
def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode:
## approach 1:reverse both and then add
##if not reverse input
len_1, len_2=0, 0
temp1, temp2=l1,l2
while temp1 or temp2:
if temp1:
len_1+=1
temp1=temp1.next
if temp2:
len_2+=1
temp2=temp2.next
start=ListNode()
cur_node=start
temp1, temp2=l1,l2
dif= abs(len_2-len_1)
if len_1>=len_2:
for _ in range(dif):
cur_node.next= ListNode(temp1.val)
cur_node= cur_node.next
temp1=temp1.next
else:
for _ in range(dif):
cur_node.next= ListNode(temp2.val)
cur_node= cur_node.next
temp2=temp2.next
while temp1 and temp2:
cur_node.next= ListNode(temp1.val+temp2.val)
cur_node=cur_node.next
temp1=temp1.next
temp2= temp2.next
##next we reverse the list
reverse_sum= self.reverse(start.next)
## take care of carry on:
start, carry_on= ListNode(), 0
temp= start
while reverse_sum:
value= reverse_sum.val+carry_on
if value>9:
carry_on=1
else:
carry_on=0
temp.next= ListNode((value)%10)
temp= temp.next
reverse_sum=reverse_sum.next
if carry_on==1: temp.next=ListNode(1)
# return start.next
return self.reverse(start.next)
|
a92986f6c43c750053312c8549017520f6881162 | neelshet007/PythonTuts | /oops2.py | 331 | 3.640625 | 4 | class Employee:
no_of_leaves=8
pass
harry=Employee()
rohan=Employee()
harry.name="Harry"
harry.salary=4554
harry.role="Instructor"
rohan.name="Rohan"
rohan.salary=4554
rohan.role="Student"
print(Employee.no_of_leaves)
print(Employee.__dict__)
Employee.no_of_leaves=9
print(Employee.__dict__)
print(Employee.no_of_leaves) |
5c5ee4027d45f1ba6b4a3e6dc0a7ef848b5a4247 | Kai-Wei-626/leetcode---Kai | /086. Partition List.py | 1,087 | 3.875 | 4 | # Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def partition(self, head, x):
"""
:type head: ListNode
:type x: int
:rtype: ListNode
"""
dummy = ListNode(0)
dummy.next = head
first = dummy
extra = ListNode(0) # dummy head for elements less than x
extra1 = extra #moving pointer for elements less than x
#first is iterator
while first.next:
if first.next.val < x:
extra1.next = first.next
extra1 = extra1.next
#extra1.next = None
# jump over the first.next
first.next = first.next.next
#no matter what, first advances to next node
else:
first = first.next
extra1.next = dummy.next
return extra.next
|
07ca2e8fb083d7e1b69ddb4392e75fbd3ad60831 | raghuprasadks/pythontutoriallatest | /workshop/Rangefunction.py | 306 | 4.5625 | 5 | #range(stop)
range1 = range(5)
print(range1)
#range(start,stop)
range2 = range(5,10)
print(range2)
#range(start,stop,step)
range3 = range(2,10,2)
print(range3)
#Using in for loop
for i in range1:
print('range1 ',i)
for i in range2:
print('range 2 ',i)
for i in range3:
print('range 3 ',i)
|
81670374c682e383aa31442f625a9f7717db4fde | ami-doshi/DP-5 | /unique-path-recursion.py | 793 | 3.546875 | 4 | class Solution:
def uniquePaths(self, m: int, n: int) -> int:
#first tried brute recursive method - 2^m*n
#2. Recursion with Table - m*n
#3. DP with table
#4. DP with single row
if m == 1 or n == 1:
return 1
return self.helper(m,n, 0, 0)
def helper(self, m: int, n:int, i:int, j:int) -> int:
#solution1 : recursive
#print(i,j)
#base
if i == m or j == n:
# print("in1")
return 0
if i == m-1 and j == n-1:
# print("in2")
return 1
#logic
#print("in3")
sums = self.helper(m, n, i+1,j) + self.helper(m,n, i,j+1)
#print("in4")
#print(sums)
return sums |
1c1ea5b29f13877c2956c0129b670228b72d0f23 | QingfengYang/demo-code | /python3/rb_sort/MergeSort.py | 1,267 | 3.71875 | 4 | #!/usr/bin/env python
# encoding: utf-8
import sys
class BadBoundary(Exception):
def __init__(self, msg):
super(BadBoundary, self).__init__(msg)
class MergeSort:
# sort arr including [start_index, end_index]
@staticmethod
def merge_sort(arr: [int], start_index: int, end_index: int):
if end_index == start_index:
return
mid = int((start_index + end_index)/2)
# sort left part: the result write back
MergeSort.merge_sort(arr, start_index, mid)
# sort right part
MergeSort.merge_sort(arr, mid + 1, end_index)
MergeSort.merge(arr, start_index, mid, end_index)
# left_start <= mid; mid < right_end
@staticmethod
def merge(arr: [], left_start: int, mid: int, right_end: int):
left_part = arr[left_start: mid + 1]
left_part.append(sys.maxsize)
right_part = arr[mid + 1: right_end + 1]
right_part.append(sys.maxsize)
l_pos = 0
r_pos = 0
for i in range(left_start, right_end + 1):
if left_part[l_pos] <= right_part[r_pos]:
arr[i] = left_part[l_pos]
l_pos = l_pos + 1
else:
arr[i] = right_part[r_pos]
r_pos = r_pos + 1
|
9bbf42aae446a240923f00399103c1f854539cca | yingkexu/pythongame | /NN2N3.py | 326 | 3.765625 | 4 | def add0(a, b):
return a + b
def times0(a,b):
return a * b
def divide0(a,b):
return a / b
print('input n')
n = int(input())
print('input n2')
n2 = int(input())
print('input n3')
n3 = int(input())
print('input n4')
n4 = int(input())
asonsum = add0(n,n2)
ssum = times0(n3,asonsum)
print(divide0(ssum,n4))
|
91fcd6e52b811c547c93bb95f3cd97ebe75d8d6d | BlazeKl/T2grafos | /funciones/conexo.py | 889 | 3.53125 | 4 | # x es el arreglo bidimensional (matriz)
# n es el largo del arreglo, matriz n*n cuadrada
#n es la cantidad de vertices o nodos
from numpy.linalg import matrix_power
def is_conexo(x,n):
arrgl = [[0 for x in range(n)] for y in range(n)]
matc=[[0 for x in range(n)] for y in range(n)]
for i in range(0,n):
for j in range(0,n):
arrgl[i][j] = x[i][j]
for i in range(0,n):
matc += matrix_power(arrgl, i) # funcion que eleva la matriz a n y va guardando la sumatoria hasta n
# ej matriz elev 0 + matriz elev 1 + ... + matriz elev n
# return matc #RETORNA UNA MATRIZ C
is_con = True
for i in range(0,n):
for j in range(0,n):
if matc[i][j] == 0 :
is_con = False
print("¿El grafo es conexo?")
if n == 0:
return False
return is_con |
7cf2cb0a2a345f5d2ac36af1f2862dd167823ad2 | turbek/helloworld | /100doors.py | 122 | 3.734375 | 4 | #looks for the square numbers between 1-10
#the square numbers have odd divider
y = [x * x for x in range(1,11)]
print(y)
|
8cdcc2b2ad0a668588985568e0f2a5b6d9d59d60 | calebxcaleb/Sneak-Game | /bullet.py | 820 | 3.71875 | 4 | import Paint
import pygame
class bullet:
player_copy = None
x = 0
y = 0
r = 10
speed = 0.5
x_speed = 0
y_speed = 0
def __init__(self, AI, player):
self.player_copy = player
self.x = AI.x
self.y = AI.y
self.setup()
def setup(self):
x_dif = self.player_copy.x - self.x
y_dif = self.player_copy.y - self.y
sum_dif = abs(x_dif) + abs(y_dif)
x_per = x_dif / sum_dif
y_per = y_dif / sum_dif
self.x_speed = self.speed * x_per
self.y_speed = self.speed * y_per
def move(self):
self.x += self.x_speed
self.y += self.y_speed
def paint_bullet(self):
pygame.draw.circle(Paint.screen, Paint.dark_red, (int(self.x), int(self.y)), self.r) |
372b13663866fe4bc667d4350ce2e4aa6fe1422b | kavisha-nethmini/Hacktoberfest2020 | /python codes/stack.py | 1,591 | 4.28125 | 4 | class Stack:
def __init__(self):
self.items = []
def push(self, item):
return self.items.append(item)
def pop(self):
if self.is_empty():
return print("Stack is Empty")
return self.items.pop()
def is_empty(self):
return self.items == []
def stack_length(self):
return len(self.items)
def peek(self):
if self.is_empty():
return print("Stack is Empty")
return self.items[-1]
def main():
stack = Stack()
print("Type Your Name : ")
name = input()
print("Welcome " + name)
print("Choose your option")
while True:
print(" 1. Push \n 2. Pop \n 3. Length \n 4. Top-Item \n 5. Show Stack")
print("________________________\n________________________")
choice = input()
if choice == "1":
print("Enter Element (Any Data Type)")
x = input()
stack.push(x)
print("*********************\n*********************")
elif choice == "2":
stack.pop()
elif choice == "3":
print('Length of the Stack is in Below')
print(stack.stack_length())
print("*********************\n*********************")
elif choice == "4":
print("Next Pop Item is in below")
print(stack.peek())
print("*********************\n*********************")
elif choice == "5":
print(stack.items)
print("*********************\n*********************")
main()
|
4fd6984d6550aebead797db5b3b733a1dc6c3ee9 | yqxd/LEETCODE | /60PermutationSequence.py | 972 | 4.03125 | 4 | '''
The set [1,2,3,...,n] contains a total of n! unique permutations.
By listing and labeling all of the permutations in order, we get the following sequence for n = 3:
"123"
"132"
"213"
"231"
"312"
"321"
Given n and k, return the kth permutation sequence.
Note:
Given n will be between 1 and 9 inclusive.
Given k will be between 1 and n! inclusive.
Example 1:
Input: n = 3, k = 3
Output: "213"
Example 2:
Input: n = 4, k = 9
Output: "2314"
'''
class Solution(object):
def getPermutation(self, n, k):
"""
:type n: int
:type k: int
:rtype: str
"""
import math
k = k - 1
A = [i for i in range(1, n + 1)]
now = n - 1
result = ''
while now >= 0:
loc = k // math.factorial(now)
k = k % math.factorial(now)
result += str(A[loc])
A.pop(loc)
now -= 1
return result
A = Solution()
print(A.getPermutation(3, 3))
|
3658b727b2f5f1cca3a9b354a085516bea5624cb | basvasilich/leet-code | /409.py | 364 | 3.5625 | 4 | # https://leetcode.com/problems/longest-palindrome
class Solution:
def longestPalindrome(self, s: str) -> int:
h = set()
for char in s:
if char in h:
h.remove(char)
else:
h.add(char)
if len(h) < 2:
return len(s)
else:
return len(s) - len(h) + 1
|
7c49110e9f236b766bfd3d093c82b74f8dbf63a3 | jcbrockschmidt/project_euler | /p015/solution.py | 503 | 3.890625 | 4 | #!/usr/bin/env python3
import math
from time import time
def count_lattice_paths(n):
"""
Counts the total number of possible routes in an `n`x`n` grid
from the top left to the bottom right moving only down and right.
"""
return int(math.factorial(2 * n) / math.factorial(n)**2)
if __name__ == '__main__':
start = time()
solu = count_lattice_paths(20)
elapse = time() - start
print('Solution: {}'.format(solu))
print('Solution found in {:.8f}s'.format(elapse))
|
6828934406c5c49d7a7ee97b8e8068a117591b31 | bazadactyl/leetcode-solutions | /src/p009-palindrome-number/solution.py | 503 | 3.625 | 4 | class Solution:
@staticmethod
def isPalindrome(x):
"""Leetcode runtime: 588ms
:type x: int
:rtype: bool
"""
def recurse(num_str):
if len(num_str) in [0, 1]:
return True
elif num_str[0] == num_str[-1]:
return recurse(num_str[1:-1])
else:
return False
if x < 0:
return False
else:
string = str(x)
return recurse(string)
|
9e81d4cba3d18e394dc49542d51e9a85540b803e | PedroTrujilloV/Python | /Python MIT course/week1_extemp.py | 548 | 4.0625 | 4 | varB = 2
varA = 3
if type(varA)== str:
if type(varB) == str:
lenA=len(varA)
lenB=len(varB)
if lenA == lenB:
print('equal')
elif lenA>lenB:
print('bigger')
else:
print('smaller')
else:
print('string involved')
elif type(varB) == float or type(varB) == int:
if varA == varB:
print('equal')
elif varA > varB:
print('bigger')
else:
print('smaller')
else:
print('string involved')
# type(varB)==str :
# |
d28f185f42f247ec04de51a7d7ca5745c9fb0bef | apcor/202006-GB-Python-Basics | /hw6/hw6_task3.py | 1,892 | 4 | 4 | '''Реализовать базовый класс Worker (работник),
в котором определить атрибуты:
name, surname, position (должность), income (доход).
Последний атрибут должен быть защищенным и ссылаться на словарь,
содержащий элементы:
оклад и премия, например, {"wage": wage, "bonus": bonus}.
Создать класс Position (должность) на базе класса Worker.
В классе Position реализовать методы получения
полного имени сотрудника (get_full_name) и
дохода с учетом премии (get_total_income).
Проверить работу примера на реальных данных
(создать экземпляры класса Position, передать данные,
проверить значения атрибутов, вызвать методы экземпляров).
'''
class Worker:
_income = {"wage": 10, "bonus": 5}
def __init__(self, name, surname, position):
self.name = name
self.surname = surname
self.position = position
class Position(Worker):
def __init__(self, name, surname):
super().__init__(name, surname, Worker._income)
self.wage = Worker._income["wage"]
self.bonus = Worker._income["bonus"]
self.position = 'simple worker'
def get_full_name(self):
print(f'Полное имя: {self.name} {self.surname}')
def get_total_income(self):
print(f'Полный доход работника {self.name} {self.surname} '
f'равен {self.wage + self.bonus}')
manager1 = Position('Иван', 'Иванов')
print(manager1.surname)
print(manager1.position)
manager1.get_full_name()
manager1.get_total_income()
|
76a1fd0a5a1b4fbc6bb3fb4bc92d5bca5fdfdb15 | lidia01/chavez_cabrera_rojas_barturen | /rojas_baturen/EJERCICIO035.py | 217 | 3.5 | 4 | #ventade camisetas
#Declarar
numero_de_camisetas=0
numero_camisetas=int(input("ingrese numero de camisetas:"))
#Procesing
costo=400*numero_camisetas
if(costo>500):
print("buena:")
else:
print("mala")
#fin_if
|
f64bd900b8f144b21d500527dae0ad041e7e39e0 | roeisavion/roeisproject2 | /תרגילי פונקציות/7.py | 268 | 3.984375 | 4 | def big(a,b):
if a>b:
return a
return b
def small(a,b) :
if b>a:
return a
return b
def between(x,y):
for i in range(x,y+1) :
print(i,end=' ')
a=int(input("enter a"))
b=int(input("enter b"))
between(small(a,b),big(a,b))
|
fd8e1dce2a0ab9799e90b37c5282a060c5656aec | AdamZhouSE/pythonHomework | /Code/CodeRecords/2524/60781/276987.py | 368 | 3.609375 | 4 | n=input()
str1=input()
pan=0
if(str1=='3 1 7 2 5'):
print('3 1 2 7 5',end=' ')
pan=1
if(str1=='1 2 3 4'):
print('1 2 3 4',end=' ')
pan=1
if(str1=='1 3 4 2'):
print('1 3 2 4',end=' ')
pan=1
if(str1=='6 4 5 8 1'):
print('6 4 1 5 8',end=' ')
pan=1
if(str1=='9 7 5 4 3'):
print('9 7 5 4 3',end=' ')
pan=1
if(pan==0):
print(str1) |
1b885001aa6f17d9679c599703b95e3d6a2cbdde | ansari3492/default-dictionary-named-tuple | /mohammed_burhan_cc26.py | 349 | 3.609375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Mon May 21 12:02:54 2018
@author: Lenovo
"""
from collections import OrderedDict
d = OrderedDict()
for _ in range(int(input())):
item, space, quantity = input().rpartition(' ')
d[item] = d.get(item, 0) + int(quantity)
print(d[item])
for item, quantity in d.items():
print(item, quantity) |
3fdd909a0937eb5eb67ddf02e555a47e50ca0b0b | buy/cc150 | /Node.py | 435 | 3.75 | 4 | class Node:
def __init__(self, data=None, next=None):
self.data = data
self.next = next
def __str__(self):
return '{ data: ' + str(self.data) + ' | next: ' + str(self.next) + ' }'
def setNext(self, node=None):
if node is None:
return None
self.next = node
return self
if __name__ == '__main__':
n1 = Node(1)
n0 = Node(0, n1)
print n0
print n1
n2 = Node(2)
n1.setNext(n2)
print n0
|
3fb6713a6f74f622ea11c1c8e70f09fba52bdc55 | pszelew/Rekrutacja-Robocik | /zadanie1/boat/vector3.py | 1,238 | 4.0625 | 4 | from __future__ import annotations
import math
class Vector3:
"""
A class used to represent a connection to 3D Vector
Attributes
----------
x : float
Value of x-axis
y : float
Value of y-axis
z : float
Value of z-axis
Methods
-------
dist(sec_vec: Vector3) -> float
Return distance to the point
"""
def __init__(self, x: float, y: float, z: float):
"""
Parameters
----------
x: float
Value of x-axis
y: float
Value of y-axis
z: float
Value of z-axis
"""
self.x = x
self.y = y
self.z = z
def dist(self, sec_vec: Vector3) -> float:
""" Return distance to the point
Parameters
----------
sec_vec: Vector3
Second point of operation
Returns
-------
float
Distance to the point described by sec_vec
"""
res: float
res = math.sqrt((self.x - sec_vec.x)**2
+ (self.y - sec_vec.y)**2
+ (self.y - sec_vec.y)**2)
# Calculate distance between two points
return res
|
e194316900bb7da30e43debb1eaf04bf4b54d8d5 | syurskyi/Algorithms_and_Data_Structure | /_algorithms_challenges/leetcode/lc-all-solutions/337.house-robber-iii/house-robber-iii.py | 499 | 3.65625 | 4 | # Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def rob(self, root):
"""
:type root: TreeNode
:rtype: int
"""
def dfs(root):
if not root:
return 0, 0
lpre, lppre = dfs(root.left)
rpre, rppre = dfs(root.right)
return max(root.val + lppre + rppre, lpre + rpre), lpre + rpre
return dfs(root)[0]
|
830553e6529d546eb6cc88b09d7b1253ee7ac763 | vinitapenmatsa/supervisedlearning-practice | /classification.py | 1,804 | 3.765625 | 4 | #%%
#Exploring data sets
from sklearn import datasets
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
plt.style.use('ggplot')
# Iris keys dict_keys(['data', 'target', 'target_names', 'DESCR', 'feature_names', 'filename'])
iris = datasets.load_iris()
#print(iris.DESCR)
#print(iris.target_names)
X = iris.data
y= iris.target
df = pd.DataFrame(X,columns=iris.feature_names)
#print(df.head())
#%%
from sklearn.neighbors import KNeighborsClassifier
from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3,random_state=21, stratify=y)
# Create a k-NN classifier with 6 neighbors: knn
knn = KNeighborsClassifier(n_neighbors=9)
# Fit the classifier to the data
knn.fit(X_train,y_train)
# Predict the labels for the training data X
y_pred = knn.predict(X_test)
print("Test set prediction:\n {}".format(y_pred))
knn.score(X_test, y_test)
#%%
# Model Complexity curves for different values on n in knn-neaest neighbours
neighbors = np.arange(1,15)
train_accuracy = np.empty(len(neighbors))
test_accuracy = np.empty(len(neighbors))
for i,k in enumerate(neighbors):
# set up knn classifier each time with K as the n_neighbor
knn = KNeighborsClassifier(n_neighbors=k)
# Fit the classifier to the training data
knn.fit(X_train, y_train)
#Compute accuracy on the training set
train_accuracy[i] = knn.score(X_train, y_train)
#Compute accuracy on the testing set
test_accuracy[i] = knn.score(X_test, y_test)
# Generate plot
plt.title('k-NN: Varying Number of Neighbors')
plt.plot(neighbors, test_accuracy, label = 'Testing Accuracy')
plt.plot(neighbors, train_accuracy, label = 'Training Accuracy')
plt.legend()
plt.xlabel('Number of Neighbors')
plt.ylabel('Accuracy')
plt.show()
|
845fbbedeb04ffd13c430459aa3078189b99e0f4 | alvinooo/advpython | /py2/solns/Flask/app/views.py | 4,840 | 3.5 | 4 | # views.py - views
from flask import render_template, flash, redirect, session, url_for, request, g
from flask_login import login_user, logout_user, current_user, login_required
from app import app, db, lm
from .forms import LoginForm, RegisterForm, CreateBookForm, DeleteBookForm
from .models import User, Role, Book
"""
The views are the handlers that respond to requests
from web browsers or other clients.
In Flask, handlers are written as Python functions.
Each view function is mapped to one or more request URLs.
"""
@app.route('/')
@app.route('/index')
@login_required
def index():
# read database to get list of books
user = g.user
print("user is authenticated: %r" % user.is_authenticated)
books = Book.query.order_by('author').all()
return render_template("index.html",
title='Home',
user=user,
books=books)
@app.route('/login', methods=['GET', 'POST'])
def login():
if g.user is not None and g.user.is_authenticated:
return redirect(url_for('index'))
form = LoginForm()
if form.data['register_me']:
print("Register me clicked!")
return redirect(url_for('register'))
if form.validate_on_submit():
user = User.query.filter_by(username=form.username.data).first()
if user is not None and user.verify_password(form.password.data):
# register this as a valid login
login_user(user)
return redirect(url_for('index'))
flash('Invalid username or password.')
return render_template('login.html', title='Sign In', form=form)
@app.route('/register', methods=['GET', 'POST'])
def register():
form = RegisterForm()
if form.validate_on_submit():
user = User.query.filter_by(username=form.username.data).first()
if user is None:
default_role = Role.query.filter_by(default=True).first()
user = User(username=form.username.data,
password=form.password.data, role=default_role)
db.session.add(user)
db.session.commit()
login_user(user)
return redirect(url_for('index'))
flash('Username is already taken. Choose a different username.')
return render_template('register.html',
title='Register Me', form=form)
"""
This function will be used by Flask-Login to load a user from the database.
This function is registered with Flask-Login through the
lm.user_loader decorator. Note that user ids in Flask-Login are
always unicode strings, so a conversion to an integer is necessary
before we can send the id to Flask-SQLAlchemy.
"""
@lm.user_loader
def load_user(id):
return User.query.get(int(id))
@app.before_request
def before_request():
g.user = current_user
@app.after_request
def apply_caching(response):
response.headers.add('Cache-Control',
'no-store, no-cache, must-revalidate, post-check=0, pre-check=0')
return response
@app.route('/logout')
def logout():
logout_user()
return redirect(url_for('index'))
@app.route('/add_book', methods=['GET', 'POST'])
@login_required
def add_book():
if g.user is not None and not g.user.role.can_modify:
flash("Sorry. You don't have administrative privileges.")
return redirect(url_for('index'))
form = CreateBookForm()
if form.validate_on_submit():
book = Book(author=form.author.data, title=form.title.data,
category=form.category.data, copies=1)
db.session.add(book)
db.session.commit()
return redirect(url_for('index'))
return render_template('add_book.html', title='Add Book', form=form)
def do_delete(del_books):
if (len(del_books) == 0):
flash("No books selected for deletion.")
else:
for book in del_books:
db.session.delete(book)
flash("Deleted book %s, '%s'" %(book.author, book.title))
db.session.commit()
@app.route('/delete_book', methods=['GET', 'POST'])
@login_required
def delete_books():
if g.user is not None and not g.user.role.can_modify:
flash("Sorry. You don't have administrative privileges.")
return redirect(url_for('index'))
books = Book.query.order_by('author').all()
forms = []
# create a checkbox boolean form for each book
for book in books:
form = DeleteBookForm(prefix=str(book.id))
forms.append(form)
if request.method=='POST':
del_books = []
for book,form in zip(books,forms):
if form.delete_bool.data:
del_books.append(book)
do_delete(del_books)
return redirect(url_for('index'))
# Jinja templates don't support zip, so zip our data first!
return render_template("delete_books.html",
title='Delete Book', form=forms[0], data=zip(books,forms))
|
9d14c96a545193c5d96b8210f8ff4a468a235c31 | soumitra9/Competitive-Coding-7 | /meeting_rooms2.py | 1,091 | 3.84375 | 4 | # Time Complexity : Add - O(n log n)
# Space Complexity : O(n)
# Did this code successfully run on Leetcode : Yes
# Any problem you faced while coding this : No
'''
0. Sort the meetings
1. Use min heap to acces the room that has earliest end time
2. So we make a min hap based on ending time.
3. If start time of an incoming meeting is more then peek, then we can pop and update the new meeting end time
4. Else push it to heap, thus allotting a new room
5. The length of heap gives the room required
'''
import heapq
def minMeetingRooms(intervals):#: List[List[int]]) -> int:
if not intervals or len(intervals)<1:
return
intervals = sorted(intervals, key=lambda x:x[0])
heap_list = []
for i in range(len(intervals)):
print (heap_list)
if i==0:
heapq.heappush(heap_list, intervals[i][1])
elif intervals[i][0] < heap_list[0]:
heapq.heappush(heap_list, intervals[i][1])
else:
heapq.heappop(heap_list)
heapq.heappush(heap_list, intervals[i][1])
return len(heap_list) |
404b1ab13c3c2c05d0ad9e115fea6a6adcd25349 | hkskunal077/Operating_System_Programming | /OSCodeLab2SJFpreemtive.py | 1,436 | 3.53125 | 4 | #NON_PREMPTIVE SJF WITH SAME ARRIVAL TIME = 0
n=int(input("Process Count\n"))
processes=[]
for i in range(0,n):
processes.append(i)
#Process list upgraded
arrival_time = []
print("Enter Arrial time correspondingly?? ")
for proc in range(n):
arrival_time.append(int(input()))
#Arrival Time list upgraded
exec_time = []
print("Exeution time correspondingly?? ")
for proc in range(n):
exec_time.append(int(input()))
#Execution Time list upgraded
exec_time = sorted(exec_time)
print(exec_time)
#Execution time list sorted and stored
Waiting_time= []
Waiting_time.append(0)
Turnaround_time = []
avg_Waiting_time = 0
avg_Turnaround_time = 0
Turnaround_time.append(exec_time[0])
def turntime()
#Loop only for the rest of processes.
for i in range(1,len(exec_time)):
Waiting_time.insert(i,int(Waiting_time[i-1])+int(exec_time[i-1]))
Turnaround_time.insert(i,int(Waiting_time[i])+int(exec_time[i]))
avg_Waiting_time+=Waiting_time[i]
avg_Turnaround_time+=Turnaround_time[i]
avg_Waiting=float(avg_Waiting_time)/n
avg_Turnaround=float(avg_Turnaround_time)/n
print("\nProcess\t Execution Time\t Waiting Time\t Turn Around Time")
for i in range(0,n):
print(str(processes[i])+"\t\t"+str(exec_time[i])+"\t\t"+str(Waiting_time[i])+"\t\t"+str(Turnaround_time[i]))
print("\n")
print("Waiting Time (AVG) "+str(avg_Waiting), "\t\t\tTurn Around Time (AVG) "+str(avg_Turnaround))
|
18aaf5a7ac37603a43bcbcb25210d13aa359f7ba | shadowp2810/python_MapMarkerGenerator | /mapGen.py | 4,142 | 3.5625 | 4 | import folium #used for visualizing geospatial data
import pandas #data analysis and manipulation tool or library
data = pandas.read_csv( "importedFiles/Volcanoes.txt" ) #creates a data frame
theLatitudes = list(data["LAT"]) #makes a list from the LON column from Volcanoes.txt
theLongitudes = list(data["LON"])
theVolcanoesName = list(data["NAME"])
theElevation = list(data["ELEV"])
def color_producer( elevation ): #function for volcano marker colours by elevation
if elevation < 1000:
return 'green'
elif 1000 <= elevation < 3000:
return 'orange'
else:
return 'red'
html = """
Hi! I'm <br>
Volcano: <a href="https://www.google.com/search?q=%%22%s%%22"
target="_blank">%s</a>
<br>
Height: %s m
""" #for iframe for each volcano markers
map = folium.Map( #map object created in folium. Feature groups will be added to it.
location = [ 38.58 , -99.09 ], #kansas center lat and lon
zoom_start = 5, #zoom_start = 4 for North America view, 5 for USA view
tiles = "Stamen Terrain" ) #other tileset options built into folium
theFeatureGroupPopulation = folium.FeatureGroup( name = "2005 Population" ) #for more layers and organization
theFeatureGroupPopulation.add_child(
folium.GeoJson( #GeoJson polygon 2005 data
data = open( 'importedFiles/world_2005.json' ,
'r' ,
encoding='utf-8-sig').read() ,
# style_function = lambda x: { #By different colours
# 'fillColor' : '#FFCC00' if x[ 'properties' ][ 'POP2005' ] < 10000000
# else '#FF9900' if 10000000 <= x[ 'properties' ][ 'POP2005' ] < 20000000
# else '#FF6600' if 20000000 <= x[ 'properties' ][ 'POP2005' ] < 100000000
# else '#FF0000' if 100000000 <= x[ 'properties' ][ 'POP2005' ] < 500000000
# else '#990000' , 'fillOpacity' : '.5'
# },
style_function = lambda x: { #By single colour opacities
'fillColor' : '#FF6600',
'fillOpacity' : '0.1' if x[ 'properties' ][ 'POP2005' ] < 5000000
else '0.15' if 5000000 <= x[ 'properties' ][ 'POP2005' ] < 10000000
else '0.3' if 10000000 <= x[ 'properties' ][ 'POP2005' ] < 20000000
else '0.45' if 20000000 <= x[ 'properties' ][ 'POP2005' ] < 100000000
else '0.6' if 100000000 <= x[ 'properties' ][ 'POP2005' ] < 500000000
else '0.75'
},
# zoom_on_click = True ,
))
theFeatureGroupVolcanoes = folium.FeatureGroup( name = "Volcanoes" )
for theLat, theLon, theName, theElev in zip( theLatitudes,
theLongitudes,
theVolcanoesName,
theElevation ): #To iterate multiple values in an array or list
iframe = folium.IFrame( html = html % ( theName , theName , theElev ),
width = 200,
height = 100 ) #to google search by clicking volcano name in popup
# theFeatureGroup.add_child(folium.Marker(location=[theLat, theLon], popup="Hi! I'm %s with an elevation of %s" % (theName,theElev), icon=folium.Icon(color='green')))
theFeatureGroupVolcanoes.add_child(
folium.CircleMarker(
location = [ theLat , theLon ],
popup = folium.Popup( iframe ),
radius = 10,
color = 'black',
opacity = 1,
fill_color = color_producer( theElev ),
fill_opacity = 0.75 ),)
map.add_child( theFeatureGroupPopulation )
map.add_child( theFeatureGroupVolcanoes )
map.add_child( folium.LayerControl() ) #To select the visible layers, top right corner
map.save( "generatedFiles/Map.html" )
|
955d24fd199d5b80073170d9301c42100aaec812 | sarveshdakhane/Python | /Algo and DS in Python/DoubleLinklist.py | 1,542 | 4.15625 | 4 | class Node:
def __init__(self, Value=None):
self.Previous = None
self.Value = Value
self.Next = None
class DoubleLinkList:
def __init__(self):
self.Head = None
def Insert_at_begining(self,ele):
NewNode=Node(ele)
if self.Head == None:
self.Head=NewNode
else:
NewNode.Next=self.Head
self.Head.Previous=NewNode
self.Head=NewNode
def Insert_at_ending(self,ele):
NewNode=Node(ele)
p=self.Head
if self.Head == None:
self.Head=NewNode
else:
while p.Next is not None:
p=p.Next
p.Next=NewNode
NewNode.Previous=p
NewNode.Next=None
def PrintDoubleLinkList(self,TargetList):
p=TargetList.Head
while p is not None:
print("Value : {} \n". format(p.Value))
p=p.Next
DoubleLinkList = DoubleLinkList()
DoubleLinkList.Head = Node("Prem")
Node1 = Node("Ram")
Node2 = Node("Sham")
DoubleLinkList.Head.Next=Node1
DoubleLinkList.Head.Next.Previous=DoubleLinkList.Head
DoubleLinkList.Head.Next.Next=Node2
DoubleLinkList.PrintDoubleLinkList(DoubleLinkList)
print("After insterting Element at first (i.e. 'Rahul') \n")
DoubleLinkList.Insert_at_begining("Rahul")
DoubleLinkList.PrintDoubleLinkList(DoubleLinkList)
print("After insterting Element at End (i.e. 'Rushi') \n")
DoubleLinkList.Insert_at_ending("Rushi")
DoubleLinkList.PrintDoubleLinkList(DoubleLinkList)
|
9bfa6f7d7bda131f54206c59ffd5f08252e3d5b2 | srwhite5/rockPaperScissors | /rockPaperScissors.py | 1,894 | 4.125 | 4 | '''
Created on May 3, 2020
@author: ITAUser
'''
from random import random
keepPlaying = True
while keepPlaying == True:
print("Welcome to Rock Paper Scissors.")
print("Best 2 out of 3 wins. Press 'q' to quit")
rock = 1
scissors = 2
paper = 3
playerScore = 0
computerScore = 0
while(playerScore < 2 and computerScore < 2):
computerChoice = random.randint(1,3)
playerChoice = input("Please choose Rock, Paper, or Scissors")
playerChoice = playerChoice.lower()
if(playerChoice == 'q'):
keepPlaying = False
break
elif((playerChoice == "rock" and computerChoice == 1) or (playerChoice == "scissors" and computerChoice == 2) or (playerChoice == "paper" and computerChoice == 3)):
print("DRAW")
print("Player's Score =" + playerScore._str_() + "Computer's Score =" + computerScore._str_())
elif((playerChoice == "rock" and computerChoice == 2) or (playerChoice == "scissors" and computerChoice == 3 ) or (playerChoice == "paper" and computerChoice == 1)):
playerScore = playerScore + 1
print("Player's Score =" + playerScore._str_() + "Computer's Score =" + computerScore._str_())
print("ROUND WON")
elif((playerChoice == "rock" and computerChoice == 3) or (playerChoice == "scissors" and computerChoice == 1) or (playerChoice == "paper" and computerChoice == 2)):
computerScore = computerScore + 1
print("Player's Score =" + playerScore._str_() + "Computer's Score =" + computerScore._str_())
print("ROUND LOST")
else:
print("Input is not valid.Try again.")
print("Thank you for playing!")
if(playerScore == 2):
print("WINNER")
if(computerScore == 2):
print("LOSER. COMPUTER WINS.")
print("Player's Score =" + playerScore._str_() + "Computer's Score =" + computerScore._str_())
|
fc44df2828b95146de312a9ac03ef78bca964055 | JessicaKarinaLopezMarroquin/Python_Crash_Course | /JKarinaLopezM/1Loops.py | 219 | 3.765625 | 4 | robots = ["nomad","Ponginator","Alfred"]
for robot in robots:
print(robot)
for num,robot in enumerate(robots):
print(num,robot)
count = 1
while count < 5:
print(count)
count = count+1
input()
|
cab021dec1177a4b7c776ce2e4a822492dda52c4 | panarnold/python-projects | /python-theory/operator-and-function-overloading.py | 2,950 | 3.65625 | 4 | #operator overloading: te same operacje daja inny behawior dla obiektów innych klas
#wbudowane funkcjonalnosci pythona mają taką konwencję nazwy, ze daje sie double underscory do nich
# np __len__() koresponduje do len(), a __add__() do operatora '+'
# z defaulta, wiekszosc wbudowanych funkcji i operatorow nie bedzie pracowala z obiektami moich klas
# trzeba te metody dodac, zeby byly kompatybilne
#dlatego len() jest rownoznaczne z obj.__len__() , a a[0] rownoznaczne z a.__getitem__(0)
# jak wpisze sie dir(obj), mamy liste funkcji ktore wspiera: wbudowane i te doslowne, a oprocz tego wlasciwosci
#overloading
class Order:
def __init__(self, cart, customer):
self.cart = list(cart)
self.customer = customer
def __len__(self):
return len(self.cart) #przy overloadingu tej samej funkcji musi zwracac domyslnie to samo, inaczej TypeError
def __bool__(self):
return len(self.cart) > 0
def __add__(self, other):
new_cart = self.cart.copy()
new_cart.append(other)
return Order(new_cart, self.customer)
def __iadd__(self, other): #chodzi o +=
self.cart.append(other)
return self # ale gdyby byl return 'HEY DUPA', to overload tej funkcji by był
def __getitem__(self, key):
return self.cart[key]
def __radr__(self, other):
new_cart = self.cart.copy()
new_cart.insert(0, other)
return Order(new_cart, self.customer)
order = Order(['dupa','kał','mors'], 'Arnold')
len(order)
#interpretacja abs - absolute value of vector
class Vector:
def __init__(self, x_comp, y_comp):
self.x_comp = x_comp
self.y_comp = y_comp
def __abs__(self):
return (self.x_comp ** 2 + self.y_comp ** 2) ** 0.5
def __str__(self):
return f'{self.x_comp}i{self.y_comp:+}j'
#__repr__ : parsable representation of an object
def __repr__(self):
return f'Vector({self.x_comp}, {self.y_comp})'
# __str__
# complete example
from math import hypot, atan, sin, cos
class CustomComplex:
def __init__(self, real, imag):
self.real = real
self.imag = imag
def conjugate(self):
return self.__class__(self.real, self.imag) #ekwiwalent od CustomComplex(real, imag)
def argz(self):
return atan(self.imag / self.real)
def __abs__(self):
return hypot(self.real, self.imag)
def __repr__(self):
return f'{self.__class__.__name__}({self.real}, {self.imag})'
def __str__(self):
return f'({self.real}{self.imag:+}j)'
def __add__(self, other):
if isinstance(other, float) or isinstance(other, int):
real_part = self.real + other
imag_part = self.imag
if isinstance(other, CustomComplex):
real_part = self.real + other.real
imag_part = self.imag + other.imag
return self.__class__(real_part, imag_part)
|
6375417beabdf08d9438e422be79be2a859b41be | jawhelan/PyCharm | /PyLearn/Exercise Files/07 Loops/iterators_else.py | 408 | 4 | 4 | #!/usr/bin/python3
# iterators.py by Bill Weinman [http://bw.org/]
# This is an exercise file from Python 3 Essential Training on lynda.com
# Copyright 2010 The BearHeart Group, LLC
def main():
my_string = 'this is a string '
item = 0
while(item < len(my_string)):
print(my_string[item], end='')
item += 1
else:
print("this is else 1")
if __name__ == "__main__": main()
|
b9e7bdfc9215715682b3ffb40e3c4b360faabf94 | Warriorchief/Euler38_PandigitalMultiples | /Euler38_PandigitalMultiples.py | 1,510 | 4.0625 | 4 | """
Euler38_PandigitalMultiples
Take the number 192 and multiply it by each of 1, 2, and 3:
192 × 1 = 192
192 × 2 = 384
192 × 3 = 576
By concatenating each product we get the 1 to 9 pandigital, 192384576.
We will call 192384576 the concatenated product of 192 and (1,2,3)
The same can be achieved by starting with 9 and multiplying by 1, 2, 3, 4, and 5,
giving the pandigital, 918273645, which is the concatenated product of 9 and (1,2,3,4,5).
What is the largest 1 to 9 pandigital 9-digit number that can be formed as the
concatenated product of an integer with (1,2, ... , n) where n > 1?
"""
import time
def make_concat(x):
s=str(x)
i=2
while len(s)+len(str(x*i))<10:
s+=str(x*i)
i+=1
if len(s)!=9:
return '0' #if it doesn't make a 9-term integer, mark it as eliminated using '0'
return s
def assemble_concats():
c=[]
i=3
while i<10000:
c.append(make_concat(i))
i+=1
#print(len(c))
return c
things=sorted(assemble_concats(),reverse=True) #print(len(things)) #--> 9997
print(things)
def is_pandigital(x):
for i in range(1,10):
if str(i) not in x:
return False
return True
def main():
for t in things:
if is_pandigital(str(t)):
print('found it!',t)
return t
start=time.time()
main() #--> found it! 932718654 CORRECT
elapse=time.time()-start
print('this took processing time:',elapse) #this took processing time: 0.0009310245513916016 |
4bf912c62c2b83e35bf50a22c0e1a86ef1271f4c | msj2/prj_Eul | /Find the Prime Factors of 600851475143 | 2,041 | 3.5 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# untitled.py
#
# Copyright 2016 keshanna <keshanna@VATAPI>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
# MA 02110-1301, USA.
#
#
#ver1
# Find the Prime Factors of 600851475143
# Prime factors of 13195 are 5,7,13, 29
#
# Loop thru odd numbers until square root of 600851475143
# check if the number is prime
# if yes, check modulo division leads to 0
# if no, continue
import math
#math.sqrt(x)
def is_prime(prime):
n_max = int(math.sqrt(prime))
print "Module is_prime.......Checking if", prime, "is a prime no.... "
n_max += 1
for n in range(3, n_max, 2):
if ( prime % n == 0 ):
return 0
else:
continue
return 1
# 71 divides this & is a prim no. but not showing up in my prog....
number = 600851475143
#number = 13195
n = 3
#We aren't checking for prime here,So, go all the way till number.
#nmax = int(math.sqrt(number))
#print nmax
#for n in range(3, nmax, 2):
#OverflowError: range() result has too many items
#for n in range(3, nmax, 2):
while (n < number):
#print n
# If this number modulo divides the given number
if(number % n == 0 ):
print n, "divides ", number
# If this number is a prime number
if (is_prime(n) == 1):
print n, " is a prime divisor of ", number
else:
print n, " is a divisor, but not prime no. "
n = n + 1
|
0b1518c0359db230e0cdc0117783affcb6cce0d7 | toddlerya/Core-Python-Programming-Homework | /Chapter_6/6-17.py | 449 | 3.75 | 4 | #!/usr/bin/env python
# coding:utf-8
"""
6–17.方法.实现一个叫 myPop()的函数,功能类似于列表的 pop()方法,用一个列表作为输入,
移除列表的最新一个元素,并返回它.
"""
def myPop(alist):
new_list = alist[:-1]
return new_list
if __name__ == "__main__":
get_list = input("Please input your list: \n")
print "The initializing list is %s" % get_list
print "The new list is", myPop(get_list)
|
377f1b437e5d14f078cf1383feab6978edb95f4a | pathim/advent_of_code_2020 | /6/main.py | 498 | 3.828125 | 4 | count=0
count_every=0
with open('input') as f:
current=set()
every_letter=set(chr(ord('a')+x) for x in range(26))
everyone=set(every_letter)
for line in f:
line=line.strip()
if not line:
count+=len(current)
current=set()
count_every+=len(everyone)
everyone=set(every_letter)
continue
current.update(set(line))
everyone.intersection_update(set(line))
count+=len(current)
count_every+=len(everyone)
print(f"First solution {count}")
print(f"Second solution {count_every}") |
247b362986c745c55642f3490c53399ecb9c3015 | olivier555/projet_metaheuristiques | /solution.py | 7,914 | 3.59375 | 4 | """
This class describes a solution (wihtout considering the data)
"""
import numpy as np
class Solution():
def __init__(self, n, sensors = None):
""" We initialize the solution with a boolean list
or a list of False if no list is provided.
"""
if sensors is None:
sensors = np.zeros(n,dtype = 'bool')
self.sensors_index = set()
else:
sensors = np.array(sensors, 'bool')
assert sensors.size == n, "size of sensors must be equal to n %s"%n
self.sensors_index = set(np.where(sensors)[0])
self.sensors = sensors
self.value = sum(self.sensors == 1)
self.n = n
def compute_value(self):
""" Compute the value of the solution.
It's the value that we try to optimize
"""
return self.value
def detected(self, data):
""" Check if all targets are detected by the solution
"""
M = data.get_matrix_sens()
# The sink doesn't have to be detected hence the 1:
return (np.matmul(M, self.sensors)[1:] >= 1).all()
# we want all the targets to be detected except the hole
def reached(self, data):
"""Getting all the sensors that are reachable from the sink.
"""
index_sensors = self.get_index_sensors().copy()
next_vertex = set(data.get_neighbours_com(0)).intersection(index_sensors)
reached = {0}.union(next_vertex)
if 0 in next_vertex:
next_vertex.remove(0)
marked = {0}
while len(next_vertex) > 0 and len(reached) < self.value + (1 - self.sensors[0]):
index = next_vertex.pop()
marked.add(index)
new = set(data.get_neighbours_com(index)).intersection(index_sensors) - marked
reached = reached.union(new)
next_vertex = next_vertex.union(new)
return reached
def related(self, data):
""" Check if the current solution is connex.
The function uses a method of graph traversal starting from the sink.
"""
reached = self.reached(data)
return len(reached) == self.value + (1 - self.sensors[0])
# we want to reach all the sensors from the hole, but we don't want
# to count the hole twice if it's a sensor
def related_removed(self, data, id_removed):
""" A connexity check adapted to the remove_targets function.
We only check if all the neighbours of id_removed are still connected in the new graph
<!> The initial solution before the removal must be eligible
"""
index_sensors = self.get_index_sensors() + [0]
neighbours_com = list(set(data.get_neighbours_com(id_removed)).intersection(index_sensors))
set_neighbours = set(neighbours_com)
first_vertex = neighbours_com[0]
next_vertex = set(data.get_neighbours_com(first_vertex)).intersection(index_sensors)
reached = {first_vertex}.union(next_vertex)
if first_vertex in next_vertex:
next_vertex.remove(first_vertex)
marked = {first_vertex}
while len(next_vertex) > 0 and not set_neighbours.issubset(reached):
index = next_vertex.pop()
marked.add(index)
new = set(data.get_neighbours_com(index)).intersection(index_sensors) - marked
reached = reached.union(new)
next_vertex = next_vertex.union(new)
return set_neighbours.issubset(reached)
def related_switch(self, data, id_removed, id_add):
""" A connexity check adapted to the switch class.
We only check if all the neighbours of id_removed are still connected to id_add in the new graph
<!> The initial solution before the switch must be eligible
"""
index_sensors = self.get_index_sensors() + [0]
set_neighbours = set(data.get_neighbours_com(id_removed)).intersection(index_sensors)
first_vertex = id_add
next_vertex = set(data.get_neighbours_com(first_vertex)).intersection(index_sensors + [0])
reached = {first_vertex}.union(next_vertex)
if first_vertex in next_vertex:
next_vertex.remove(first_vertex)
marked = {first_vertex}
while len(next_vertex) > 0 and not set_neighbours.issubset(reached):
index = next_vertex.pop()
marked.add(index)
new = set(data.get_neighbours_com(index)).intersection(index_sensors) - marked
reached = reached.union(new)
next_vertex = next_vertex.union(new)
return set_neighbours.issubset(reached)
def related_two_to_one(self, data, id_removed_1, id_removed_2, id_add):
""" A connexity check adapted to the search_two_to_one function.
We only check if all the neighbours of id_removed_1 and id_removed_2
are connected to id_add in the new graph
<!> The initial solution before the search must be eligible
"""
index_sensors = self.get_index_sensors() + [0]
set_neighbours_1 = set(data.get_neighbours_com(id_removed_1)).intersection(index_sensors)
set_neighbours_2 = set(data.get_neighbours_com(id_removed_2)).intersection(index_sensors)
set_neighbours = set_neighbours_1.union(set_neighbours_2)
first_vertex = id_add
next_vertex = set(data.get_neighbours_com(first_vertex)).intersection(index_sensors + [0])
reached = {first_vertex}.union(next_vertex)
if first_vertex in next_vertex:
next_vertex.remove(first_vertex)
marked = {first_vertex}
while len(next_vertex) > 0 and not set_neighbours.issubset(reached):
index = next_vertex.pop()
marked.add(index)
new = set(data.get_neighbours_com(index)).intersection(index_sensors) - marked
reached = reached.union(new)
next_vertex = next_vertex.union(new)
return set_neighbours.issubset(reached)
def eligible(self, data):
""" Check if the solution is eligible.
"""
return self.detected(data) and self.related(data)
def eligible_switch(self, data, id_removed, id_add):
""" Check if the solution is eligible after a switch.
<!> The initial solution before the switch must be eligible
"""
return self.detected(data) and self.related_switch(data, id_removed, id_add)
def eligible_two_to_one(self, data, id_removed_1, id_removed_2, id_add):
""" Check if the solution is eligible after a search_two_to_one.
<!> The initial solution before the search must be eligible
"""
return self.detected(data) and self.related_two_to_one(data, id_removed_1, id_removed_2, id_add)
def get_size(self):
return self.n
def copy(self):
""" Create a copy of the solution
"""
s = Solution(self.n, self.sensors.copy())
return s
def add_sensor(self, i):
""" add a sensor and update the value
"""
if not self.sensors[i]:
self.sensors[i] = True
self.value += 1
self.sensors_index.add(i)
def remove_sensor(self, i):
""" remove a sensor and update the value
"""
if self.sensors[i]:
self.sensors[i] = False
self.value -= 1
self.sensors_index.remove(i)
def is_sensor(self, index):
""" check if there is a sensor at index
"""
return self.sensors[index]
def get_index_sensors(self):
""" get a list of all the sensors in the solution.
"""
return list(self.sensors_index)
if __name__ == '__main__':
from data import Data
data = Data(1,1,2,2)
s = Solution(4,[0,0,1,0])
print(s.value)
print(s.compute_value())
s.add_sensor(1)
print(s.sensors_index)
print(s.get_index_sensors())
s.remove_sensor(3)
print(s.value)
|
a804bc91859358f8ec4fe8e174ede457a67e3c2b | japawka/Bakery | /S03 Klasy/24 word without clases.py | 472 | 4 | 4 | cake_01 = {
'taste': 'vanilia',
'glaze': 'chocolade',
'text': 'Happy Brithday',
'weight': 0.7
}
cake_02 = {
'taste': 'tee',
'glaze': 'lemon',
'text': 'Happy Python Coding',
'weight': 1.3
}
def show_cake_info(cake):
print('{} cake, with {} glaze, with text "{}", and weight of {} kg'.format(
cake['taste'], cake['glaze'], cake['text'], cake['weight']))
cakes = [cake_01, cake_02]
for cake in cakes:
show_cake_info(cake) |
ff9ed762c56160222e580326943fd0353db9a7e1 | PavelBLab/machine_learning | /assignment_3/assignment_3.py | 7,146 | 3.734375 | 4 | import numpy as np
import pandas as pd
import warnings
warnings.filterwarnings('ignore')
'''
Question 1
Import the data from fraud_data.csv. What percentage of the observations in the dataset are instances of fraud?
This function should return a float between 0 and 1.
'''
def answer_one():
df = pd.read_csv('fraud_data.csv')
# print(df)
# print(df['Class'][df['Class'] == 1].size) # 1 is froad
return df['Class'][df['Class'] == 1].size / df['Class'].size
# print(answer_one())
from sklearn.model_selection import train_test_split
df = pd.read_csv('fraud_data.csv')
X = df.iloc[:, :-1]
y = df.iloc[:, -1]
X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=0)
'''
Question 2
Using X_train, X_test, y_train, and y_test (as defined above), train a dummy classifier that classifies everything as the majority class of the training data. What is the accuracy of this classifier? What is the recall?
This function should a return a tuple with two floats, i.e. (accuracy score, recall score).
'''
def answer_two():
from sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score
from sklearn.dummy import DummyClassifier
from sklearn.metrics import recall_score
dummy_clf = DummyClassifier(strategy='most_frequent').fit(X_train, y_train)
y_dummy_predictions = dummy_clf.predict(X_test)
# print(y_dummy_predictions)
# print('Accuracy: {:.2f}'.format(accuracy_score(y_test, y_dummy_predictions)))
# '='
# print('Accuracy: {:.2f}'.format(dummy_clf.score(X_test, y_test)))
# print('Accuracy: {:.2f}'.format(recall_score(y_test, y_dummy_predictions)))
return (accuracy_score(y_test, y_dummy_predictions), recall_score(y_test, y_dummy_predictions))
# print(answer_two())
'''
Question 3
Using X_train, X_test, y_train, y_test (as defined above), train a SVC classifer using the default parameters. What is the accuracy, recall, and precision of this classifier?
This function should a return a tuple with three floats, i.e. (accuracy score, recall score, precision score).
'''
def answer_three():
from sklearn.metrics import accuracy_score, recall_score, precision_score
from sklearn.svm import SVC
SVC_clf = SVC().fit(X_train, y_train)
# print(SVC_clf)
y_SVC_prediction = SVC_clf.predict(X_test)
# print(y_SVC_prediction)
# print('Accuracy: {:.2f}'.format(accuracy_score(y_test, y_SVC_prediction)))
# print('Accuracy: {:.2f}'.format(recall_score(y_test, y_SVC_prediction)))
# print('Accuracy: {:.2f}'.format(precision_score(y_test, y_SVC_prediction)))
return (accuracy_score(y_test, y_SVC_prediction), recall_score(y_test, y_SVC_prediction), precision_score(y_test, y_SVC_prediction))
# print(answer_three())
'''
Question 4
Using the SVC classifier with parameters {'C': 1e9, 'gamma': 1e-07}, what is the confusion matrix when using a threshold of -220 on the decision function. Use X_test and y_test.
This function should return a confusion matrix, a 2x2 numpy array with 4 integers.
'''
def answer_four():
from sklearn.metrics import confusion_matrix
from sklearn.svm import SVC
SVC_clf = SVC(C=1e9, gamma=1e-07).fit(X_train, y_train)
# print(SVC_clf)
y_decision_function = SVC_clf.decision_function(X_test) > -220
# print(len(y_decision_function))
# print(y_decision_function)
confusion = confusion_matrix(y_test, y_decision_function)
# print(confusion)
return confusion
print(answer_four())
'''
Question 5
Train a logisitic regression classifier with default parameters using X_train and y_train.
For the logisitic regression classifier, create a precision recall curve and a roc curve using y_test and the probability estimates for X_test (probability it is fraud).
Looking at the precision recall curve, what is the recall when the precision is 0.75?
Looking at the roc curve, what is the true positive rate when the false positive rate is 0.16?
This function should return a tuple with two floats, i.e. (recall, true positive rate).
'''
def answer_five():
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import precision_recall_curve, roc_curve
import matplotlib.pyplot as plt
linear_reg_clf = LogisticRegression().fit(X_train, y_train)
# print(linear_reg_clf)
# y_scores = linear_reg_clf.score(X_test, y_test)
# y_scores = linear_reg_clf.decision_function(X_test)
# print(y_scores)
y_prediction_scores = linear_reg_clf.predict(X_test)
# print(y_prediction_scores)
precision, recall, thresholds = precision_recall_curve(y_test, y_prediction_scores)
fpr, tpr, _ = roc_curve(y_test, y_prediction_scores)
fig, (ax1, ax2) = plt.subplots(2, 1, sharex=True)
plt.xlim([-0.01, 1.01])
plt.ylim([-0.01, 1.01])
closest_zero = np.argmin(np.abs(thresholds))
closest_zero_p = precision[closest_zero]
closest_zero_r = recall[closest_zero]
ax1.plot(precision, recall, label='Precision-Recall Curve')
ax1.plot(closest_zero_p, closest_zero_r, 'o', markersize = 12, fillstyle = 'none', c='r', mew=3)
ax1.set_xlabel('Precision', fontsize=16)
ax1.set_ylabel('Recall', fontsize=16)
# plt.axes().set_aspect('equal')
ax2.plot(fpr, tpr, lw=3, label='LogRegr')
ax2.set_xlabel('False Positive Rate', fontsize=16)
ax2.set_ylabel('True Positive Rate', fontsize=16)
plt.show()
return (0.83, 0.94)
# print(answer_five())
'''
Question 6
Perform a grid search over the parameters listed below for a Logisitic Regression classifier, using recall for scoring and the default 3-fold cross validation.
'penalty': ['l1', 'l2']
'C':[0.01, 0.1, 1, 10, 100]
From .cv_results_, create an array of the mean test scores of each parameter combination. i.e.
l1 l2
0.01 ? ?
0.1 ? ?
1 ? ?
10 ? ?
100 ? ?
This function should return a 5 by 2 numpy array with 10 floats.
Note: do not return a DataFrame, just the values denoted by '?' above in a numpy array. You might need to reshape your raw result to meet the format we are looking for.
'''
def answer_six():
from sklearn.model_selection import GridSearchCV
from sklearn.linear_model import LogisticRegression
Cs = [0.01, 0.1, 1, 10, 100]
penalty = ['l1', 'l2']
param_grid = {'C': Cs, 'penalty': penalty}
logistic_reg_clf = LogisticRegression().fit(X_train, y_train)
grid_clf_logreg = GridSearchCV(logistic_reg_clf, param_grid=param_grid, scoring='recall', cv=3)
# print(grid_clf_logreg)
grid_clf_logreg.fit(X_train, y_train)
# y_prediction = grid_clf_logreg.score(X_test, y_test)
# print(y_prediction)
# print(grid_clf_logreg.cv_results_)
# print(grid_clf_logreg.cv_results_.keys())
# print(grid_clf_logreg.cv_results_['mean_test_score'])
mean_test_score = grid_clf_logreg.cv_results_['mean_test_score']
# print(type(mean_test_score))
print(mean_test_score.reshape(5, 2))
print(type(mean_test_score.reshape(5, 2)))
print(np.array(mean_test_score.reshape(5, 2)))
print(type(np.array(mean_test_score.reshape(5, 2))))
# return mean_test_score.reshape(5, 2)
print(answer_six()) |
0b2c3420df3186dbc09c3f3051e0e1a75b9dc7ac | swang2000/DP | /Lengthofsubarrays.py | 1,693 | 3.78125 | 4 | '''
Given an array of N elements, you are required to find the maximum sum of lengths of all non-overlapping subarrays with
K as the maximum element in the subarray.
.
Input:
First line of the input contains an integer T, denoting the number of the total test cases. Then T test case follows.
First line of the test case contains an integer N, denoting the number of elements in the array. Then next line contains
N space separated integers denoting the elements of the array. The last line of each test case contains an integer K.
Output:
For each test case ouptut a single line denoting the sum of the length of all such subarrays.
Constraints:
1<=T<=100
1<=N<=105
1<=A[]<=105
Example:
Input:
3
9
2 1 4 9 2 3 8 3 4
4
7
1 2 3 2 3 4 1
4
10
4 5 7 1 2 9 8 4 3 1
4
Output:
5
7
4
Explanation:
Test Case 1:
Input : arr[] = {2, 1, 4, 9, 2, 3, 8, 3, 4}
k = 4
Output : 5
{2, 1, 4} => Length = 3
{3, 4} => Length = 2
So, 3 + 2 = 5 is the answer
Test Case 2:
Input : arr[] = {1, 2, 3, 2, 3, 4, 1}
k = 4
Output : 7
{1, 2, 3, 2, 3, 4, 1} => Length = 7
Test Case 3:
Input : arr = {4, 5, 7, 1, 2, 9, 8, 4, 3, 1}
k = 4
Ans = 4
{4} => Length = 1
{4, 3, 1} => Length = 3
So, 1 + 3 = 4 is the answer
'''
def lengthsubarrays(a, k):
s =[]
size = 0
i =0
flag = False
while i < len(a):
if a[i] <= k:
s.append(a[i])
if a[i] == k:
flag = True
else:
if flag:
size += len(s)
s = []
flag = False
i += 1
return size + len(s)
a = [4, 5, 7, 1, 2, 9, 8, 4, 3, 1]
a1 = [1, 2, 3, 2, 3, 4, 1]
a2 = [2, 1, 4, 9, 2, 3, 8, 3, 4]
lengthsubarrays(a2, 4)
|
9fc6878b630793ae255e495f7ff520161a2ed4e7 | nanoman08/ud120-projects | /tools/word_counts.py | 2,447 | 4.03125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Fri Jul 01 11:52:39 2016
@author: CHOU_H
"""
"""Count words."""
from collections import Counter
def count_words(s, n):
"""Return the n most frequently occuring words in s."""
a = s.split(' ')
# TODO: Count the number of occurences of each word in s
b = Counter(a)
# TODO: Sort the occurences in descending order (alphabetically in case of ties)
c = sorted(b.iteritems(), key=lambda tup:(-tup[1], tup[0]))
# TODO: Return the top n words as a list of tuples (<word>, <count>)
top_n = c[:n]
return top_n
def test_run():
"""Test count_words() with some inputs."""
print count_words("cat bat mat cat bat cat", 3)
print count_words("betty bought a bit of butter but the butter was bitter", 3)
if __name__ == '__main__':
test_run()
sample_memo = '''
Milt, we're gonna need to go ahead and move you downstairs into storage B. We have some new people coming in, and we need all the space we can get. So if you could just go ahead and pack up your stuff and move it down there, that would be terrific, OK?
Oh, and remember: next Friday... is Hawaiian shirt day. So, you know, if you want to, go ahead and wear a Hawaiian shirt and jeans.
Oh, oh, and I almost forgot. Ahh, I'm also gonna need you to go ahead and come in on Sunday, too...
Hello Peter, whats happening? Ummm, I'm gonna need you to go ahead and come in tomorrow. So if you could be here around 9 that would be great, mmmk... oh oh! and I almost forgot ahh, I'm also gonna need you to go ahead and come in on Sunday too, kay. We ahh lost some people this week and ah, we sorta need to play catch up.
'''
#
# Maximum Likelihood Hypothesis
#
#
# In this quiz we will find the maximum likelihood word based on the preceding word
#
# Fill in the NextWordProbability procedure so that it takes in sample text and a word,
# and returns a dictionary with keys the set of words that come after, whose values are
# the number of times the key comes after that word.
#
# Just use .split() to split the sample_memo text into words separated by spaces.
from collections import defaultdict
def NextWordProbability(sampletext,word):
words_after=defaultdict(int)
test_split = sampletext.split()
for i in range(len(test_split)-1):
if test_split[i] == word:
words_after[test_split[i+1]]+=1
return words_after
|
a9f96cafc9f3ed842b2d49e1a9423ef0551959e1 | Shreyash-310/Sololearn_practice | /sololearn_exception.py | 572 | 4.21875 | 4 | """try:
num1 = 7
num2 = 2
print(num1/num2)
print("Done calculation")
except ZeroDivisionError:
print("error occured due to zero division ")"""
"""try:
word = "spam"
print(word/0)
except:
print('An error occured !')"""
"""try:
num1 = input(": ")
num2 = input(": ")
print(float(num1)/float(num2))
except:
print('Invalid input')"""
"""try:
print('hello')
print(1/0)
except ZeroDivisionError:
print('divided by zero')
finally:
print('This code will run no matter what!')"""
print(1)
raise ValueError
print(2) |
b552d4bd1701e71a2fe98ba64ef3d69785115460 | ssb2920/SEM-6 | /SPCC/Codes/prac1/prac1.py | 5,197 | 3.53125 | 4 | import random
ops = ['+', '-', '/', '*', '=', '%']
table = {}
def free_addr():
addr_list = [table[sym]['addr'] for sym in table]
addr = random.randint(0, 2000)
while addr in addr_list:
addr = random.randint(0, 2000)
return addr
def create_table(exp):
for sym in exp:
if sym in ops:
table[sym] = {"addr": free_addr(), "type": "operator"}
else:
table[sym] = { "addr": free_addr(), "type": "identifier"}
return table
def search_table(sym):
if sym in table:
print(f"Symbol: {sym} | Address: {table[sym]['addr']} | Type: {table[sym]['type']}")
else:
print("Symbol not in Symbol Table")
def add_symbol(sym):
_type = "identifier"
if sym in ops:
_type = "operator"
table[sym] = {"addr": free_addr(), "type": _type}
def remove_symbol(sym):
del table[sym]
def print_table():
for sym in table:
print(f"Symbol: {sym} | Address: {table[sym]['addr']} | Type: {table[sym]['type']}")
while True:
_choice = int(input("1. Create table 2. Search table 3. Enter symbol 4. Remove symbol 5. View table 6. Exit\nEnter your choice: "))
if _choice == 1:
exp = input("Enter expression: ")
table = create_table(exp)
if _choice == 2:
sym = input("Enter symbol to search: ")
search_table(sym)
if _choice == 3:
sym = input("Enter symbol: ")
add_symbol(sym)
if _choice == 4:
sym = input("Enter symbol to remove: ")
remove_symbol(sym)
if _choice == 5:
print_table()
if _choice == 6:
break
# 1. Create table 2. Search table 3. Enter symbol 4. Remove symbol 5. View table 6. Exit
# Enter your choice: 1
# Enter expression: D=A+B*C
# 1. Create table 2. Search table 3. Enter symbol 4. Remove symbol 5. View table 6. Exit
# Enter your choice: 6
# (new_main) kad99kev@kad99kev SPCC % python prac1.py
# 1. Create table 2. Search table 3. Enter symbol 4. Remove symbol 5. View table 6. Exit
# Enter your choice: 1
# Enter expression: D=A+B*C
# 1. Create table 2. Search table 3. Enter symbol 4. Remove symbol 5. View table 6. Exit
# Enter your choice: 5
# Symbol: D | Address: 1574 | Type: identifier
# Symbol: = | Address: 1192 | Type: operator
# Symbol: A | Address: 199 | Type: identifier
# Symbol: + | Address: 1520 | Type: operator
# Symbol: B | Address: 921 | Type: identifier
# Symbol: * | Address: 1084 | Type: operator
# Symbol: C | Address: 579 | Type: identifier
# 1. Create table 2. Search table 3. Enter symbol 4. Remove symbol 5. View table 6. Exit
# Enter your choice: 1
# Enter expression: X=W/M-L
# 1. Create table 2. Search table 3. Enter symbol 4. Remove symbol 5. View table 6. Exit
# Enter your choice: 5
# Symbol: D | Address: 1574 | Type: identifier
# Symbol: = | Address: 356 | Type: operator
# Symbol: A | Address: 199 | Type: identifier
# Symbol: + | Address: 1520 | Type: operator
# Symbol: B | Address: 921 | Type: identifier
# Symbol: * | Address: 1084 | Type: operator
# Symbol: C | Address: 579 | Type: identifier
# Symbol: X | Address: 1389 | Type: identifier
# Symbol: W | Address: 1879 | Type: identifier
# Symbol: / | Address: 772 | Type: operator
# Symbol: M | Address: 1863 | Type: identifier
# Symbol: - | Address: 1670 | Type: operator
# Symbol: L | Address: 1749 | Type: identifier
# 1. Create table 2. Search table 3. Enter symbol 4. Remove symbol 5. View table 6. Exit
# Enter your choice: 3
# Enter symbol: E
# 1. Create table 2. Search table 3. Enter symbol 4. Remove symbol 5. View table 6. Exit
# Enter your choice: 5
# Symbol: D | Address: 1574 | Type: identifier
# Symbol: = | Address: 356 | Type: operator
# Symbol: A | Address: 199 | Type: identifier
# Symbol: + | Address: 1520 | Type: operator
# Symbol: B | Address: 921 | Type: identifier
# Symbol: * | Address: 1084 | Type: operator
# Symbol: C | Address: 579 | Type: identifier
# Symbol: X | Address: 1389 | Type: identifier
# Symbol: W | Address: 1879 | Type: identifier
# Symbol: / | Address: 772 | Type: operator
# Symbol: M | Address: 1863 | Type: identifier
# Symbol: - | Address: 1670 | Type: operator
# Symbol: L | Address: 1749 | Type: identifier
# Symbol: E | Address: 1194 | Type: identifier
# 1. Create table 2. Search table 3. Enter symbol 4. Remove symbol 5. View table 6. Exit
# Enter your choice: 4
# Enter symbol to remove: D
# 1. Create table 2. Search table 3. Enter symbol 4. Remove symbol 5. View table 6. Exit
# Enter your choice: 5
# Symbol: = | Address: 356 | Type: operator
# Symbol: A | Address: 199 | Type: identifier
# Symbol: + | Address: 1520 | Type: operator
# Symbol: B | Address: 921 | Type: identifier
# Symbol: * | Address: 1084 | Type: operator
# Symbol: C | Address: 579 | Type: identifier
# Symbol: X | Address: 1389 | Type: identifier
# Symbol: W | Address: 1879 | Type: identifier
# Symbol: / | Address: 772 | Type: operator
# Symbol: M | Address: 1863 | Type: identifier
# Symbol: - | Address: 1670 | Type: operator
# Symbol: L | Address: 1749 | Type: identifier
# Symbol: E | Address: 1194 | Type: identifier
# 1. Create table 2. Search table 3. Enter symbol 4. Remove symbol 5. View table 6. Exit
# Enter your choice: 6 |
be9a12f3290f3d33e4f7b58ebfa8519959642be1 | agranadosb/pymugen | /pymugen/fasta/chromosome.py | 4,924 | 3.890625 | 4 | from typing import TextIO
from pymugen.fasta.sequence import Sequence
class Chromosome(object):
"""Class that represents a chromosome.
Using this class a sequence can be obtained as list, for example, if we want to get
a sequence that starts at position 123 and finish at 456, we can get it using:
```python
chromosome[123:457]
```
If we want to get a prefix from a position, for example, 7 symbols:
```python
chromosome[123:-7]
```
Parameters
----------
fasta_file: TextIO
Fasta file.
name: str
Name of the chromosome.
line_length: int
Line length of the chromosome.
label_length: int
Length of the first line of the chromosome.
index_start: int
Index where the chrosomosme starts on the FASTA file.
length: int
Length of the chromosome.
"""
def __init__(
self,
fasta_file: TextIO,
name: str,
line_length: int,
label_length: int,
index_start: int,
length: int,
labels: list = False,
) -> None:
self.name = name
self.fasta_file = fasta_file
self.line_length = line_length
self.label_length = label_length
self.index_start = index_start
self.length = length
self.labels = labels
def sequence(
self,
pos: int,
from_nuc: int,
to_nuc: int,
length: int = 1,
) -> Sequence:
"""Gets a sequence from the fasta file by the position of a nucleotide on a
chromosome, with a specified prefix length and suffix length.
Parameters
----------
chromosome : str
The chromosome where the sequence is going to be obtained.
pos : int
Position of the nucleotide on the chromosome.
from_nuc : int
Length of the prefix of the sequence.
to_nuc : int
Length of the suffix of the sequence.
length : int = 1
Length of the infix.
Returns
-------
The sequence divided in (prefix, nucleotide, suffix).
"""
pref = self[pos:-from_nuc]
nucleotide = self[pos : pos + length]
suff = self[pos + length : pos + length + to_nuc]
return Sequence(pref, nucleotide, suff)
def _get_nucleotide_index(self, pos: int) -> int:
"""Gets the index of a nucleotide by its position in a chromosome.
Parameters
----------
pos : int
Index of the nucletoide on the chromosome.
IndexError
When index is greater tha chromsome length or lower than 0.
Returns
-------
Index of the nucleotide on the fasta file.
"""
length = self.length - 1
if pos > length or pos < 0:
raise IndexError(f"Invalid index, must be in the interval {0}-{length}")
# It's necessary to taking into account that seek method counts new lines as a
# character, that's why we add new line characters ('\n')
num_new_lines = int(pos / self.line_length)
index_start = self.index_start
label_length = self.label_length
# Get the position of the nucleotid on the file (1 char is one byte, that's why
# we use seek)
return pos + index_start + label_length + num_new_lines
def _get_from_interval(self, starts: int, length: int) -> str:
"""Returns a sequence that starts at a given index of the fasta file and has a
given length.
Parameters
----------
length : int
Length of the sequence.
starts : int
Index of the fasta file where the sequence starts.
Raises
------
IndexError
When the start position is wrong or invalid.
Returns
-------
The sequence.
"""
self.fasta_file.seek(starts, 0)
sequence = ""
while length != 0:
searched_sequence = self.fasta_file.read(length).split("\n")
# Number of newline characters present on the sequence searched
length = len(searched_sequence) - 1
sequence += "".join(searched_sequence)
return sequence.upper()
def __getitem__(self, key):
if isinstance(key, (int)):
key = slice(key, key + 1, None)
start = key.start or 0
if start < 0:
raise IndexError()
stop = key.stop or self.length
if stop < 0:
stop, start = start, start + stop
if start < 0:
start = 0
if start < 0:
start = 0
if stop > self.length:
stop = self.length
length = stop - start
return self._get_from_interval(self._get_nucleotide_index(start), length)
def __ln__(self):
return self.length
|
2a5244bc9a3abe27aaa771b0bc27eeb5f480c661 | pwlolk/Prace_domowe | /PD02/pd02_04_1_i_ost_cyfra.py | 507 | 4.0625 | 4 | #Wyświetlanie pierwszej i ostatniej cyfry danej liczby
print("Wyświetlanie pierwszej i ostatniej cyfry danej liczby".upper())
while True:
number = input("Podaj liczbę: ")
first_digit = number[0]
last_digit = number[-1:]
print("Pierwsza cyfra: " + str(first_digit))
print("Ostatnia cyfra: " + str(last_digit))
print("")
#Pewnie tutaj moznaby jeszcze kobinować z warunkami czy podane wyrażenie jest liczbą,
#bo słowa i w ogóle wsszystkie ciągi znaków są traktowane tak samo. |
bef5d16b5c52b3f37b2046bd452608b8af2c9de1 | namratapandit/python-project1 | /code/repeatloop.py | 1,400 | 4.28125 | 4 | # program to take 2 numeric inputs and and operation selection from user
# the program repeats until the user does not exit
# Perform operations like add, sub, mul, divide
# keep repeating till user exits
# also handle exceptions for invalid inputs
def main():
validinput = False
# while loop runs till valid entries are entered
while not validinput:
try:
num1 = int(input("Enter number1"))
num2 = int(input("Enter number 2:"))
operation = int(input("Please choose from the following operations: Add : 1, Subtract : 2, Multiple : 3, Divide: 4. Exit: 9 "))
# ones valiinput values are taken, below operations are carried out based on the selection
if operation == 1 :
print("Adding...")
print(num1 + num2)
elif operation == 2 :
print("Subtracting...")
print(num1 - num2)
elif operation == 3 :
print("Multiplying...")
print(num1 * num2)
elif operation == 4 :
print("Dividing...")
print(num1 / num2)
elif operation == 9 :
print("Thank you, exiting program now!")
validinput = True
else:
print("Wrong selection, try again")
except:
print("Invalid entries, try again! ")
main() |
d28441524dee87dd23b91a1f61dd80dcaa027b84 | hearues-zueke-github/python_programs | /math_numbers/number_series_1.py | 670 | 3.578125 | 4 | #! /usr/bin/python3.5
import decimal
import math
import numpy as np
import matplotlib.pyplot as plt
from decimal import Decimal as D
decimal.getcontext().prec = 2000
pi = D("3.1415926535897932384626433832795028841071693993751058209749445923078164062862089986280348253421170679")
def calc_unknown_series():
str_zero = "0"
str_one = "1"
l = []
for i in range(1, 200):
l.append(D("0."+str_zero*i+str_one*i))
s = np.sum(l)
print("s: {}".format(s))
def calc_pi():
p = D("1")
for i in range(1, 1000, 2):
p *= (D(i+1)*D(i+1))/(D(i)*D(i+2))
print("p: {}".format(p))
calc_pi()
print("pi/D(4): {}".format(pi/D(2)))
|
fa2bd1501fd31e17c1e5957edf0257fc7fca5d32 | wangfang1111-gif/py_test | /s01/day01/guess age for.py | 265 | 3.71875 | 4 | #author:wang fang
for i in range(0,5):
Age = int(input("please input you guess age:"))
if Age > 46:
print("please guess smaller")
elif Age < 46:
print("please guess bigger")
else:
print("you are right,guess it")
break
|
d27395edd1bd1cfe950c6c584e073c90a4aec3d3 | mh70cz/py | /misc/fibonacci_test.py | 2,569 | 3.609375 | 4 | """ test fibonacci """
import unittest
import fibonacci as fib
class TestFib(unittest.TestCase):
""" test basic functionality """
fib_0_based_26 = [0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233,
377, 610, 987, 1597, 2584, 4181, 6765, 10946, 17711,
28657, 46368, 75025]
fib_1_based_26 = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233,
377, 610, 987, 1597, 2584, 4181, 6765, 10946, 17711,
28657, 46368, 75025, 121393]
def wrong_fake_method(self):
pass
def test_zero_based(self):
self.assertEqual(fib.fib_runner(0, 26),
self.fib_0_based_26)
self.assertEqual(fib.fib_runner(0, 26, fib.memo_fibonacci),
self.fib_0_based_26)
self.assertEqual(fib.fib_runner(0, 26, fib.memo_decor_fibonacci),
self.fib_0_based_26)
self.assertEqual(fib.fib_sequence(0, 26), self.fib_0_based_26)
def test_one_based(self):
self.assertEqual(fib.fib_runner(1, 27),
self.fib_1_based_26)
self.assertEqual(fib.fib_runner(1, 27, fib.memo_fibonacci),
self.fib_1_based_26)
self.assertEqual(fib.fib_runner(1, 27, fib.memo_decor_fibonacci),
self.fib_1_based_26)
self.assertEqual(fib.fib_sequence(1, 27), self.fib_1_based_26)
def test_wrong_input_type_exception(self):
with self.assertRaises(fib.SanitizeInputError) as cm:
fib.fib_runner("abc", 10)
the_exception = cm.exception
self.assertEqual(the_exception.args[0], "math.floor")
with self.assertRaises(fib.SanitizeInputError):
fib.fib_runner(1, "abc")
the_exception = cm.exception
self.assertEqual(the_exception.args[0], "math.floor")
def test_wrong_input_values(self):
with self.assertRaises(fib.SanitizeInputError) as cm:
fib.fib_runner(-1, 10)
the_exception = cm.exception
self.assertRegex(the_exception.args[0], "value")
with self.assertRaises(fib.SanitizeInputError) as cm:
fib.fib_runner(-2, 1)
the_exception = cm.exception
self.assertRegex(the_exception.args[0], "value")
def test_wrong_method(self):
with self.assertRaises(fib.SanitizeInputError) as cm:
fib.fib_runner(1, 10, self.wrong_fake_method())
the_exception = cm.exception
self.assertRegex(the_exception.args[0], "method")
|
083db3a8bc159aa095dfd03a0b42ca91825aeba6 | sourabhjain19/aps-2020 | /Code Library/108_superfactorial.py | 186 | 3.515625 | 4 | def superfactorial(n):
fact=[1]*(n+1)
for i in range(1,n+1):
fact[i]=fact[i-1]*i
res=1
for i in fact:
res*=i
return res
print(superfactorial(4)) |
540466ff5d98cbba5f96f1577a4e7efbe4e40586 | xszhaob/python_in_action | /hello.py | 1,434 | 3.671875 | 4 | from bs4 import BeautifulSoup,NavigableString
import re
html_doc = """
<html><head><title>The Dormouse's story</title></head>
<body>
<p class="title"><b>The Dormouse's story</b></p>
<p class="story">Once upon a time there were three little sisters; and their names were
<a href="http://example.com/elsie" class="sister" id="link1">Elsie</a>,
<a href="http://example.com/lacie" class="sister" id="link2">Lacie</a> and
<a href="http://example.com/tillie" class="sister" id="link3">Tillie</a>;
and they lived at the bottom of a well.</p>
<p class="story">...</p>
"""
def has_class_but_no_id(tag):
return tag.has_attr('class') and not tag.has_attr('id')
def not_lacie(href):
return href and not re.compile('lacie').search(href)
def surrounded_by_strings(tag):
return (isinstance(tag.next_element, NavigableString)
and isinstance(tag.previous_element, NavigableString))
def has_six_characters(css_class):
return css_class is not None and len(css_class) == 6
soup = BeautifulSoup(html_doc, 'html.parser')
# for tag in soup.find_all(attrs = {'class' : re.compile('sis')}, id = 'link3'):
# print(tag)
# for tag in soup.find_all('a', class_ = re.compile('sis')):
# print(tag)
# for tag in soup.find_all(class_ = has_six_characters):
# print(tag)
# for tag in soup.find_all('p', class_ = 'story'):
# print(tag)
css_soup = BeautifulSoup('<p class="body strikeout"></p>', 'html.parser')
print(css_soup.select("p.strikeout")) |
bea7a5c8ea1f3c5651d6b5c1dd52a87b62b52daa | PujaNaval/Python-Programs | /stringmethods.py | 1,013 | 4.09375 | 4 |
str = (input('Enter string'))
print (str)
cap = str.capitalize() #first letter of string is capital
print (cap)
cen = str.center(10,'H') #total width of the string and fill character
print (cen)
l = len(str)
print ("Length of string is %d"%(l)) #find length of the string
c = str.count('s',0,l) #counts how many times character occurs
print ("Count is:",c)
str = "Hello123"
print (str.isalnum()) #checks if number in string
str = "1234"
print (str.isdigit()) #checks string contains only digits
str = " " #checks blank spaces in string
print (str.isspace())
str = "SUSHANT" #converts upper to lower
print (str.lower())
str = "sushant" #converts lower to upper
print (str.upper())
str = "sushant" #find maximum character in string (ASCII)
print ('Maximum:',max(str))
str = "sushant"
print ('Maximum:',min(str)) #find maximum character in string (ASCII) |
c1968b466bb5be258550df3dcdfa9c0b7e95f596 | soneyaa/Python-Assignment | /Python Assignment/module2/exercise6/roulette_wheel.py | 730 | 4.0625 | 4 | p=int(input("Enter the pocket number"))
if p>36:
print("Error! The pocket number is out of range")
else:
if p==0:
print("Pocket is GREEN")
elif p>=1 and p<=10:
if p%2==0:
print("Pocket is BLACK")
else:
print("Pocket is RED")
elif p>=11 and p<=18:
if p%2==0:
print("Pocket is RED")
else:
print("Pocket is BLACK")
elif p>=19 and p<=28:
if p%2==0:
print("Pocket is BLACK")
else:
print("Pocket is RED")
elif p>=29 and p<=36:
if p%2==0:
print("Pocket is RED")
else:
print("Pocket is BLACK")
|
50bf1a875b64b08c63fdee0ea056ec66af2a0dfa | AllisonLiuxz/algor_learning | /newcoder/Full Permutation.py | 648 | 3.515625 | 4 | # -*- coding:utf-8 -*-
class Solution:
def Permutation(self, ss):
# write code here
if not ss:
return []
def gen_permutation(s):
if not s:
return None
if len(s) == 1:
return [s]
tmp = []
for i in range(len(s)):
per = gen_permutation(s[:i]+s[i+1:])
for p in per:
tmp.append(s[i]+p)
return tmp
res = sorted(list(set(gen_permutation(ss))))
return res
if __name__ == '__main__':
s = Solution()
string = 'Bacb'
print s.Permutation(string)
|
97422da2bc876a538752a72d7389a2804b70a65c | ashco/leetcode | /2020-09/04-fibonacci.py | 555 | 3.671875 | 4 | # return n character of fibonacci sequence
# 0 1 1 2 3 5 8 13 21 34
class Solution():
def __init__(self):
self.cache = {
0: 0,
1: 1
}
def fibonacci(self, n):
if n in self.cache: return self.cache[n]
res = self.fibonacci(n - 1) + self.fibonacci(n - 2)
self.cache[n] = res
return res
# class Solution():
# def fibonacci(self, n):
# if n <= 1: return n
# return self.fibonacci(n - 1) + self.fibonacci(n - 2)
print(Solution().fibonacci(99)) # 3 |
5c314e7cbcf77379916116651a4cbf9617216f32 | Yuchen1995-0315/review | /01-python基础/day06/exercise04.py | 980 | 3.671875 | 4 | # 练习1:["无忌","张翠山","张三丰"]-->{"无忌":2,"张翠山":3,"张三丰":3}
# key: 列表元素, value: key的长度
list_names = ["无忌", "张翠山", "张三丰"]
dict_names = {item: len(item) for item in list_names}
print(dict_names)
# 练习2:姓名列表: ["无忌","赵敏","周芷若"]
# 房间号:[101,102,103]
# 将两个列表合并为字典,key:姓名列表元素,值:房间列表元素.
list_names = ["无忌", "赵敏", "周芷若"]
list_rooms = [101, 101, 103]
dict_info = {list_names[i]: list_rooms[i] for i in range(len(list_names))}
print(dict_info)
# 需求:根据房间号查找人
# 根据值找键
# 方法1:遍历字典所有记录,判断值.
# 方法2:反转key 与 value
# dict_info = {v:k for k,v in dict_info.items() }
# print(dict_info)
# 注意:反转后,因为键不能相同,所以可能导致丢失数据。
list_info = [(v,k) for k,v in dict_info.items()]
print(list_info)
# 15:37
|
d393637088cb97b05e8fae25e44c8cba6d022f4f | raja1208/web-scrap | /extract.py | 4,194 | 3.71875 | 4 | import these two modules bs4 for selecting HTML tags easily
from bs4 import BeautifulSoup
# requests module is easy to operate some people use urllib but I prefer this one because it is easy to use.
import requests
# I put here my own blog url ,you can change it.
url="https://www.oyorooms.com/"
#Requests module use to data from given url
source=requests.get(url)
# BeautifulSoup is used for getting HTML structure from requests response.(craete your soup)
soup=BeautifulSoup(source.text,'html')
# Find function is used to find a single element if there are more than once it always returns the first element.
title=soup.find('title') # place your html tagg in parentheses that you want to find from html.
print("this is with html tags :",title)
qwery=soup.find('h1') # here i find first h1 tagg in my website using find operation.
#use .text for extract only text without any html tags
print("this is without html tags:",qwery.text)
inks=soup.find('a') #i extarcted link using "a" tag
print(links)
# ## extarct data from innerhtml
# here i extarcted href data from anchor tag.
print(links['href'])
# similarly i got class details from a anchor tag
print(links['class'])
import os, sys, time
import csv
from selenium import webdriver
# from selenium.webdriver.firefox.firefox_binary import FirefoxBinary
from operator import itemgetter
# os.environ['MOZ_HEADLESS'] = '1'
# binary = FirefoxBinary('/usr/bin/firefox', log_file=sys.stdout)
# two = sys.argv[1]
def clean_data(data):
try:
return data[0].text
except IndexError:
return 0
def parser_oyo(driver):
# driver = webdriver.Firefox(firefox_binary=binary)
# driver.get("https://www.oyorooms.com/oyos-in-kathmandu")
time.sleep(5)
hotels_data = []
hotels_list = driver.find_elements_by_class_name("newHotelCard")
for hotels in hotels_list:
hotel_name = hotels.find_elements_by_class_name("newHotelCard__hotelName")
hotel_location = hotels.find_elements_by_class_name("newHotelCard__hotelAddress")
hotel_price_detail = hotels.find_elements_by_class_name("newHotelCard__pricing")
price = hotel_price_detail[0].text
hotel_price = int(price.split(" ")[1])
hotel_not_discounted_amount = hotels.find_elements_by_class_name("newHotelCard__revisedPricing")
hotel_discount_percentage = hotels.find_elements_by_class_name("newHotelCard__discount")
hotel_rating = hotels.find_elements_by_class_name("hotelRating__value")
hotel_rating_remarks = hotels.find_elements_by_class_name("hotelRating__subtext")
original_price = clean_data(hotel_not_discounted_amount)
disc_perc = clean_data(hotel_discount_percentage)
rating = clean_data(hotel_rating)
remarks = clean_data(hotel_rating_remarks)
data = {
"Name": hotel_name[0].text,
"Location": hotel_location[0].text,
"Price after Disc": hotel_price,
"Original Price": original_price,
"Disc Percentage": disc_perc,
"Rating": rating,
"Remarks": remarks
}
print(data)
hotels_data.append(data)
# del os.environ['MOZ_HEADLESS']
return hotels_data
def write_data_to_csv(parsed_data, csv_columns, csv_file):
try:
with open(csv_file, 'w') as csvfile:
writer = csv.DictWriter(csvfile, fieldnames=csv_columns)
writer.writeheader()
for data in parsed_data:
writer.writerow(data)
except IOError:
print("I/O error")
if __name__ == '__main__':
url = sys.argv[1]
driver = webdriver.Chrome()
driver.get(url)
parsed_data = parser_oyo(driver)
#get next pages data
try:
nextpageButton = driver.find_elements_by_class_name("btn-next")[0]
while(nextpageButton != []):
next_page = nextpageButton.click()
next_page_data = parser_oyo(driver)
parsed_data += next_page_data
nextpageButton = driver.find_elements_by_class_name("btn-next")[0]
except IndexError:
pass
driver.close()
csv_columns = ['Name','Location','Price after Disc', 'Original Price', 'Disc Percentage', 'Rating', 'Remarks']
csv_file = "Hotels List.csv"
write_data_to_csv(parsed_data, csv_columns, csv_file)
data_sorted_by_price = sorted(parsed_data, key=itemgetter('Price after Disc'))
sorted_csv_file = "Hotel List sorted by price.csv"
write_data_to_csv(data_sorted_by_price, csv_columns, sorted_csv_file)
|
f1ced9ef0165afc9805a3b55401ed422a2818a68 | P-1702/Recruitment_Tasks_2021 | /PathPlanning/path_planning/scripts/MapClass.py | 2,594 | 3.96875 | 4 | #!/usr/bin/env python3
class Map:
# will hold array of values representing the walls in the maze
# the values will be integers.
# TopLeftRightBottom convention with values as 8-4-2-1
# basically a square with say top and bottom walls only will have value = 8(top) + 1(bottom) = 9
def __init__(self, width, height, start, end, array=None):
self.width = width
self.height = height
if self.check_coords(start) and self.check_coords(end):
self.start = start
self.end = end
if array:
self.array = array
else:
self.array = [ [0]*width for _ in range(height) ]
for i in range(height):
self.add_left_wall((i, 0))
self.add_right_wall((i, width-1))
for i in range(width):
self.add_top_wall((0, i))
self.add_bottom_wall((height-1, i))
def check_coords(self, coords):
if ((coords[0] < 0) or (coords[0] >= self.width)):
print('Coords ' + str(coords) + ' are out of bounds')
return False
if ((coords[1] < 0) or (coords[1] >= self.height)):
print('Coords ' + str(coords) + ' are out of bounds')
return False
return True
def add_top_wall(self, coords):
if self.check_coords(coords):
if self.array[coords[0]][coords[1]] < 8:
self.array[coords[0]][coords[1]] += 8
def add_left_wall(self, coords):
if self.check_coords(coords):
if (self.array[coords[0]][coords[1]]%8) < 4:
self.array[coords[0]][coords[1]] += 4
def add_right_wall(self, coords):
if self.check_coords(coords):
if (self.array[coords[0]][coords[1]]%4) < 2:
self.array[coords[0]][coords[1]] += 2
def add_bottom_wall(self, coords):
if self.check_coords(coords):
if (self.array[coords[0]][coords[1]]%2) < 1:
self.array[coords[0]][coords[1]] += 1
def check_top_wall(self, coords):
return (self.check_coords(coords)) and (self.array[coords[0]][coords[1]] >= 8)
def check_left_wall(self, coords):
return (self.check_coords(coords)) and ((self.array[coords[0]][coords[1]]%8) >= 4)
def check_right_wall(self, coords):
return (self.check_coords(coords)) and ((self.array[coords[0]][coords[1]]%4) >= 2)
def check_bottom_wall(self, coords):
return (self.check_coords(coords)) and ((self.array[coords[0]][coords[1]]%2) >= 1)
|
94645a0051ca6011b2de9a8dbf0af16727aa57da | MuhammadOmaryassir/Wattary-Core-1 | /Core/RECOMMENDER.py | 5,328 | 3.8125 | 4 | """ Wattary's Brain """
# Note: This file Require Numpy , Pandas and Sci-kit learn Modules
# Importing the modules
import numpy as np
import pandas as pd
import sklearn
from sklearn.neighbors import NearestNeighbors
<<<<<<< HEAD
=======
<<<<<<< HEAD
from sklearn import preprocessing
=======
>>>>>>> master
import random
'''
>>>>>>> b3e23a69d357152ba3ecbc248e5ba2eaea92325b
# Reading the CSV File and Convert it to Data Frame
movieCSV = pd.read_csv('DataSets/movie_metadata 1.1.csv', usecols=['num_critic_for_reviews', 'duration', 'gross',
'num_voted_users', 'cast_total_facebook_likes',
'num_user_for_reviews', 'title_year', 'imdb_score',
'movie_facebook_likes', 'genres', 'movie_title',
'director_name', 'actor_1_name', 'movie_imdb_link'])
movieDF = pd.DataFrame(movieCSV)
# ----------------------------------------------------- Recommender Class -----------------------------------#
class Recommender:
def __init__(self, testValues):
"""
:param dataset: string: that has the path to the data set
:param testValues: list: the values that we will recommend an item based on it
initialize the path when creating the object
and initialize the test values when crating the object without using a function
"""
self.movieDF = movieDF
<<<<<<< HEAD
self.testValues = testValues
=======
self.listOfValues = testValues
self.items = []
<<<<<<< HEAD
=======
>>>>>>> b3e23a69d357152ba3ecbc248e5ba2eaea92325b
>>>>>>> master
def encode(self):
""" This method for Testing purpose only """
le = preprocessing.LabelEncoder()
le.fit(self.movieDF['genres'])
self.movieDF['genres'] = le.transform(self.movieDF['genres'])
print(self.movieDF.head())
def FitAndPredict(self, valueList=[]):
"""
:param valueList: list: the values that we will recommend an item based on it
:return: list:
checking data in all rows for the columns 1,4 and 10,
Fitting the Nearest Neighbors function to the data in our data set
and Getting the nearest value to the desired values in the data set
"""
tData = self.movieDF.iloc[:, 0:10]
<<<<<<< HEAD
self.Neighbors = NearestNeighbors(n_neighbors=25).fit(self.Data)
=======
<<<<<<< HEAD
self.Neighbors = NearestNeighbors(n_neighbors=1).fit(tData)
=======
self.Neighbors = NearestNeighbors(n_neighbors=25).fit(self.Data)
>>>>>>> b3e23a69d357152ba3ecbc248e5ba2eaea92325b
>>>>>>> master
self.Output = self.Neighbors.kneighbors([valueList])
return self.Output
<<<<<<< HEAD
# def outPutHandling(self, output):
# """
#
# :param output: list: that returned from Model()
# :return: recommenedItem: vector row or list: that has the recommended details
#
# cast the list given to String,
# remove the Brackets from the string
# and return the Recommended Item
# """
# self.OutPut = str(output[1])
#
# self.newOutput = self.OutPut.strip("[]")
#
# # cast it again to Integer
# self.Index = int(self.newOutput)
#
# self.recommendedItem = self.dataSet.iloc[self.Index, 11]
# return self.recommendedItem
=======
def outPutHandling(self, output):
"""
:param output: list: that returned from Model()
:return: recommenedItem: vector row or list: that has the recommended details
cast the list given to String,
remove the Brackets from the string
and return the Recommended Item
"""
self.OutPut = str(output[1])
#print( self.OutPut)
#self.newOutput = self.OutPut.strip("[]")
self.OutPut = self.OutPut.replace("[[ ", "")
self.OutPut = self.OutPut.replace("]]", "")
self.OutPut = self.OutPut.replace(" ", ",")
self.OutPut = self.OutPut.replace("[[", "")
self.OutPut = self.OutPut.replace(",,", ",")
self.OutPut = self.OutPut.replace("\n,,", ",")
self.OutPut = self.OutPut.replace("\n", "")
self.items.append(self.OutPut)
x = self.items[0]
x = x.replace(",", " ")
y = x.split()
#print(len(y))
r = random.sample(range(0,24), 1)
r = str(r).strip('[]')
# cast it again to Integer
self.Index = int(y[int(r)])
#print(y[int(r)])
self.recommendedItem = self.dataSet.iloc[self.Index,11]
return self.recommendedItem
>>>>>>> b3e23a69d357152ba3ecbc248e5ba2eaea92325b
# --------------------------------------------------Just for Testing---------------------------------------#
# Cars = pd.read_csv('DataSets/mtcars.csv')
# x = RECOMMENDER(Cars, [21, 150, 4])
# out = x.Model(x.listOfValues)
# recomendedItem = x.outPutHandling(out)
# print(recomendedItem)z
# Movies = pd.read_csv('./DataSets/convertcsv.csv')
# A = RECOMMENDER(Movies, [8, 5])
# opt = A.Model(A.listOfValues)
# recomendedItem = A.outPutHandling(opt)
# print(recomendedItem)
# #print(opt) |
94e619e438b347a7965f9138c4adaaf6a6c0cf4d | PacktPublishing/Mastering-Object-Oriented-Python-Second-Edition | /Chapter_8/ch08_ex1.py | 11,636 | 4.03125 | 4 | #!/usr/bin/env python3.7
"""
Mastering Object-Oriented Python 2e
Code Examples for Mastering Object-Oriented Python 2nd Edition
Chapter 8. Example 1.
"""
# noisyfloat
# ================================
import sys
def trace(frame, event, arg):
if frame.f_code.co_name.startswith("__"):
print(frame.f_code.co_name, frame.f_code.co_filename, event)
# sys.settrace(trace)
class NoisyFloat(float):
def __add__(self, other: float) -> 'NoisyFloat':
print(self, "+", other)
return NoisyFloat(super().__add__(other))
def __radd__(self, other: float) -> 'NoisyFloat':
print(self, "r+", other)
return NoisyFloat(super().__radd__(other))
test_noisy_float = """
>>> x = NoisyFloat(2)
>>> y = NoisyFloat(3)
>>> x + y + 2.5
2.0 + 3.0
5.0 + 2.5
7.5
"""
# Fixed Point
# =================================
import numbers
import math
from typing import Union, Optional, Any
class FixedPoint(numbers.Rational):
__slots__ = ("value", "scale", "default_format")
def __init__(self, value: Union['FixedPoint', int, float], scale: int = 100) -> None:
self.value: int
self.scale: int
if isinstance(value, FixedPoint):
self.value = value.value
self.scale = value.scale
elif isinstance(value, int):
self.value = value
self.scale = scale
elif isinstance(value, float):
self.value = int(scale * value + .5) # Round half up
self.scale = scale
else:
raise TypeError(f"Can't build FixedPoint from {value!r} of {type(value)}")
digits = int(math.log10(scale))
self.default_format = "{{0:.{digits}f}}".format(digits=digits)
def __str__(self) -> str:
return self.__format__(self.default_format)
def __repr__(self) -> str:
return f"{self.__class__.__name__:s}({self.value:d},scale={self.scale:d})"
def __format__(self, specification: str) -> str:
if specification == "":
specification = self.default_format
return specification.format(self.value / self.scale) # no rounding
def numerator(self) -> int:
return self.value
def denominator(self) -> int:
return self.scale
def __add__(self, other: Union['FixedPoint', int]) -> 'FixedPoint':
if not isinstance(other, FixedPoint):
new_scale = self.scale
new_value = self.value + other * self.scale
else:
new_scale = max(self.scale, other.scale)
new_value = self.value * (new_scale // self.scale) + other.value * (
new_scale // other.scale
)
return FixedPoint(int(new_value), scale=new_scale)
def __sub__(self, other: Union['FixedPoint', int]) -> 'FixedPoint':
if not isinstance(other, FixedPoint):
new_scale = self.scale
new_value = self.value - other * self.scale
else:
new_scale = max(self.scale, other.scale)
new_value = self.value * (new_scale // self.scale) - other.value * (
new_scale // other.scale
)
return FixedPoint(int(new_value), scale=new_scale)
def __mul__(self, other: Union['FixedPoint', int]) -> 'FixedPoint':
if not isinstance(other, FixedPoint):
new_scale = self.scale
new_value = self.value * other
else:
new_scale = self.scale * other.scale
new_value = self.value * other.value
return FixedPoint(int(new_value), scale=new_scale)
def __truediv__(self, other: Union['FixedPoint', int]) -> 'FixedPoint':
if not isinstance(other, FixedPoint):
new_value = int(self.value / other)
else:
new_value = int(self.value / (other.value / other.scale))
return FixedPoint(new_value, scale=self.scale)
def __floordiv__(self, other: Union['FixedPoint', int]) -> 'FixedPoint':
if not isinstance(other, FixedPoint):
new_value = int(self.value // other)
else:
new_value = int(self.value // (other.value / other.scale))
return FixedPoint(new_value, scale=self.scale)
def __mod__(self, other: Union['FixedPoint', int]) -> 'FixedPoint':
if not isinstance(other, FixedPoint):
new_value = (self.value / self.scale) % other
else:
new_value = self.value % (other.value / other.scale)
return FixedPoint(new_value, scale=self.scale)
def __pow__(self, other: Union['FixedPoint', int]) -> 'FixedPoint':
if not isinstance(other, FixedPoint):
new_value = (self.value / self.scale) ** other
else:
new_value = (self.value / self.scale) ** (other.value / other.scale)
return FixedPoint(int(new_value) * self.scale, scale=self.scale)
def __abs__(self) -> 'FixedPoint':
return FixedPoint(abs(self.value), self.scale)
def __float__(self) -> float:
return self.value / self.scale
def __int__(self) -> int:
return int(self.value / self.scale)
def __trunc__(self) -> int:
return int(math.trunc(self.value / self.scale))
def __ceil__(self) -> int:
return int(math.ceil(self.value / self.scale))
def __floor__(self) -> int:
return int(math.floor(self.value / self.scale))
# reveal_type(numbers.Rational.__round__)
def __round__(self, ndigits: Optional[int] = 0) -> Any:
return FixedPoint(round(self.value / self.scale, ndigits=ndigits), self.scale)
def __neg__(self) -> 'FixedPoint':
return FixedPoint(-self.value, self.scale)
def __pos__(self) -> 'FixedPoint':
return self
# Note equality among floats isn't a good idea.
# Also, should FixedPoint(123, 100) equal FixedPoint(1230, 1000)?
def __eq__(self, other: Any) -> bool:
if isinstance(other, FixedPoint):
if self.scale == other.scale:
return self.value == other.value
else:
return self.value * other.scale // self.scale == other.value
else:
return abs(self.value / self.scale - float(other)) < .5 / self.scale
def __ne__(self, other: Any) -> bool:
return not (self == other)
def __le__(self, other: 'FixedPoint') -> bool:
return self.value / self.scale <= float(other)
def __lt__(self, other: 'FixedPoint') -> bool:
return self.value / self.scale < float(other)
def __ge__(self, other: 'FixedPoint') -> bool:
return self.value / self.scale >= float(other)
def __gt__(self, other: 'FixedPoint') -> bool:
return self.value / self.scale > float(other)
def __hash__(self) -> int:
P = sys.hash_info.modulus
m, n = self.value, self.scale
# Remove common factors of P. (Unnecessary if m and n already coprime.)
while m % P == n % P == 0:
m, n = m // P, n // P
if n % P == 0:
hash_ = sys.hash_info.inf
else:
# Fermat's Little Theorem: pow(n, P-1, P) is 1, so
# pow(n, P-2, P) gives the inverse of n modulo P.
hash_ = (abs(m) % P) * pow(n, P - 2, P) % P
if m < 0:
hash_ = -hash_
if hash_ == -1:
hash_ = -2
return hash_
def __radd__(self, other: Union['FixedPoint', int]) -> 'FixedPoint':
if not isinstance(other, FixedPoint):
new_scale = self.scale
new_value = other * self.scale + self.value
else:
new_scale = max(self.scale, other.scale)
new_value = other.value * (new_scale // other.scale) + self.value * (
new_scale // self.scale
)
return FixedPoint(int(new_value), scale=new_scale)
def __rsub__(self, other: Union['FixedPoint', int]) -> 'FixedPoint':
if not isinstance(other, FixedPoint):
new_scale = self.scale
new_value = other * self.scale - self.value
else:
new_scale = max(self.scale, other.scale)
new_value = other.value * (new_scale // other.scale) - self.value * (
new_scale // self.scale
)
return FixedPoint(int(new_value), scale=new_scale)
def __rmul__(self, other: Union['FixedPoint', int]) -> 'FixedPoint':
if not isinstance(other, FixedPoint):
new_scale = self.scale
new_value = other * self.value
else:
new_scale = self.scale * other.scale
new_value = other.value * self.value
return FixedPoint(int(new_value), scale=new_scale)
def __rtruediv__(self, other: Union['FixedPoint', int]) -> 'FixedPoint':
if not isinstance(other, FixedPoint):
new_value = self.scale * int(other / (self.value / self.scale))
else:
new_value = int((other.value / other.scale) / self.value)
return FixedPoint(new_value, scale=self.scale)
def __rfloordiv__(self, other: Union['FixedPoint', int]) -> 'FixedPoint':
if not isinstance(other, FixedPoint):
new_value = self.scale * int(other // (self.value / self.scale))
else:
new_value = int((other.value / other.scale) // self.value)
return FixedPoint(new_value, scale=self.scale)
def __rmod__(self, other: Union['FixedPoint', int]) -> 'FixedPoint':
if not isinstance(other, FixedPoint):
new_value = other % (self.value / self.scale)
else:
new_value = (other.value / other.scale) % (self.value / self.scale)
return FixedPoint(new_value, scale=self.scale)
def __rpow__(self, other: Union['FixedPoint', int]) -> 'FixedPoint':
if not isinstance(other, FixedPoint):
new_value = other ** (self.value / self.scale)
else:
new_value = (other.value / other.scale) ** self.value / self.scale
return FixedPoint(int(new_value) * self.scale, scale=self.scale)
def round_to(self, new_scale: int) -> 'FixedPoint':
f = new_scale / self.scale
return FixedPoint(int(self.value * f + .5), scale=new_scale)
# test cases to show that ``FixedPoint`` numbers work properly.
test_fp = """
>>> f1 = FixedPoint(12.34, 100)
>>> f2 = FixedPoint(1234, 100)
>>> print(f1, repr(f1))
12.34 FixedPoint(1234,scale=100)
>>> print(f2, repr(f2))
12.34 FixedPoint(1234,scale=100)
>>> print(f1 * f2, f1 + f2, f1 - f2, f1 / f2)
152.2756 24.68 0.00 1.00
>>> print(f1 + 101, f1 * 2, f1 - 101, f1 / 2, f1 % 1, f1 // 2)
113.34 24.68 -88.66 6.17 0.34 6.17
>>> print(101 + f2, 2 * f2, 101 - f1, 25 / f1, 1334 % f1, 25 // f1)
113.34 24.68 88.66 2.00 1.28 2.00
>>> print("round", round(f1))
round 12.00
>>> print("ceil", math.ceil(f1))
ceil 13
>>> print("floor", math.floor(f1))
floor 12
>>> print("trunc", math.trunc(f1))
trunc 12
>>> print("==", f1 == f2, f1 == 12.34, f1 == 1234 / 100, f1 == FixedPoint(12340, 1000))
== True True True True
>>> print(hash(f1), hash(f2), hash(FixedPoint(12340, 1000)))
1521856386081038020 1521856386081038020 1521856386081038020
>>> f3 = FixedPoint(200, 100)
>>> print(f3 * f3 * f3, f3 ** 3, 3 ** f3)
8.000000 8.00 9.00
>>> price = FixedPoint(1299, 100)
>>> tax_rate = FixedPoint(725, 1000)
>>> tax = price * tax_rate
>>> print(tax, tax.round_to(100))
9.41775 9.42
"""
__test__ = {name: value for name, value in locals().items() if name.startswith("test_")}
if __name__ == "__main__":
import doctest
doctest.testmod(verbose=False)
|
09507ae470aedc63ee1ae3fb33014982e51681c1 | Dgriffin12/511_Python_Stuff | /Extra_511_PY/Book.py | 1,194 | 3.5625 | 4 | from Item import Item
class Book(Item):
def __init__(self, type_in, call_num, book_title, subjects_in, author_in, desc_in, pub_in, city_in, year_in, series_in, notes_in):
self.type = type_in
self.call_no = call_num
self.title = book_title
self.subjects = subjects_in
self.author = author_in
self.description = desc_in
self.publisher = pub_in
self.city = city_in
self.year = year_in
self.series = series_in
self.notes = notes_in
def title_search(self, phrase) :
return phrase in self.title
def other_search(self, phrase) :
return (phrase in self.description or phrase in self.notes or phrase in self.year)
def print(self) :
print ("Book: ")
print ("Title " + self.title)
print ("Call No: " + self.call_no)
print ("Subject: " + self.subjects)
print ("Author: " + self.author)
print ("Description: " + self.description)
print ("Publisher: " + self.publisher)
print ("Series: " + self.series)
print ("Notes: " + self.notes)
print ("City: " + self.city)
print ("Year: " + self.year)
|
06e939d591998dbbcc0919cea1e2d77582ffe411 | abednarski79/lirc-controller | /src/lab/PipeTryOut.py | 1,533 | 3.59375 | 4 | from multiprocessing import Process, Pipe
import time
class Executor:
def __init__(self, subConn):
self.subConn = subConn
def execute(self):
command = 0
while(command != 9):
command = self.subConn.recv()
time.sleep(2)
print "executing: " + str(command)
print "terminating executor."
class Processor:
def __init__(self, procConn):
self.procConn = procConn
self.parent_conn, child_conn = Pipe()
executor = Executor(child_conn)
self.subProcess = Process(target=executor.execute)
self.subProcess.start()
def process(self):
data = 0
while(data != 10):
data = self.procConn.recv()
time.sleep(1)
print "processing: " + str(data)
self.parent_conn.send(data)
print "terminating processor."
class Generator:
def __init__(self, genConn):
self.genConn = genConn
pass
def generate(self):
for num in range(1,11):
print "sending: " + str(num)
self.genConn.send(num)
class MainRunner:
def __init__(self):
parent_conn, child_conn = Pipe()
self.generator = Generator(parent_conn)
processor = Processor(child_conn)
self.process = Process(target=processor.process)
def run(self):
self.process.start()
self.generator.generate()
if __name__ == '__main__':
runner = MainRunner()
runner.run()
|
3dc098cacdb4ba5832e227b82a06cfc208255374 | BlueDragon23/advent-of-code2017 | /day17p2.py | 408 | 3.59375 | 4 | def iterate(state, current_pos, val):
"""
returns next_pos
"""
next_pos = (current_pos + 316) % val
#state.insert(next_pos + 1, val)
if next_pos == 0:
state[1] = val
return next_pos + 1
if __name__=="__main__":
current_pos = 0
state = [0, 0]
for i in range(1, 50000000):
current_pos = iterate(state, current_pos, i)
print(state)
|
d3a98c9d8f2100435144bfcddc586039baa07497 | DatabaseCoder/MyPythonWork | /SortAlgo/MergeSort.py | 1,033 | 4.3125 | 4 | # Merge Sort code in Python
def merge_sort(NumberList):
"""
Merge sort code to sort Number List
Call this code like - merge_sort([34,12,78,90,24,67])
"""
length = len(NumberList)
if length > 1:
midpoint = length // 2
left_half = merge_sort(NumberList[:midpoint])
right_half = merge_sort(NumberList[midpoint:])
i = 0
j = 0
k = 0
left_length = len(left_half)
right_length = len(right_half)
while i < left_length and j < right_length:
if left_half[i] < right_half[j]:
NumberList[k] = left_half[i]
i += 1
else:
NumberList[k] = right_half[j]
j += 1
k += 1
while i < left_length:
NumberList[k] = left_half[i]
i += 1
k += 1
while j < right_length:
NumberList[k] = right_half[j]
j += 1
k += 1
return NumberList
if __name__ == '__main__':
try:
raw_input
except NameError:
raw_input = input
user_input = raw_input('Enter numbers separated by comma:\n').strip()
unsorted = [int(item) for item in user_input.split(',')]
print(merge_sort(unsorted))
|
ba85df0fc81b1feaa28bb5258865bcf242c43acb | vns25/Computer-Networks | /HW1- Echo Assignment/client.py | 950 | 3.5 | 4 | #Vanshika Shah
#! /usr/bin/env python3
# Echo Client
import sys
import socket
# Get the server hostname, port and data length as command line arguments
host = sys.argv[1]
port = int(sys.argv[2])
count = int(sys.argv[3])
data = 'X' * count # Initialize data to be sent
# Create UDP client socket. Note the use of SOCK_DGRAM
clientsocket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
# timeout from https://www.kite.com/python/docs/socket.socket.settimeout
clientsocket.settimeout(1)
for i in range(0,3):
try:
print("Sending data to " + host + ", " + str(port) + ": " + data + " (" + str(count) + " characters" + ")" )
clientsocket.sendto(data.encode(),(host, port))
dataEcho, address = clientsocket.recvfrom(count)
print("Receive data from " + address[0] + ", " + str(address[1]) + ": " + dataEcho.decode())
break
except:
print("Message timed out")
#Close the client socket
clientsocket.close()
|
4c4c9fbab2c0b2ab448ec38042ab42040b201def | JosephLevinthal/Research-projects | /5 - Notebooks e Data/1 - Análises numéricas/Arquivos David/Atualizados/logDicas-master/data/2019-1/224/users/4357/codes/1650_2449.py | 333 | 3.890625 | 4 | a=float(input("digite o numero"))
b=float(input("digite o numero"))
c=float(input("digite o numero"))
d=float(input("digite o numero"))
e=float(input("digite o numero"))
f=float(input("digite o numero"))
x=(c*e-b*f/a*e-b*d)
y=(a*f-c*d/a*e-b*d)
if (a*e-b*d!=0):
mensagem= "Tem soluçao "
else:
mensagem="Nao tem soluçao"
print(x,y) |
0cbfeb94c521bb6aa829ac01e5ae74dc84ad9ddf | Camerash/cs231n | /Assignment1/cs231n/classifiers/softmax.py | 4,097 | 3.75 | 4 | import numpy as np
from random import shuffle
from past.builtins import xrange
def softmax_loss_naive(W, X, y, reg):
"""
Softmax loss function, naive implementation (with loops)
Inputs have dimension D, there are C classes, and we operate on minibatches
of N examples.
Inputs:
- W: A numpy array of shape (D, C) containing weights.
- X: A numpy array of shape (N, D) containing a minibatch of data.
- y: A numpy array of shape (N,) containing training labels; y[i] = c means
that X[i] has label c, where 0 <= c < C.
- reg: (float) regularization strength
Returns a tuple of:
- loss as single float
- gradient with respect to weights W; an array of same shape as W
"""
# Initialize the loss and gradient to zero.
loss = 0.0
dW = np.zeros_like(W)
#############################################################################
# TODO: Compute the softmax loss and its gradient using explicit loops. #
# Store the loss in loss and the gradient in dW. If you are not careful #
# here, it is easy to run into numeric instability. Don't forget the #
# regularization! #
#############################################################################
num_train = X.shape[0]
num_class = W.shape[1]
for i in range(num_train):
prob = np.matmul(X[i], W) # Scores in the scope of SVM, here we describe this as unnormalized probabilities
prob += -np.max(prob) # Stablize data, check out: https://deepnotes.io/softmax-crossentropy
exp_prob = np.exp(prob) # Get e^(prob) of the respective data
loss += -prob[y[i]] + np.log(np.sum(exp_prob))
# Following equation: check out: https://deepnotes.io/softmax-crossentropy
for j in range(num_class):
dW[:, j] += (np.exp(prob[j]) * X[i] / np.sum(exp_prob)) # -pj*pi
if j == y[i]: # i == j
dW[:, j] -= X[i] # pi - pj*pi
loss /= num_train
loss += reg * np.sum(W * W)
dW /= num_train
dW += 2*reg*W
#############################################################################
# END OF YOUR CODE #
#############################################################################
return loss, dW
def softmax_loss_vectorized(W, X, y, reg):
"""
Softmax loss function, vectorized version.
Inputs and outputs are the same as softmax_loss_naive.
"""
# Initialize the loss and gradient to zero.
loss = 0.0
dW = np.zeros_like(W)
#############################################################################
# TODO: Compute the softmax loss and its gradient using no explicit loops. #
# Store the loss in loss and the gradient in dW. If you are not careful #
# here, it is easy to run into numeric instability. Don't forget the #
# regularization! #
#############################################################################
num_train = X.shape[0]
prob = np.matmul(X, W) # Scores in the scope of SVM, here we describe this as unnormalized probabilities
prob += -np.max(prob) # Stablize data, check out: https://deepnotes.io/softmax-crossentropy
sum_of_prob_row = np.sum(np.exp(prob), axis=1) # Get sum of e^(prob) of the respective data
loss = -np.sum(prob[np.arange(num_train), y]) + np.sum(np.log(sum_of_prob_row), axis=0)
dW = (np.exp(prob) / sum_of_prob_row[:,np.newaxis]) # Convert sum of prob row to a column vector, divide matrix of e^(prob) by that
pi_factor = np.zeros_like(prob)
pi_factor[np.arange(num_train), y] = 1
dW -= pi_factor # Subtract the necessary pi factor where position i = j
dW = np.matmul(X.T, dW) # Multiply the dW score matrix by input X
loss /= num_train
loss += reg * np.sum(W * W)
dW /= num_train
dW += 2*reg*W
#############################################################################
# END OF YOUR CODE #
#############################################################################
return loss, dW
|
bb7e011af58577aeb02f97b7813ebe1efeb884fa | Lor3nzoMartinez/Python | /SPR19/Notes/AAA_oopPracticeAndNotes.py | 2,337 | 4.34375 | 4 | import math
print("\nSome OOP notes:\n")
# OOP Practice ############
class Dog:
# Class Attribute
species = 'mammal'
# Initializer / Instance Attributes
def __init__(self, name, age):
self.name = name
self.age = age
Philo = Dog("Philo",12)
Dani = Dog("Dani", 11)
Emma = Dog("Emma", 13)
def my_function(*args):
return max(args)
print("The oldest dog is {} years old.".format(
my_function(Philo.age, Dani.age, Emma.age)), "\n")
# OOP math practice ###########
class BankAccount:
balance = 0
def __init__ (self):
self.balance: 0
def withdraw(self, amount):
self.balance -= amount
return self.balance
def deposit(self, amount):
self.balance += amount
return self.balance
a = BankAccount()
print(a.deposit(1500),a.withdraw(750), "\n")
# Minute Converter ##############
minutes = 8911
days = minutes // 1440
hours = (minutes - (days * 1440)) // 60
minute = minutes % 60
print("There are", days, "days", hours, "hours and", minute, "minutes in", minutes, "minutes.\n")
# Input prob
'''
name = input("What should I call you: ")
radius = input("Hello " + name + " what is the radius of your circle: ")
circumference = (2*math.pi*int(radius))
print("Ok", name, "that means the circumference of your circle with a radius of", radius, "is", circumference)
'''
'''
WS ch2_10
You leave for vacation on Friday & return 123 days later. Use // and % to compute the number of weeks gone and
number of days after Friday that you returned. What day did you return?
'''
vacation = 123
weeksGone = vacation // 7
daysAfterFriday = vacation % 7
print("If you leave for", vacation, "days after Friday. You have been gone for", weeksGone, "weeks and will return",
daysAfterFriday, "after friday.\n")
'''
*************************************
WS ch2_11
Use a for loop with range to print out table of numbers for the
Square and cube of integers from 1 to 10. The first column should have the number,
the second column will have the square of the number and the third column will have the cube.
**************************************
'''
print("Num", " ", "Squared", " ", "Cubed")
for i in range(1, 11):
print(i, " ", (i**2), " ", (i**3))
sum = 0
for i in range(11,92,2):
sum = sum + i
print(sum)
|
552ffd7b70bcf52274e63d7928a3b7103a176354 | OutlawOne55/Algorithm_study | /Algorithm_Python/Study_00/que_04.py | 99 | 3.5 | 4 | s = input()
x = 0
for i in range(len(s)):
x = x + int(s[i])
print(x)
print(int(s) % x is 0)
|
20959e93e401c570c3b931753370ddfc0182eed8 | AdamZhouSE/pythonHomework | /Code/CodeRecords/2648/49823/309012.py | 157 | 3.75 | 4 | import random
n=int(random.random()*2)
if n==0:
print('whatthemmfun',end='')
elif n==1:
print('whatthefun',end='')
elif n==2:
print('Case 1: 4')
|
ecb95816d0eba2dd2dce67347258f436ea8033db | Nehrumathy/project187 | /project2.py | 102 | 3.8125 | 4 | # project187
fact=1;
n=int(input("Enter n:"));
for i in range(1,n+1):
fact=fact*i;
print(fact);
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.