blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
fd00acdfa7e5f6187dcef82ca53e2a34595bb3e9 | erinmiller926/adventurelab | /adventure_lab.py | 2,337 | 4.375 | 4 | # Adventure Game Erin_Miller
import random
print("Last night, you went to sleep in your own home.")
print("Now, you wake up in a locked room.")
print("Could there be a key hidden somewhere?")
print("In the room, you can see:")
# The menu Function:
def menu(list, question):
for item in list:
print(1 + list.index(item), item)
return int(input(question))
items = ["backpack", "painting", "vase", "bowl", "door"]
# This is the list of items in the room:
key_location = random.randint(1, 4)
# the key is not found.
key_found = "No"
loop = 1
# Display the menu until the key is found:
while loop == 1:
choice = menu(items, "What do you want to inspect?")
print("")
if choice < 5:
if choice == key_location:
print("You found a small key in the", items[choice-1])
key_found = "Yes"
else:
print("You found nothing in the", items[choice-1])
elif choice == 5:
if key_found == "Yes":
loop = 0
print(" You insert the key in the keyhole and turn it.")
else:
print("The door is locked. You need to find the key.")
else:
print("Choose a number less than 6.")
print("You open the door to a long corridor.")
print("You creep down the long corridor and tiptoe down the stairs.")
print("The stairs lead to a living room.")
print("You see the following:")
def menu2(list, question):
for item in list:
print(1 + list.index(item), item)
return int(input(question))
items = ["fireplace", "window", "bookcase", "closet", "door"]
key_location = random.randint(1, 4)
key_found = "No"
loop = 1
while loop == 1:
choice = menu(items, "What do you want to inspect?")
if choice < 5:
if choice == key_location:
print("You found a small key in the", items[choice-1])
key_found = "Yes"
else:
print("You found nothing in the", items[choice-1])
elif choice == 5:
if key_found == "Yes":
loop = 0
print(" You insert the key in the keyhole and turn it.")
else:
print("The door is locked. You need to find the key.")
else:
print("Choose a number less than 6.")
print("You exit the house before anyone came home. You breathe a sigh of relief.")
|
f3e0649ba83f365ea5d1a0dd16f04935935f5af5 | arihant-2310/Python-Programs | /average height og boys nd girls.py | 716 | 3.6875 | 4 | n= input('enter number of students:-')
student= []
print'\t\tENTER STUDENT DETAILS'
i=1
while i<=n:
name= raw_input('enter name-')
rno= input('enter roll number-')
gender= raw_input('enter your gender(M/F)-')
height= input('enter height in cms-')
student.append((name,rno,gender,height))
print
i= i+1
print'\t\tDETAILS OF STUDENTS'
print student
print
print
(nb,ng,hb,hg)=(0,0,0,0)
for i in student:
if i[2]=='f'or i[2]=='F':
ng= ng+1
hg= hg+i[3]
elif i[2]=='m'or i[2]=='M':
nb= nb+1
hb= hb+i[3]
else:
print'invalid entry'
print'average height of girls-',hg/ng
print'average height of boys-',hb/nb
|
4dd2b7b009d9eb025d8b867477e8919fdb38f70c | mrseidel-classes/archives | /ICS3U/ICS3U-2022-2023/Code/python-notes/14 - lists/lists.py | 838 | 4.625 | 5 | #-----------------------------------------------------------------------------
# Name: Lists (lists.py)
# Purpose: To provide examples of how to wor with lists in Python
# in a variety of ways including specific functions for lists
#
# Author: Mr. Seidel
# Created: 27-Oct-2018
# Updated: 27-Oct-2018
#-----------------------------------------------------------------------------
# creating a list of fruit as a list
fruit = ['apple', 'pear', 'peach', 'banana', 'pineapple']
# printing out the fruit list (individually) using the indexing method
for i in range(0, len(fruit), 1):
print(fruit[i])
# resetting fruit (in case something happened above)
fruit = ['apple', 'pear', 'peach', 'banana', 'pineapple']
# printing out the fruit list using the advanced for loop
for item in fruit:
print(item)
|
b5f295bac917dfe6a46e6309b43e0588d0581839 | ItamarRocha/DailyByte | /week_012/day84_countingprimes.py | 752 | 3.984375 | 4 | """
This question is asked by Google. Given a positive integer N, return the number of prime numbers less than N.
Ex: Given the following N…
N = 3, return 1.
2 is the only prime number less than 3.
Ex: Given the following N…
N = 7, return 3.
2, 3, and 5 are the only prime numbers less than 7.
"""
# https://www.geeksforgeeks.org/how-is-the-time-complexity-of-sieve-of-eratosthenes-is-nloglogn/
# Time O(n * log(log n))
# Space O(n)
def countprimes(n):
if n <= 2:
return 0
primes = [True] * (n)
primes[0] = primes[1] = False
for i in range(2,int(n ** 0.5) + 1):
if not primes[i]:
continue
for j in range(i+i,n, i):
primes[j] = False
return sum(primes)
print(countprimes(1)) |
9692cdddbc9a790e746f592936682fbc79f48536 | camohe90/-mision_tic_G1 | /s5/1.1_input.py | 797 | 4 | 4 | """ Realizar un codigo que simule una persona que saluda a otra, solicitar que el usuario ingrese su comida favorita y su color favorito. El sistema debe imprimir un unico mensaje saludando como el ejemplo y diciendo algun mensaje referente a la comida y al color"""
print("Manejo de información de entrata con python")
print("--------------------------------------------------")
primer_nombre = input("Por favor ingrese su nombre: ") #Guardo la información ingresada por teclado en la variables primer_nombre
primer_apellido = input("Por favor ingrese su apellido: ") #Guardo la información ingresada por teclado en la variables primer_apellido
print("Hola", end =" ")
print(primer_nombre, end =" ")
print(primer_apellido, end =" ")
print("es un gusto saludarte", end =" ")
|
316a9165f446c83160c82e7a48cdd20c70a0dcf6 | isabellapepke/SpotifyMatch | /playlist.py | 2,243 | 3.875 | 4 | import song
class Playlist:
"""Class holds a username and a library of songs. It is equipped with a __str__ method and
equality operator oveloads
List of class variables:
userId = Spotify userId of playlist -- dec in function __init__
songs = List of songs in playlist -- dec in function __init__
"""
def __init__(self, userId = "none", songs = []):
self.userId = userId
self.songs = songs
# str() method
def __str__(self):
string = ""
for song in self.songs:
string += str(song) + "\n"
return string
# == overload
def __eq__(self, other):
for song in self.songs:
if not (song in other.songs):
return False
return True
# != oveload
def __neq__(self,other):
return not (self == other)
def add (self, song):
"""adds parameter to playlist"""
self.songs.append(song)
def has(self, song):
"""returns true if parameter in playlist, false otherwise"""
if song in self.songs:
return True
return False
def compare(self, other):
""" Param: other playlist to compare
Returns: tuple (sharedSongs, sharedArtists, artistsCount) of type (Playlist, Set, Int) where
sharedSongs = playlist object containing songs in common
sharedArtists = set of all artists who have at least one song in both playlists
artistsCount = number pairs of songs (one song from each playlist) with the same artist
"""
sharedSongs = Playlist("none",[])
sharedArtists = set()
artistsCount = 0
artistPairs = []
for song in self.songs:
if song in other.songs:
sharedSongs.add(song)
for track in other.songs:
if song.artists == track.artists:
if not (track in artistPairs):
for artist in song.artists:
sharedArtists.add(artist)
artistPairs.append(track)
artistsCount+=1
return (sharedSongs, sharedArtists, artistsCount)
|
0c005a91a1073c441040d91cdc5719afad1514f3 | jiawu/ChicagoCrime | /checkpoints/checkpoint1.py | 1,491 | 3.609375 | 4 | crime_file_name = '/Users/jjw036/ChicagoCrime/crimes_2001_to_present_parsed.csv'
file_object = open(filename, 'r')
#read the file line-by-line
data_list = []
for line in file_object:
#get rid of \n newspace
new_line = line.strip()
data_list.append(new_line)
#first line is the header, remove that from the data and save it
data_header = data_list.pop(0)
#1. How many crimes have been reported from 2001 to present?
total_crimes = len(data_list)
#Organizing the data into easily ascessible structures.
#let's model the crime data with a dictionary. Each entry/line will be turned into what we define as a case
case_list = []
for entry in data_list:
entry = entry.split(',')
case = { "ID": entry[0],
"CaseNumber": entry[1],
"Date": entry[2],
"Block": entry[3],
"Type": entry[4],
"Description": entry[5],
"LocationType": entry[6],
"Ward": entry[7],
"Year": entry[8],
"Month": entry[9],
"Latitude": entry[10],
"Longitude": entry[11]
}
case_list.append(case)
#Writing your first function:
def read_data(filename):
"""Returns a list of all the lines in the file, minus the header"""
file_object = open(filename, 'r')
#read the file line-by-line
data_list = []
for line in file_object:
#get rid of \n newspace
new_line = line.strip()
data_list.append(new_line)
#first line is the header, remove that from the data and save it
data_header = data_list.pop(0)
return(data_list)
data_list = read_data(crime_file_name) |
518b3c35d6494096190774c26fb993009c557daa | yveega/CoffeeGraphics | /Kolya_pyprojects/Turtle_Kolya.py | 2,981 | 3.53125 | 4 | from math import *
from random import randint
def dekahex2(n):
n = round(n)
lc = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f']
return lc[(n % 256) // 16] + lc[n % 16]
def tow(x1, y1, x2, y2):
return atan((x2 - x1) / (y2 - y1))
def rgb(red, green, blue):
return '#' + dekahex2(red) + dekahex2(green) + dekahex2(blue)
class Turtle:
def __init__(self, canvas, x=0, y=0, direction=0, color='black', draw=False, width=1):
self.canvas = canvas
self.x = x
self.y = y
self.d = (direction - 180) / -180 * pi
self.color = color
self.draw = draw
self.width = width
def goto(self, x, y, pen=False):
if pen:
self.canvas.create_line(self.x, self.y, x, y, fill=self.color, width=self.width)
self.x = x
self.y = y
def fd(self, step):
xn = self.x + step * sin(self.d)
yn = self.y + step * cos(self.d)
if self.draw:
self.canvas.create_line(self.x, self.y, xn, yn, fill=self.color, width=self.width)
self.x = xn
self.y = yn
def bd(self, step):
xn = self.x - step * sin(self.d)
yn = self.y - step * cos(self.d)
if self.draw:
self.canvas.create_line(self.x, self.y, xn, yn, fill=self.color, width=self.width)
self.x = xn
self.y = yn
def rt(self, deg):
self.d -= deg / 180 * pi
def lt(self, deg):
self.d += deg / 180 * pi
def dir(self, deg):
self.d = (deg - 180) / -180 * pi
def rgb(self, red, green, blue):
self.color = '#' + dekahex2(red) + dekahex2(green) + dekahex2(blue)
def set_gradient(self, start_color, end_color, k):
red = start_color[0] + (end_color[0]-start_color[0]) * k
green = start_color[1] + (end_color[1]-start_color[1]) * k
blue = start_color[2] + (end_color[2]-start_color[2]) * k
self.rgb(red, green, blue)
def pu(self):
self.draw = False
def pd(self):
self.draw = True
def tow(self, x, y):
self.d = tow(self.x, self.y, x, y)
class ColorCube:
def __init__(self, r_start=randint(20, 235), g_start=randint(20, 235), b_start=randint(20, 235),
r_step=1, b_step=1, g_step=1):
self.r = r_start
self.g = g_start
self.b = b_start
self.r_step = r_step
self.g_step = g_step
self.b_step = b_step
def __call__(self, *args, **kwargs):
return rgb(self.r, self.g, self.b)
def change_color(self):
if self.r <= abs(self.r_step)+1 or self.r >= 254-abs(self.r_step):
self.r_step *= -1
if self.g <= abs(self.g_step)+1 or self.g >= 254-abs(self.g_step):
self.g_step *= -1
if self.b <= abs(self.b_step)+1 or self.b >= 254-abs(self.b_step):
self.b_step *= -1
self.r += self.r_step
self.g += self.g_step
self.b += self.b_step
|
611f3d889139072582ccc696bbe9a6b7e0779ea0 | KseniiaPitel/python_course | /functional programming tasks/stairs.py | 424 | 4.0625 | 4 | import sys
stairs_num=sys.argv[1]
#stairs_num = input("Enter the number of stairs ")
stairs_num = int(stairs_num)
hashtags = (stairs_num + 1) - stairs_num
spaces = stairs_num - 1
n: int = spaces
j: int = 1
hash = "#"
sp = " "
temp_sp = sp * n
temp_hash = hash * j
while hashtags <= n and spaces >= j:
print(temp_sp+temp_hash)
n -= 1
j += 1
temp_sp = sp * n
temp_hash = hash * j
print(hash*stairs_num)
|
de7058426abcf7dc18cf1e6c364a43ee86de8697 | jteti/jteti2013_PyHomework1 | /jteti2013_ExtraPoints_classes.py | 770 | 4.03125 | 4 | # Extra Points
# Create a class called Student that has the properties:
class Student:
# Count variable set to 0
studentCount = 0
def __init__(self, name, age, birthmonth ):
# name (holds student name)
self.name = name
# age (holds student age)
self.age = age
# birthmonth (holds students birthmonth)
self.birthmonth = birthmonth
# Upon each call to the class this variable increments
Student.studentCount += 1
# Function Displayname returns the student name
def displayName(self):
print("Student name: ", self.name)
# Function DisplayBirthmonth returns the student birthmonth
def displayBirthmonth(self):
print("Birthmonth: ", self.age)
|
5919738e2e778fc6acb1317abfeb907d18e325cc | damani-14/supplementary-materials | /Python_Exercises/Chapter03/CH03_12.py | 413 | 4.15625 | 4 | # program to find the sum of the cubes of the first n natural numbers
import math
def main():
print("")
print("This program will find the sum of the cubes")
print("of the first n natural numbers given user")
print("provided input for n")
print("")
n = eval(input("Please enter a value for n : "))
tot = 0
for i in range(n + 1):
tot = tot + i**3
print(tot)
main() |
4db43b3627ce71b65078c3610a3ad71319c4c739 | Audarya07/Daily-Flash-Codes | /Week4/Day6/Solutions/Python/prog3.py | 183 | 3.609375 | 4 | for num in range(1,101):
sum = 0
for i in range(1,num):
if num%i==0:
sum+=i
if sum==num:
continue
else:
print(num,end=" ")
print()
|
e0617aae5d5029ed63f5788e47e0c6b0122f90ab | leo-gs/machine_learning_tools | /regression.py | 757 | 3.53125 | 4 | import data
import numpy as np
class LinearRegression():
def __init__(self, dataset):
self.dataset = dataset
def least_squares(self, predictor, label):
if not data.is_numeric(self.dataset.get_attribute_datatype(predictor)) or not data.is_numeric(self.dataset.get_attribute_datatype(label)):
raise ValueError('Both the predictor and label must be numeric')
n = len(self.dataset)
xs = self.dataset.get_column_vector(predictor)
ys = self.dataset.get_column_vector(label)
mean_x = xs.mean()
mean_y = ys.mean()
b1 = ((xs - mean_x) * (ys - mean_y)).sum() / ((xs - mean_x) ** 2).sum()
b0 = (float(ys.sum()) / n) - b1 * (float(xs.sum()) / n)
self.b1 = b1
self.b0 = b0
def predict(self, value):
return self.b1 * value + self.b0 |
436fb9a968d82e1e3ac337a403b9bab6462dba54 | sanjeevseera/Python-Practice | /Data-Structures/Tuple/P03.py | 217 | 4.375 | 4 | """
Write a Python program to create a tuple with numbers and print one item
"""
#Create a tuple with numbers
tuplex = 5, 10, 15, 20, 25
print(tuplex)
#Create a tuple of one item
tuplex = 5,
print(tuplex)
|
69b43f932c6e231a1231950a154012470614c3fd | colms/programming-and-algorithms-1 | /Assignment/selection_sort.py | 1,169 | 4.25 | 4 | # selection sort
import sorted_checker
def single_iteration(numbers, iteration_number):
"""Performs one iteration of the sorting algorithm.
Mutates input list and does not return a value.
"""
pass
def multiple_iterations(numbers_original, num_iterations_to_complete):
"""Performs the specified number of iterations of the sorting algorithm.
Returns a sorted copy of the list of numbers.
"""
pass
def sort(numbers_original):
"""Sorts a list of numbers in ascending order using the bubble sort algorithm.
Returns a sorted copy of the list of numbers.
"""
i = 0
numbers_copy = numbers_original[:]
# used to prevent infinite loop when is_sorted isn't implemented
if sorted_checker.is_sorted(numbers_copy) is None:
return None
while not sorted_checker.is_sorted(numbers_copy):
single_iteration(numbers_copy, i)
i += 1
return numbers_copy
""" output should look like this:
[4, 1, 6, 2, 7, 9, 4, 3]
[1, 4, 6, 2, 7, 9, 4, 3]
[1, 2, 6, 4, 7, 9, 4, 3]
[1, 2, 3, 4, 7, 9, 4, 6]
[1, 2, 3, 4, 7, 9, 4, 6]
[1, 2, 3, 4, 4, 9, 7, 6]
[1, 2, 3, 4, 4, 6, 7, 9]
7 iterations in total
"""
|
ac6a3a8d4a3cf2af2dbba211e8c9f5cc81099645 | nicktsao88/python | /nick.py | 82 | 3.734375 | 4 | name=input("who are youname?")
print("hello,"+name)
print("come to learn python")
|
927ef6b16dbf85fbc068b1acdbcf2f10a99e1cd7 | CNieves121/lps_compsci | /problem_sets/problemset4/problemset4.py | 742 | 3.8125 | 4 | bacteria_population = 1
minutes = 0
while bacteria_population < 5000000:
print("After " + str(minutes) + " minutes, there are " + str(bacteria_population) + " bacteria in the sink.")
print("No need to disinfect the sink yet.")
bacteria_population = bacteria_population * 2
minutes = minutes + 1
print("After " + str(minutes) + " minutes, there are " + str(bacteria_population) + " bacteria in the sink.")
print("You shoud use some Clorox on the sink now.")
"""
account_balance = 1000
withdrawal = 50
while account_balance > 0:
print("Ok, your withdrawal has been made.")
account_balance = account_balance - withdrawal
print("Your balance is now $" + str(account_balance) + ".")
"""
|
95a9db8725abf044052c99018e08d2814ce77c7b | eachofwhich/Udacity_CS212 | /Unit3/find_tags.py | 1,318 | 4.46875 | 4 | # Unit 3 Hw 3-3
# Implement a function findtags() that extracts all HTML tags from a document.
import sys, re
def findtags(text):
"""Return a list of all HTML tags within text."""
pattern_string = r'<\s*\w+(?:\s*\w+\s*="?[\w\.\_]+"?)*\s*>'
regex = re.compile(pattern_string)
return regex.findall(text)
testtext1 = """
My favorite website in the world is probably
<a href="www.udacity.com">Udacity</a>. If you want
that link to open in a <b>new tab</b> by default, you should
write <a href="www.udacity.com"target="_blank">Udacity</a>
instead!
"""
testtext2 = """
Okay, so you passed the first test case. <let's see> how you
handle this one. Did you know that 2 < 3 should return True?
So should 3 > 2. But 2 > 3 is always False.
"""
testtext3 = """
It's not common, but we can put a LOT of whitespace into
our HTML tags. For example, we can make something bold by
doing < b > this < /b >, Though I
don't know why you would ever want to.
"""
def test():
result = findtags(testtext1)
check = ['<a href="www.udacity.com">', '<b>', '<a href="www.udacity.com"target="_blank">']
assert result == check, result
assert findtags(testtext2) == []
assert findtags(testtext3) == ['< b >']
return 'tests pass'
print test() |
f154f49a57a3d0e738584d37579f3e62bd6ab62f | Arwen0905/Python_Test | /TQC_考題練習/b0529_TQC證照_708.py | 1,677 | 3.6875 | 4 | # 1. 題目說明:
# 請開啟PYD708.py檔案,依下列題意進行作答,進行兩詞典合併,
# 使輸出值符合題意要求。作答完成請另存新檔為PYA708.py再進行評分。
# 2. 設計說明:
# 請撰寫一程式,自行輸入兩個詞典(以輸入鍵值"end"作為輸入結束點,
# 詞典中將不包含鍵值"end"),將此兩詞典合併,
# 並根據key值字母由小到大排序輸出,如有重複key值,
# 後輸入的key值將覆蓋前一key值。
# 3. 輸入輸出:
# 輸入說明
# 輸入兩個詞典,直至end結束輸入
# 輸出說明
# 合併兩詞典,並根據key值字母由小到大排序輸出,如有重複key值,
# 後輸入的key值將覆蓋前一key值
# 輸入輸出範例
# 輸入與輸出會交雜如下,輸出的部份以粗體字表示
# Create dict1:
# Key: a
# Value: apple
# Key: b
# Value: banana
# Key: d
# Value: durian
# Key: end
# Create dict2:
# Key: c
# Value: cat
# Key: e
# Value: elephant
# Key: end
# a: apple
# b: banana
# c: cat
# d: durian
# e: elephant
# ※要看圖片※
# 下圖中的 粉紅色點 為 空格
#TODO
def compute():
dic={}
while True:
key = input("Key: ")
#Key: (後方有一空白格)
if key == 'end':
return dic
value = input("Value: ")
#Value: (後方有一空白格)
dic[key] = value
print('Create dict1:')
dict1 = compute()
print('Create dict2:')
dict2 = compute()
merge_dict = dict1.copy()
merge_dict.update(dict2)
merge_sort = sorted(merge_dict)
for i in merge_sort:
print('%s: %s'%(i,merge_dict[i]))
###### 輸出字串、soered()的使用、輸出時的字典指定觀念 ######
|
08b4aa3c2a81787538fe76b1e626708766946aa0 | BryceFuller/quantum-mobile-backend | /qiskit/backends/_basebackend.py | 967 | 3.515625 | 4 | """This module implements the abstract base class for backend modules.
To create add-on backend modules subclass the Backend class in this module.
Doing so requires that the required backend interface is implemented.
"""
from abc import ABC, abstractmethod
class BaseBackend(ABC):
@abstractmethod
def __init__(self, qobj):
"""Base class for backends.
This method should initialize the module and its configuration, and
raise a FileNotFoundError exception if a component of the module is
not available.
Args:
qobj (dict): qobj dictionary
Raises:
FileNotFoundError if backend executable is not available.
"""
self._qobj = qobj
self._configuration = None # IMPLEMENT for your backend
@abstractmethod
def run(self):
pass
@property
def configuration(self):
"""Return backend configuration"""
return self._configuration
|
b6f5b4fbebda9beb5e03c07b5fc105c473097b70 | sofiazk/cs108 | /CS108/a07_acumulator.py | 928 | 4.09375 | 4 | # file: a07_accumulator.py
# author: Sofia Kurd (sofiak@bu.edu)
# description:
def sum_of_range(start, stop, skip):
'''Calculates and returns the sum of the numbers produced by the
range function'''
sum = 0
for i in range(start, stop, skip):
sum += i
print(sum)
def replace(s, old_ch, new_ch):
'''Processes the string s and replaces all occurrences of char old_ch with
new_ch'''
result = ""
for old_ch in s:
s.split(old_ch)
new_ch.join(new_ch)
return(s + new_ch)
print(replace("chocolate", "o", "a"))
def calculate_average():
'''Collects input from keyboard, calculates and prints out avg of inputs'''
n = int(input("How many observations do you have? "))
sum = 0
for i in range(0, n):
sum += int(input("Enter next value: "))
print("The average is " + str(sum/n) + ".")
sum_of_range(1, 5, 1)
calculate_average()
|
897b235f1f3c187c96ca69fdd83c85fdebf3324f | srisar/python_kavi_class | /functions/types_of_func1.py | 321 | 3.953125 | 4 | # Types of functions
# 1. With returnable value
# 2. Without returnable value (procedure)
#
#
# 1. With returnable value
def add(a, b):
return a + b
x = add(3, 4)
# add(1,2) = x # cant do this!
# 2. Without returnable value
def sayHello():
print("saying hello!")
print("saying goodbye!")
sayHello()
|
259287c41cbc1cffc832192c9656af1fd8aa2f51 | santiago-pan/project-euler | /python/problem7/problem.py | 986 | 4 | 4 | import sys
def isDivisor(number, divisor):
return number % divisor == 0
def isPrime(number):
if number < 2:
return False
for divisor in range(2, int(number**0.5) + 1):
if isDivisor(number, divisor):
return False
return True
def getNextPrimeNumber(currentPrime):
currentPrime = currentPrime + 1
while isPrime(currentPrime) == False:
currentPrime = currentPrime + 1
return currentPrime
# Recursion in python can cause maximum recursion depth
sys.setrecursionlimit(15000)
def getPrimeAtPositionRecursive(toPosition, position=0, prime=1):
if (position == toPosition):
return prime
else:
prime = getNextPrimeNumber(prime)
return getPrimeAtPositionRecursive(toPosition, position + 1, prime)
def getPrimeAtPosition(toPosition):
position = 0
prime = 1
while (position < toPosition):
prime = getNextPrimeNumber(prime)
position = position + 1
return prime
|
10c21cb2a23665dc89c01b9d32b00d7373fe67d1 | Bhuvana11/anu | /set1a.py | 111 | 4.09375 | 4 | # your code goes here
num=3
if(num>0):
print("positive")
elif(num<0):
print("negative")
else:
print("zero")
|
1d5b77607ecdabfc875486e82d36178fb918a1bd | kiraheta/data-structures-and-algorithms | /data structures/hash_table/python/hashtable.py | 1,934 | 3.703125 | 4 |
#!/usr/bin/python
"""
Hash Table implementation
Load Factor = num of items / tablesize
"""
class HashTable():
def __init__(self):
self.size = 11
self.buckets = [None] * self.size
self.data = [None] * self.size
def put(self, key, data):
hashvalue = self.hashfunction(key, len(self.buckets))
if self.buckets[hashvalue] == None:
self.buckets[hashvalue] = key
self.data[hashvalue] = data
else:
if self.buckets[hashvalue] == key:
self.data[hashvalue] = data
else:
nextbucket = self.rehash(hashvalue, len(self.buckets))
while self.buckets[nextbucket] is not None and \
self.buckets[nextbucket] is not key:
nextbucket = self.rehash(nextbucket, len(self.buckets))
if self.buckets[nextbucket] == None:
self.buckets[nextbucket] = key
self.data[nextbucket] = data
else:
self.data[nextbucket] = data
def hashfunction(self, key, size):
return key % size
def rehash(self, oldhash, size):
return (oldhash + 1) % size
def get(self, key):
startbucket = self.hashfunction(key, len(self.buckets))
data = None
stop = False
found = False
position = startbucket
while self.buckets[position] is not None and \
not found and not stop:
if self.buckets[position] == key:
found = True
data = self.data[position]
else:
position = self.rehash(position, len(self.buckets))
if position == startbucket:
stop = True
return data
def __getitem__(self, key):
return self.get(key)
def __setitem__(self, key, data):
self.put(key, data)
|
d5dee3c68ce06e1f95046d443f68c447be0af944 | korynewton/Intro-Python-II | /src/room.py | 783 | 3.59375 | 4 | # Implement a class to hold room information. This should have name and
# description attributes.
from item import Item
class Room:
n_to = None
s_to = None
e_to = None
w_to = None
def __init__(self, name, description):
self.name = name
self.description = description
self.items = []
def __repr__(self):
string_of_items = "\n".join([str(x) for x in self.items])
return f"\nCurrent Location: {self.name}...{self.description}.\n\n \
Items availabe: \n{string_of_items}"
def add_to_room(self, item):
self.items.append(item)
print(f'**{item.name} added to room**')
def remove_from_room(self, item):
self.items.remove(item)
print(f'**{item.name} removed from room**')
|
0b48ce4c0c35d93dc7646e23a032550437d09950 | tesladodger/Fibonacci | /fibonacci.py | 3,582 | 4.21875 | 4 | #Fibonacci
#Calculates the sequence to the nth iteration or up to a certain number
#You can save the results to a '.txt' file with the name you want
#André Martins, 2018
import sys
import os
def ntimes(n, clear) :
save_file = 0;
try :
n = int(n);
except ValueError :
print('\n\nYou must introduce an integer\n\n')
return save_file; #=False
if (n <= 0) :
print('\n\nYou must introduce a positive integer\n\n')
return save_file; #=False
os.system(clear)
num = 1;
next_num = 1;
print(num)
for x in range(0,n-1) :
print(next_num) #By doing this we do one less calculation
temp = next_num; #Is there a better way to do this without temp?
next_num = next_num + num;
num = temp;
print('\nS - Save to a file')
print('else - Go to the main menu')
ntimeschoice = str(input('==> '));
if (ntimeschoice=='s') :
save_file = 1;
return save_file; #=True
else :
os.system(clear)
return save_file; #=False
def upton(maxnum, clear) :
try :
maxnum = int(maxnum);
except ValueError :
print('\n\nYou must introduce an integer\n\n')
return;
if (maxnum < 1) :
print('\n\nYou must insert a value greater or equal to 1\n\n')
os.system(clear)
num = 1;
next_num = 1;
itera = 0;
print(num)
while (next_num<=maxnum) :
print(next_num)
temp = next_num;
next_num = next_num + num;
num = temp;
itera += 1;
print('\nS - Show more information')
print('else - Go to the main menu')
ntimeschoice = str(input('==> '));
if (ntimeschoice=='s') :
os.system(clear)
if (num==maxnum) :
print("The number", maxnum, "is in the Fibonacci sequence")
print("Number of iterations: ", itera)
print("Your number: ", maxnum)
print("Next number in the sequence:", next_num)
print("Diference to that number: ", (next_num - maxnum))
print("\n\n")
return;
else :
print('')
return;
def file_saver(n) :
name = str(input('Name of the file: '));
name = name.replace(" ","") #Remove whitespaces to avoid issues
name = name + '.txt';
file = open(name,"w");
conc = "Number of iterations: " + n + '\n';
file.write(conc)
num = 1;
next_num = 1;
n = int(n); #No need to check, we already know it's an int
for x in range(0,n) :
str_num = str(num) + '\n';
file.write(str_num)
temp = next_num;
next_num = next_num + num;
num = temp;
file.close()
return name;
def message() :
import datetime
hour = datetime.datetime.now().hour;
if (hour>=20) :
greeting = 'night!';
elif (hour>=12) :
greeting = 'afternoon!';
elif (hour>=5) :
greeting = 'day!';
else :
greeting = 'night!';
return greeting;
plat = sys.platform
if (plat == 'linux') :
clear = 'clear';
elif (plat == 'win32') :
clear = 'cls';
else : clear = 'clear';
os.system(clear)
print(' __________________________')
print('| |')
print('|** Fibonacci calculator **|')
print('|__________________________|\n\n')
repeat = 1;
while (repeat==True) :
print('1 - Calculate n number of times')
print('2 - Calculate up to a certain number')
print('T - Terminate')
choice = str(input('==> '));
choice = choice.upper();
if (choice=='1') :
n = str(input('Number of times: '));
save_file = ntimes(n,clear);
if (save_file==True) :
name = file_saver(n);
os.system(clear)
print('\nFile saved as:', name, '\n\n')
elif (choice=='2') :
maxnum = str(input('Calculate to the number: '))
upton(maxnum, clear);
elif (choice=='T') :
import datetime
greeting = message();
print('\nThank you, have a good', greeting)
repeat = 0;
else :
os.system(clear)
print('\nInvalid option\n')
|
bd37d7f243c7e67aae25294b3a82abb73074b781 | jihyun28/Python | /practice.py | 16,865 | 3.8125 | 4 | # -*- coding: euc-kr -*-
### ڷ
## ڷ
print(5)
print(-10)
print(3.14)
print(5+3)
print(5*4)
print(3*(3+1))
## ڿ ڷ
print('abc')
print("a"*9)
print(""*5)
## boolean ڷ - /
print(5>10)
print(True)
print(not True)
print(not (5>10))
##
animal = ""
name = "ź"
age = 4
hobby = "å"
is_adult = age >= 3
print("츮 " + animal + " ̸ " + name + "")
print(name + " " + str(age) + "̸, " + hobby + " ؿ")
print(name, " ϱ?", is_adult) # ǥ ĭ
## ּ
# ּ
''' ̷
ϸ
ּó'''
# [ctrl] + '/' ϰ ּó
###
##
print(1+1)
print(2**3) # 2^3=8
print(4//3) # 1
print(10 > 3) # True
print(4 == 2) # False
print(1 != 3) # True
print((3 > 0) & (3 < 5)) # True
print((3 > 0) | (3 < 5)) # True
print(5 > 4 > 7) # False
##
print(2 + 3 * 4)
number = 2 + 3 * 4
print(number)
number += 2 # 16
print(number)
number %= 2 # 0
print(number)
## ó Լ
print(abs(-5)) # 5
print(pow(4, 2)) # 4^2
print(max(5, 12)) # 12
print(min(5, 12)) # 5
print(round(3.14)) # 3 (ݿø)
from math import *
print(floor(4.99)) # 4 ()
print(ceil(3.14)) # 4 (ø)
print(sqrt(16)) # 4.0 ()
## Լ
from random import *
print(random()) # 0.0 ~ 1.0 ̸
print(random() * 10) # 0.0 ~ 10.0 ̸
print(int(random() * 10 + 1)) # 1 ~ 10
print(randrange(1, 45)) # 1 ~ 45 ̸
print(randint(1, 45)) # 1 ~ 45
### ڿ ó
## ڿ
sentence = ' ҳԴϴ'
print(sentence)
sentence2 = """
ҳ̰,
̽
"""
print(sentence2)
## ̽
jumin = "990120-1234567"
print(" : " + jumin[7])
print(" : " + jumin[0:2]) # 0 2 (0,1)
print(" : " + jumin[2:4])
print(" : " + jumin[4:6])
print(" : " + jumin[:6]) # ó 6
print(" 7ڸ : " + jumin[7:]) # 7
print(" 7ڸ(ں) : " + jumin[-7:]) # ڿ 7°
## ڿ ó Լ
python = "Python is Amazing"
print(python.lower()) # ڸ ҹڷ
print(python.upper()) # ڸ 빮ڷ
print(python[0].isupper()) # []° ڰ 빮
print(len(python)) # ڿ
print(python.replace("Python", "Java")) # ڿ ü
index = python.index("n") # n̶ ڰ °
print(index) # 5
index = python.index("n", index + 1) # ġ(index + 1)
print(index) # 15
print(python.find("Java")) # ڿ ã -> -1
# print(python.index("Java")) # ڿ ã ->
print(python.count("n")) # ش
## ڿ
# 1
print(" %dԴϴ." % 20)
print(" %s ؿ." % "̽")
print("Apple %c ؿ." % "A")
print(" %s %s ؿ." % ("Ķ", ""))
# 2
print(" {}Դϴ.".format(20))
print(" {} {} ؿ." .format("Ķ", ""))
print(" {0} {1} ؿ." .format("Ķ", "")) # Ķ ؿ.
print(" {1} {0} ؿ." .format("Ķ", "")) # Ķ ؿ.
# 3
print(" {age}̸, {color} ؿ.".format(age = 20, color = ""))
print(" {age}̸, {color} ؿ.".format(color = "", age = 20))
# 4 (v 3.6 ̻)
age = 20
color = ""
print(f" {age}̸, {color} ؿ.")
## Ż
# \n : ٹٲ
print("鹮 ҿϰ\n ҿŸ")
# \" \' : ǥ
print(" \"ڵ\"Դϴ.") # "ڵ"Դϴ.
print(" \'ڵ\'Դϴ.") # "ڵ"Դϴ.
# \\ : \
print("C:\\Users\\user\\Desktop\\PythonWorkspace>")
# \r : Ŀ ̵
print("Red Apple\rPine") # PineApple
# \b : 齺̽ ( )
print("Redd\bApple") # RedApple
# \t :
print("Red\tApple") # Red Apple
### ڷᱸ
## Ʈ
# ö ĭ 10, 20, 30
subway = [10, 20, 30]
print(subway)
subway = ["缮", "ȣ", "ڸ"]
print(subway)
# ȣ ° ĭ Ÿ ִ°?
print(subway.index("ȣ")) # 1
# Ͼ 忡 ĭ Ž
subway.append("")
print(subway) # ['缮', 'ȣ', 'ڸ', '']
# 缮 / ȣ ̿ ¿
subway.insert(1, "")
print(subway) # ['缮', '', 'ȣ', 'ڸ', '']
# ö ִ ڿ
print(subway.pop())
# ̸ ִ Ȯ
print(subway.count("缮")) # 1
# ĵ
num_list = [5,2,4,3,1]
num_list.sort()
print(num_list) # [1, 2, 3, 4, 5]
#
num_list.reverse()
print(num_list) # [5, 4, 3, 2, 1]
#
num_list.clear()
print(num_list) # []
# پ ڷ Բ
mix_list = ["ȣ", 20, True]
# Ʈ Ȯ
num_list = [1, 2, 3, 4, 5]
num_list.extend(mix_list)
print(num_list) # [1, 2, 3, 4, 5, 'ȣ', 20, True]
##
cabinet = {3:"缮", 100:"ȣ"}
print(cabinet[3]) # 缮
print(cabinet[100]) # ȣ
print(cabinet.get(3)) # 缮
# print(cabinet[5]) # (α )
print(cabinet.get(5)) # None
print(cabinet.get(5, " ")) #
print(3 in cabinet) # True
print(5 in cabinet) # False
cabinet = {"A-3":"缮", "B-100":"ȣ"}
print(cabinet["A-3"])
# մ
print(cabinet) # {'A-3': '缮', 'B-100': 'ȣ'}
cabinet["A-3"] = ""
cabinet["C-20"] = "ȣ"
print(cabinet) # {'A-3': '', 'B-100': 'ȣ', 'C-20': 'ȣ'}
# մ
del cabinet["A-3"]
print(cabinet)
# key鸸
print(cabinet.keys())
# value鸸
print(cabinet.values())
# key, value
print(cabinet.items())
#
cabinet.clear()
print(cabinet)
## Ʃ
# ʴ
# Ʈ ӵ
menu = ("", "ġ")
print(menu[0])
# menu.add("") #
(name, age, hobby) = ("", 20, "ڵ")
print(name, age, hobby)
## Ʈ
# (set)
# ߺ ȵ,
my_set = {1,2,3,3,3}
print(my_set) # {1, 2, 3}
java = {"缮", "ȣ", "缼"}
python = set(["缮", "ڸ"])
#
print(java & python) # {'缮'}
print(java.intersection(python)) # {'缮'}
#
print(java | python) # {'缮', 'ڸ', 'ȣ', '缼'}
print(java.union(python)) # {'缮', 'ڸ', 'ȣ', '缼'}
#
print(java - python) # {'缼', 'ȣ'}
print(java.difference(python)) # {'缼', 'ȣ'}
# ߰
python.add("ȣ")
print(python) # {'ȣ', '缮', 'ڸ'}
#
java.remove("ȣ")
print(java) # {'缼', '缮'}
## ڷᱸ
menu = {"Ŀ", "", "ֽ"}
print(menu, type(menu)) # {'ֽ', '', 'Ŀ'} <class 'set'>
menu = list(menu)
print(menu, type(menu)) # {'ֽ', '', 'Ŀ'} <class 'list'>
menu = tuple(menu)
print(menu, type(menu)) # {'ֽ', '', 'Ŀ'} <class 'tuple'>
###
## if
weather = "ƿ"
if weather == "":
print(" ì⼼")
elif weather == "̼":
print("ũ ì⼼")
else:
print("غ ʿ ")
# temp = int(input(" ?"))
# if 30 <= temp:
print("ʹ .")
# else:
# print("ʹ ߿.")
## for
for waiting_no in [0, 1, 2, 3, 4]:
print("ȣ : {0}".format(waiting_no))
for waiting_no in range(5): # 0, 1, 2, 3, 4
print("ȣ : {0}".format(waiting_no))
for waiting_no in range(1, 6): # 1, 2, 3, 4, 5
print("ȣ : {0}".format(waiting_no))
starbucks = ["̾", "丣", "̿ Ʈ"]
for customer in starbucks:
print("{0}, Ŀǰ غǾϴ.".format(customer))
## while
# while ݺ
customer = "丣"
index = 5
while index >= 1:
print("{0}, Ŀǰ غǾϴ. {1} Ҿ.".format(customer, index))
index -= 1
if index == 0:
print("ĿǴ óеǾϴ.")
# ѷ - [Ctrl] + C
# while True:
## continue break
# continue : ʰ, ݺ
# break : ʰ, ݺ Ż
## for
# 1,2,3,4 տ 100 ̱ -> 101,102,103,104
students = [1,2,3,4,5]
students = [i+100 for i in students]
print(students)
# л ̸ ̷ ȯ
students = ["Iron man", "Thor", "I am groot"]
students = [len(i) for i in students]
print(students) # [8, 4, 10]
# л ̸ 빮ڷ ȯ
students = ["Iron man", "Thor", "I am groot"]
students = [i.upper() for i in students]
print(students) # ['IRON MAN', 'THOR', 'I AM GROOT']
### Լ
## Լ
def open_account():
print("ο ° Ǿϴ.")
open_account()
## ް ȯ
def deposit(balance, money): # Ա
print("Ա ϷǾϴ. ܾ {0}Դϴ.".format(balance + money))
return balance + money
def withdraw(balance, money): #
if balance >= money:
print(" ϷǾϴ. ܾ {0}Դϴ.".format(balance - money))
return balance - money
else:
print(" Ϸ ʾҽϴ. ܾ {0}Դϴ.".format(balance))
return balance
balance = 0
balance = deposit(balance, 1000)
print(balance)
balance = withdraw(balance, 500)
print(balance)
## ⺻
def profile(name, age = 17, main_lang = "C"):
print("̸ : {0}\t : {1}\t : {2}".format(name, age, main_lang))
profile("缮")
profile("ȣ")
## Ű尪
def profile(name, age, main_lang):
print(name, age, main_lang)
profile(name="缮", main_lang="̽", age=20)
##
def profile(name, age, lang1, lang2, lang3, lang4, lang5):
print("̸ : {0}\t : {1}\t".format(name, age), end=" ") # end=" " ٹٲ ʰ ⸸ Ѵٴ ǹ
print(lang1, lang2, lang3, lang4, lang5)
profile("缮", 20, "Python", "Java", "C", "C++", "C#")
def profile(name, age, *language):
print("̸ : {0}\t : {1}\t".format(name, age), end=" ")
for lang in language:
print(lang, end=" ")
print()
profile("缮", 20, "Python", "Java", "C", "C++", "C#", "HTML")
profile("ȣ", 25, "Python", "Java")
##
# : Լ
# : α
###
## ǥ
print("Python", "Java", sep=",")
print("Python", "Java", sep=",", end="?")
import sys
print("Python", "Java", file=sys.stdout) # ǥ
print("Python", "Java", file=sys.stderr) # ǥ ó
scores = {"":0, "":50, "ڵ":100}
for subject, score in scores.items():
print(subject.ljust(8), str(score).rjust(4), sep=":")
for num in range(1,21):
print("ȣ : " + str(num).zfill(3)) # 3ĭ 0 ä
# Է ؼ ڿ ȴ.
# answer = input("ƹ ̳ Էϼ : ")
# print("ԷϽ " + answer + "Դϴ.")
## پ
# ڸ ΰ, ϵ, 10ڸ Ȯ
print("{0: >10}".format(500))
# + ǥ, - ǥ
print("{0: >+10}".format(500))
print("{0: >+10}".format(-500))
# ϰ, ĭ _ ä
print("{0:_<10}".format(500))
# 3ڸ ֱ
print("{0:,}".format(100000000000))
# 3ڸ , ȣ ٿֱ
print("{0:+,}".format(100000000000))
print("{0:+,}".format(-100000000000))
# 3ڸ ֱ, ȣ ̰, ڸ Ȯϱ
# ڸ ^ äֱ
print("{0:^<+30,}".format(100000000000))
# Ҽ
print("{0:f}".format(5/3))
# Ҽ Ư ڸ ǥ (Ҽ 3° ڸ ݿø)
print("{0:.2f}".format(5/3))
##
# Է()
#score_file = open("score.txt", "w", encoding="utf8")
#print(" : 0", file=score_file)
#print(" : 0", file=score_file)
#score_file.close()
# ϴ
#score_file = open("score.txt", "a", encoding="utf8")
#score_file.write(" : 80\n") # ٹٲ ־
#score_file.close()
# (б)
#score_file = open("score.txt", "r", encoding="utf8")
#print(score_file.read())
#score_file.close()
# ٺ б, а Ŀ ٷ ̵
#score_file = open("score.txt", "r", encoding="utf8")
#print(score_file.readline())
#score_file.close()
# ̸
#score_file = open("score.txt", "r", encoding="utf8")
#while True:
# line = score_file.readline()
# if not line:
# break
# print(line)
# score_file.close()
# Ʈ ־ ó
#score_file = open("score.txt", "r", encoding="utf8")
#lines = score_file.readlines() # list ·
#for line in lines:
# print(line, end="")
# score_file.close()
## pickle
# α ϴ · ϴ
#import pickle
#profile_file = open("profile.pickle", "wb", encoding="utf-8")
#profile = {"̸":"ڸ", "":30, "":["౸","","ڵ"]}
#print(profile)
#pickle.dump(profile, profile_file) # profile ִ file
#profile_file.close()
#profile_file = open("profile.pickle", "rb")
#profile = pickle.load(profile_file) # file ִ profile ҷ
#print(profile)
#profile_file.close()
## with
#import pickle
#with open("profile.pickle", "rb") as profile_files:
# print(pickle.load(profile_file))
#with open("study.txt", "w", encoding="utf8") as study_file:
# study_file.write("̽ ")
#with open("study.txt", "r", encoding="utf8") as study_file:
# print(study_file.read())
### Ŭ
class Unit:
def __init__(self, name, hp, damage):
self.name = name
self.hp = hp
self.damage = damage
print("{0} Ǿϴ.".format(self.name))
print("ü {0}, ݷ {1}".format(self.hp, self.damage))
marine1 = Unit("", 40, 5)
marine2 = Unit("", 40, 5)
tank = Unit("ũ", 30, 5)
## __init__
# ̽㿡 Ǵ
# ü ڵ
# ü __init__ Լ ǵ ϰ Ǹ ־
# marine3 = Unit("") #
##
wraith1 = Unit("̽", 80, 5)
print(" ̸ : {0}, ݷ : {1}".format(wraith1.name, wraith1.damage))
# ܺο ü ߰ ϴ ͵
wraith2 = Unit("̽", 80, 5)
wraith2.clocking = True
## ҵ
# ⺻ ۼ Լ
# ҵ ù ° Ű ݵ self ؾ
##
# ǹ
# Unit Ŭ ִ
class AttackUnit(Unit):
def __init__(self, name, hp, damage):
Unit.__init__(self, name, hp)
self.clocking = clocking
##
# ǹ
class Flyable:
def __init__(self, flying_speed):
self.flying_speed = flying_speed
# ̿
# class FlyableAttackUnit(AttackUnit, Flyable):
## ҵ ̵
# ĻŬ Ŭ ҵ带
### ó |
b5ad41bfc82ba6fab780f5a7df6705e5413e4922 | yhgao96/Pytorch_SourceCode | /LinearRegression.py | 3,134 | 3.609375 | 4 | #pytorch
import torch
import torch.nn as nn
import numpy as np
import matplotlib.pyplot as plt
import torch.nn.functional as F
#fake data
x = torch.unsqueeze(torch.linspace(-1,1,100),dim=1) #将1维数据转化为2维
y=x.pow(2)+0.2*torch.rand(x.size())
# plt.scatter(x,y)
# plt.show()
class Net(torch.nn.Module):
def __init__(self,n_feature,n_hidden,n_output):
super(Net,self).__init__()
self.hidden=nn.Linear(n_feature,n_hidden) #自己搭建的层作为这个类的一个属性(input,output)
self.predict=nn.Linear(n_hidden,n_output) #另外一层(input,output)
def forward(self,x):
x=F.relu(self.hidden(x))
x=self.predict(x)
return x
plt.ion()
plt.show()
net=Net(1,10,1) #n_feature,n_hidden,n_output
print(net) #打印出网络结构
optimizer=torch.optim.SGD(net.parameters(),lr=0.2) #优化器(传入神经网络中的参数 学习率lr)
loss_func=nn.MSELoss() #损失函数(均方误差)
for t in range(500):
prediction=net(x)
loss=loss_func(prediction,y)
optimizer.zero_grad() #把神经网络中的梯度设为0
loss.backward()
optimizer.step()
if t%5==0:
print('Epoch [{}/{}], Loss: {:.4f}'.format(t + 1, 500, loss.item()))
plt.cla()
plt.scatter(x.numpy(),y.numpy())
plt.plot(x.numpy(),prediction.detach().numpy(),'r-',lw=5)
plt.text(0.5,0,'Loss=%.4f'%loss.item(),fontdict={'size':20,'color':'red'})
plt.pause(0.1)
plt.ioff()
plt.show()
print('Done!')
'''
# Hyper-parameters
input_size = 1
output_size = 1
num_epochs = 100
learning_rate = 0.001
# Toy dataset
x_train = np.array([[3.3], [4.4], [5.5], [6.71], [6.93], [4.168],
[9.779], [6.182], [7.59], [2.167], [7.042],
[10.791], [5.313], [7.997], [3.1]], dtype=np.float32)
y_train = np.array([[1.7], [2.76], [2.09], [3.19], [1.694], [1.573],
[3.366], [2.596], [2.53], [1.221], [2.827],
[3.465], [1.65], [2.904], [1.3]], dtype=np.float32)
# Linear regression model
model = nn.Linear(input_size, output_size)
# Loss and optimizer
criterion = nn.MSELoss()
optimizer = torch.optim.SGD(model.parameters(), lr=learning_rate)
plt.ion()
plt.show()
# Train the model
for epoch in range(num_epochs):
# Convert numpy arrays to torch tensors
inputs = torch.from_numpy(x_train)
targets = torch.from_numpy(y_train)
# Forward pass
outputs = model(inputs)
loss = criterion(outputs, targets)
# Backward and optimize
optimizer.zero_grad()
loss.backward()
optimizer.step()
if (epoch + 1) % 5 == 0:
print('Epoch [{}/{}], Loss: {:.4f}'.format(epoch + 1, num_epochs, loss.item()))
# Plot the graph
plt.cla()
predicted = model(torch.from_numpy(x_train)).detach().numpy()
plt.plot(x_train, y_train, 'ro', label='Original data')
plt.plot(x_train, predicted, label='Fitted line')
plt.text(8,2, 'Loss=%.4f' % loss.item(), fontdict={'size': 15, 'color': 'red'})
plt.pause(0.1)
plt.ioff()
plt.show()
''' |
c3af5c2691f075c1e54288422256b2ce4be76c13 | emailechiu/emailechiu.github.io | /lesson_turtle1/gridbg.py | 1,839 | 3.546875 | 4 | from turtle import *
from math import *
from canvasvg import *
def jump(x,y):
pu()
goto(x,y)
pd()
def line(x1,y1,x2,y2):
pu()
goto(x1,y1)
pd()
goto(x2,y2)
pu()
def horizontal_line(y,width):
line(-width,y,width,y)
def vertical_line(x,height):
line(x,-height,x,height)
def grid(width,height):
for x in range(-width,width+1,10):
vertical_line(x,height)
for y in range(-height,height+1,10):
horizontal_line(y,width)
def xaxis(width):
jump(-width,0)
shapesize(0.2,1)
for x in range(-width,width+1,100):
goto(x,0)
write(x,align='center')
stamp()
def yaxis(height):
jump(0,-height)
shapesize(1,0.2)
for y in range(-height,height+1,100):
goto(0,y)
write(y,align='center')
stamp()
def polar(radius):
inner_radius=radius-100
angle=30
jump(radius,0)
seth(0)
shape('arrow')
color(0.5,0.5,1)
tilt(90)
t=clone()
t.color(1,0.5,0.5)
t.pu()
t.goto(inner_radius,0)
t.pd()
for i in range(0,360,30):
stamp()
write(abs(180-towards(0,0)),align='center')
circle(radius,angle)
t.stamp()
t.write(i,align='center')
t.circle(inner_radius,angle)
def cartesian():
mode('logo')
width=400
height=400
print(screensize())
setup(width=2*width+50,height=2*height+50)
screensize(100,100) #meaningful only when greater than setup size, scrolls
print(screensize())
#setup(0.99,0.75) #unrelated to screensize, but related to actual screen
color('grey')
tracer(0)
grid(width,height)
pensize(2)
shape('square')
#color('black')
yaxis(height)
xaxis(width)
polar(min(width,height))
update()
saveall('grid.svg',Screen()._canvas)
tracer(1)
cartesian()
|
b576800600c567a049dcb02bb6365ccc76288500 | nazarov-yuriy/contests | /yrrgpbqr/p0023/__init__.py | 2,627 | 3.859375 | 4 | import unittest
from typing import List
import heapq
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
def __lt__(self, other):
return self.val < other.val
class Solution:
def mergeKLists(self, lists: List[ListNode]) -> ListNode:
head = ListNode()
tail = head
heap = [(node.val, uniq_id, node) for uniq_id, node in enumerate(lists) if node is not None]
uniq_id = len(lists)
heapq.heapify(heap)
while len(heap) > 0:
_, _, node = heapq.heappop(heap)
if node.next is not None:
heapq.heappush(heap, (node.next.val, uniq_id, node.next))
uniq_id += 1
tail.next, tail = node, node
return head.next
def compactMergeKLists(self, lists: List[ListNode]) -> ListNode:
head = ListNode()
tail = head
heap = [node for node in lists if node is not None]
heapq.heapify(heap)
while len(heap) > 0:
node = heapq.heappop(heap)
if node.next is not None:
heapq.heappush(heap, node.next)
tail.next, tail = node, node
return head.next
class Test(unittest.TestCase):
def test(self):
lists = [
ListNode(1, ListNode(4, ListNode(5))),
ListNode(1, ListNode(3, ListNode(4))),
ListNode(2, ListNode(6)),
]
merged = Solution().mergeKLists(lists)
self.assertEqual(merged.val, 1)
self.assertEqual(merged.next.val, 1)
self.assertEqual(merged.next.next.val, 2)
self.assertEqual(merged.next.next.next.val, 3)
self.assertEqual(merged.next.next.next.next.val, 4)
self.assertEqual(merged.next.next.next.next.next.val, 4)
self.assertEqual(merged.next.next.next.next.next.next.val, 5)
self.assertEqual(merged.next.next.next.next.next.next.next.val, 6)
lists = [
ListNode(1, ListNode(4, ListNode(5))),
ListNode(1, ListNode(3, ListNode(4))),
ListNode(2, ListNode(6)),
]
merged = Solution().compactMergeKLists(lists)
self.assertEqual(merged.val, 1)
self.assertEqual(merged.next.val, 1)
self.assertEqual(merged.next.next.val, 2)
self.assertEqual(merged.next.next.next.val, 3)
self.assertEqual(merged.next.next.next.next.val, 4)
self.assertEqual(merged.next.next.next.next.next.val, 4)
self.assertEqual(merged.next.next.next.next.next.next.val, 5)
self.assertEqual(merged.next.next.next.next.next.next.next.val, 6)
|
0e17599aceeca2dbc51cbce8e49f652d95a670af | vasyanch/edu | /first_my_proframm/MY_TIMER/eight_ex_prime.py | 1,143 | 4.40625 | 4 | '''
Функции, которые определяют является ли целое положительное
число простым.
'''
def prime(y):
if not y > 1:
print(y, 'not prime')
elif y != int(y):
print(y, 'not prime')
else:
x = y // 2
while 1 < x:
if y % x == 0:
print(y, 'has factor', x)
break
x -=1
#else:
#print(y, 'is prime!')
return 'Good day!'
'''print('Run the prime:')
prime(13)
prime(14.00)
prime(45.78)
prime(-77)
prime(-88)
prime(0)
print('')'''
def prime_2(y):
if not y > 1:
print(y, 'not prime')
elif y != int(y):
print(y, 'not prime')
else:
x = y // 2
for i in range(x, 1, -1):
if y % i == 0:
print(y, 'has factor', i)
break
#else:
#print(y, 'is prime!')
return 'Good day!'
'''
print('Run the prime_2:')
prime_2(13)
prime_2(14)
prime_2(-77)
prime_2(-88)
prime_2(0)
prime_2(13.67)
prime_2(2.5)
'''
|
ba792c0a92f602db95c45856b811fa91e43e5864 | shivanikarnwal/Python-Programming-Essentials-Rice-University | /week1/numbers-in-python.py | 943 | 4.15625 | 4 | """
Demonstration of numbers in Python
"""
# Python has an integer type called int
print("int")
print("---")
print(0)
print(1)
print(-3)
print(70383028364830)
print("")
# Python has a real number type called float
print("float")
print("-----")
print(0.0)
print(7.35)
print(-43.2)
print("")
# Limited precision
print("Precision")
print("---------")
print(4.56372883832331773)
print(1.23456789012345678)
print("")
# Scientific/exponential notation
print("Scientific notation")
print("-------------------")
print(5e32)
print(999999999999999999999999999999999999999.9)
print("")
# Infinity
print("Infinity")
print("--------")
print(1e500)
print(-1e500)
print("")
# Conversions
print("Conversions between numeric types")
print("---------------------------------")
print(float(3))
print(float(99999999999999999999999999999999999999))
print(int(3.0))
print(int(3.7))
print(int(-3.7))
|
f9ff961e377d66913a93e6ee76e2c3cc216d72f8 | aenglander/command-line-parsing-in-python | /examples/click.py | 724 | 3.828125 | 4 | import click
@click.group()
def main():
"""This is an "click" example CLI argument parsing."""
pass
@main.command()
@click.option("--times", default=1, type=click.IntRange(1, 5), help="Number of greetings: 1-5")
@click.argument("name")
def hello(name, times):
"""This says hello a particular number of times using the provided name argument."""
for _ in range(times):
click.echo("Hello, {}!".format(name))
@main.command()
@click.argument("name", default="Cruel World")
def goodbye(name):
"""This says goodbye using the optional name argument."""
utterance = "Goodbye, {}!".format(name)
if name == "Cruel World":
utterance = click.style(utterance, fg="red")
click.echo(utterance)
|
d1ff27255efc83fa8f9164bf9b2cc8fc899ecf7d | stroud109/challenges | /lowest_unique/lowest_unique.py | 4,352 | 4.34375 | 4 | """
1. Find the smallest element in an array of unique numbers
2. Find nth smallest element
3. Find smallest element in a nested list (recursion!)
4. Find lowest int that's /not/ in the random, unique array, e.g. 'find next available server'
Include tests
Determine the run time
"""
import random
import datetime
# import numpy
# Generate array of unique ints
# Option 1:
def generate_unique_array(len_array):
return random.sample(xrange(1, (len_array * 3)), len_array)
# unique_array = generate_unique_array(10)
# print "unique array: ", unique_array
# Option 2:
# def numpy_generate_unique_array(len_array):
# return numpy.random.choice(len_array * 3, len_array)
# unique_array = numpy_generate_unique_array(1000)
def find_min(unique_array):
start = datetime.datetime.utcnow()
min_num = unique_array[0]
for i in xrange(len(unique_array)):
if min_num > unique_array[i]:
min_num = unique_array[i]
end = datetime.datetime.utcnow()
delta = end - start
print "find_min time: ", delta.total_seconds() * 1000
print "find_min result: ", min_num
return min_num
# min_num = find_min(unique_array)
# print "result: ", min_num
def _merge_sort(unique_array):
if len(unique_array) > 1:
mid = len(unique_array) / 2
lefthalf = unique_array[:mid]
righthalf = unique_array[mid:]
_merge_sort(lefthalf)
_merge_sort(righthalf)
i = 0 # leftshark
j = 0 # rightshark
k = 0 # the ultimate source of ordered truth
while i < len(lefthalf) and j < len(righthalf):
if lefthalf[i] < righthalf[j]:
unique_array[k] = lefthalf[i]
i = i + 1
else:
unique_array[k] = righthalf[j]
j = j + 1
k = k + 1
# start with the left half, because we started by moving smaller numbers to the left
while i < len(lefthalf):
unique_array[k] = lefthalf[i]
i = i + 1
k = k + 1
while j < len(righthalf):
unique_array[k] = righthalf[j]
j = j + 1
k = k + 1
return unique_array
def merge_sort_helper(unique_array):
start = datetime.datetime.utcnow()
sorted_array = _merge_sort(unique_array)
end = datetime.datetime.utcnow()
delta = end - start
print "merge sort time: ", delta.total_seconds() * 1000
return sorted_array[0]
# min_num2 = merge_sort_helper(unique_array)
# print "merge sort time: ", min_num2
def find_nth_lowest(nth_lowest, unique_array):
start = datetime.datetime.utcnow()
sorted_array = _merge_sort(unique_array)
end = datetime.datetime.utcnow()
delta = end - start
print "nth lowest time: ", delta.total_seconds() * 1000
try:
return sorted_array[nth_lowest]
except:
return "list is too short"
def find_nested_min(unique_nested_array):
start = datetime.datetime.utcnow()
# un-nest the array
def _reducer(accumulater, curr):
if isinstance(curr, list):
reduce(_reducer, curr, accumulater)
else:
accumulater.append(curr)
return accumulater
formatted_list = reduce(_reducer, unique_nested_array, [])
end = datetime.datetime.utcnow()
delta = end - start
print "find nested min time: ", delta.total_seconds() * 1000
# then find min
return find_min(formatted_list)
# min_nested = find_nested_min([29, [26, [17, 9]], [[14, 16], [19, 25, 6, 4]]])
# print "min_nested: ", min_nested
def find_next_available_server(some_array):
# if the list is empty, all servers are available, so let's use the first one!
if len(some_array) < 1:
return 1
# sort
sorted_array = sorted(some_array) # [1, 3, 5]
for i in xrange(sorted_array[-1]):
if i + 1 != sorted_array[i]:
return i + 1
assert find_next_available_server([5, 3, 1]) == 2
def find_next_avail_server(some_array):
my_set = set(some_array)
if len(my_set) < 1:
return 1
# no need to sort a set
# let's not iterate to the last int
# better to use length of set, in this case 3
# set(1, 2, 100)
for x in xrange(len(my_set)):
if x + 1 not in my_set:
return x + 1
assert find_next_avail_server([100, 2, 1, 1]) == 3
|
865a35e5a487247883ca4a038b16d27870da4d32 | YukiHaix86/TheCryptor | /main.py | 1,770 | 3.796875 | 4 | import os, cryptography
from cryptography.fernet import Fernet
import encryp
import key
import sys,time,random
import yukiutils
#key.write_key()
key = key.load_key()
#check if key exists
print("Checking if Key exists...")
#if key.check_key() == True:
# print("Key found and checked!")
#else:
# print("Attention Key might be broken! You should delete your .key file or select generate new key in the Menu!")
#
str_array = ["Encrypt Message","Decrypt Message","Encrypt File","Decrypt File","Check Key","Generate new Keys","Exit"]
print("What do you want to do?")
i = 0
for x in str_array:
i += 1
txt = "{counter1}.| {str_array_output}".format(counter1 = i, str_array_output = x)
print(txt)
#change to yukiutils
print("You can now choose what you wanna do! (Only numbers from 1-7 accepted!)")
print("")
selectioner = False
while selectioner == False:
auswahl = input()
if auswahl.isdigit() == True:
auswahl = int(auswahl)
if 1<= auswahl <= 6:
txt2 = "You selected {auswahl1}.| ".format(auswahl1 = auswahl)
print(txt2 + str_array[auswahl-1])
selectioner = True
elif auswahl == 7:
print("Goodbye")
break
else:
print("You can only use the numbers 1-7!")
else:
print("You can only use the numbers 1-7!")
#Dictionary for Selection
auswahl -= 1
if auswahl == 0:
msg = input("Write your message to encrypt\n").encode()
newmessage = encryp.encryptmessage(msg, key)
print(newmessage)
elif auswahl == 1:
msg = input("Write message to decrypt\n").encode()
newmessage = encryp.decryptmessage(msg, key)
print(newmessage)
else:
print("Something went wrong") |
0dfd75ae60e07a0a6da821da6846ba38096191c4 | lkmflam/07-Network-Programming | /09_NetworkingExtended/SocketProgramming/Socket Challenge Lab #2 Server.py | 1,249 | 3.921875 | 4 | # Echo server program
import socket
HOST = '' # Symbolic name meaning all available interfaces. It will acept whoever is wanting to connect.
PORT = 50007 # Arbitrary non-privileged port
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s: #Instantiates the socket and sets to "s" for use later
s.bind((HOST, PORT)) #Binds the host and port together. Basically makes this the address of the client
s.listen(1) #Means that the server is only listening to one client. Can be multiple though.
conn, addr = s.accept() #Sets the accepted socket connection to two variables for use later.
with conn:
print('Connected by', addr) #Prints who connected with. Like the address.
while True: #States that while receiving information (data), it will store in data.
data = conn.recv(1024)
if not data: break #If no data is received from the client then it will break out of the loop
print(data) #This will print whatever was received from the client.
vowel = "a", "e", "i", "o", "u"
for vowel in data:
data.replace(vowel, "#")
print(data)
conn.sendall(data) #Will send back what it recieved. |
8cdfa40ad61ea0c313c47c059255ba076b98d1c9 | wljSky/order-receiving-project | /人物拼接/pingjie.py | 2,357 | 3.578125 | 4 | import random
import pygame
# 初始化
pygame.init()
# 窗口标题
pygame.display.set_caption('一个简单的拼图游戏')
# 窗口大小
s = pygame.display.set_mode((1200, 600))
# 绘图地图
imgMap = [
[0, 1, 2],
[3, 4, 5],
[6, 7, 8]
]
# 判断胜利的地图
winMap = [
[0, 1, 2],
[3, 4, 5],
[6, 7, 8]
]
# 游戏的单击事件
def click(x, y, map):
if y - 1 >= 0 and map[y - 1][x] == 8:
map[y][x], map[y - 1][x] = map[y - 1][x], map[y][x]
elif y + 1 <= 2 and map[y + 1][x] == 8:
map[y][x], map[y + 1][x] = map[y + 1][x], map[y][x]
elif x - 1 >= 0 and map[y][x - 1] == 8:
map[y][x], map[y][x - 1] = map[y][x - 1], map[y][x]
elif x + 1 <= 2 and map[y][x + 1] == 8:
map[y][x], map[y][x + 1] = map[y][x + 1], map[y][x]
# 打乱地图
def randMap(map):
for i in range(1000):
x = random.randint(0, 2)
y = random.randint(0, 2)
click(x, y, map)
# 加载图片
img = pygame.image.load('3.jpg')
# 随机地图
randMap(imgMap)
# 游戏主循环
while True:
# 延时32毫秒,相当于FPS=30
pygame.time.delay(32)
for event in pygame.event.get():
# 窗口的关闭事件
if event.type == pygame.QUIT:
exit()
elif event.type == pygame.MOUSEBUTTONDOWN: # 鼠标单击事件
if pygame.mouse.get_pressed() == (1, 0, 0): # 鼠标左键按下
mx, my = pygame.mouse.get_pos() # 获得当前鼠标坐标
if mx < 498 and my < 498: # 判断鼠标是否在操作范围内
x = int(mx / 166) # 计算鼠标点到了哪个图块
y = int(my / 166)
click(x, y, imgMap) # 调用单击事件
if imgMap == winMap: # 如果当前地图情况和胜利情况相同,就print胜利
print("胜利了!")
# 背景色填充成绿色
s.fill((0, 255, 0))
# 绘图
for y in range(3):
for x in range(3):
i = imgMap[y][x]
if i == 8: # 8号图块不用绘制
continue
dx = (i % 3) * 166 # 计算绘图偏移量
dy = (int(i / 3)) * 166
s.blit(img, (x * 166, y * 166), (dx, dy, 166, 166))
# 画参考图片
s.blit(img, (500, 0))
# 刷新界面
pygame.display.flip() |
d2fc896a97cffe927a26fc2825886c15faa9ce76 | GitError/python-lib | /Learn/Udemy/generators.py | 759 | 4.53125 | 5 | """
Intro to python generators
"""
# generators allow us to generate a sequence of values over time
# the main difference in syntax is the use of yield statement
# -- return one element at the time, no need to store entire list in memory
# e.g. range() is a generator
# in memory list example
def create_cubes(n):
result = []
for x in range(n):
result.append(x ** 3)
return result
print(create_cubes(10))
# generator - way more memory efficient
def cubes(n):
for x in range(n):
yield x ** 3
print(cubes(10))
# generator objects (return of generator function) need to be iterated over
def gen_fibon(n):
a = 1
b = 1
for _ in range(n):
yield a
a, b = b, a + b
print(list(gen_fibon(10)))
|
9145fed51acac489382229cefef64ee6a88ddda8 | brunnuscz/uespi-curso-python | /Exercícios de Matriz/#02.py | 743 | 3.9375 | 4 | matriz = []
lista = []
c = 0
for i in range(3):
lista.clear()
for j in range(3):
num = int(input(f"Digite [{i+1},{j+1}]: "))
while (num in lista):
print("Erro ! O valor já existe na MATRIZ\n")
num = int(input("Digite: "))
lista.append(num)
matriz.append(lista[:])
print("\n")
for i in range(3):
for j in range(3):
print(f"[ {matriz[i][j]} ]", end = '')
if j >= 2:
print("\n")
novo = int(input("Digite o número que você quer encontrar: "))
for i in range(3):
for j in range(3):
if (novo == matriz[i][j]):
print(f"Existe !\nEstá na posição [{i+1},{j+1}]")
c+=1
if(c < 1):
print("Não Existe !") |
6f5d9b74a44861dd67e7bd36003461f87dc33b10 | CODE-Lab-IASTATE/MDO_course | /04_programming_with_scipy/gradient_free.py | 679 | 3.8125 | 4 | #Tutorials for optimization in python
#2D
#Gradient free algorithms
#Nelder-Mead simplex algorithm
#Powell algorithm
#Import libraries
from scipy import optimize
#Objective function
def f(x): # The rosenbrock function
return .5*(1 - x[0])**2 + (x[1] - x[0]**2)**2
#Run the optimizer
#Try powell algorithm as well
result = optimize.minimize(f, [2, -1], method="Nelder-Mead")
#check if the solver was successful
print(result.success)
#return the minimum
x_min = result.x
print("True minimum:",[1,1])
print("Minimum found by the optimizer:",x_min)
print("Value of the objective function at the minimum:",f([1,1]))
print("Minimum objective function value found:",f(x_min))
|
db23aa426ca05bbe5973386e07f3c86609d59cea | jyn514/Stanford-CS-231 | /assignment1/cs231n/classifiers/notes.py | 3,825 | 3.796875 | 4 | def L_i(x, y, W):
"""
unvectorized version. Compute the multiclass svm loss for a single example (x,y)
- x is a column vector representing an image (e.g. 3073 x 1 in CIFAR-10)
with an appended bias dimension in the 3073-rd position (i.e. bias trick)
- y is an integer giving index of correct class (e.g. between 0 and 9 in CIFAR-10)
- W is the weight matrix (e.g. 10 x 3073 in CIFAR-10)
"""
delta = 1.0 # see notes about delta later in this section
scores = W.dot(x) # scores becomes of size 10 x 1, the scores for each class
correct_class_score = scores[y]
D = W.shape[0] # number of classes, e.g. 10
loss_i = 0.0
for j in xrange(D): # iterate over all wrong classes
if j == y:
# skip for the true class to only loop over incorrect classes
continue
# accumulate loss for the i-th example
loss_i += max(0, scores[j] - correct_class_score + delta)
return loss_i
def L_i_vectorized(x, y, W):
"""
A faster half-vectorized implementation. half-vectorized
refers to the fact that for a single example the implementation contains
no for loops, but there is still one loop over the examples (outside this function)
"""
delta = 1.0
scores = W.dot(x)
# compute the margins for all classes in one vector operation
margins = np.maximum(0, scores - scores[y] + delta)
# on y-th position scores[y] - scores[y] canceled and gave delta. We want
# to ignore the y-th position and only consider margin on max wrong class
margins[y] = 0
loss_i = np.sum(margins)
return loss_i
def L(X, y, W):
"""
fully-vectorized implementation :
- X holds all the training examples as columns (e.g. 3073 x 50,000 in CIFAR-10)
- y is array of integers specifying correct class (e.g. 50,000-D array)
- W are weights (e.g. 10 x 3073)
"""
# evaluate loss over all examples in X without using any for loops
# left as exercise to reader in the assignment
def random_search(X, Y):
# assume X_train is the data where each column is an example (e.g. 3073 x 50,000)
# assume Y_train are the labels (e.g. 1D array of 50,000)
# assume the function L evaluates the loss function
bestloss = float("inf") # Python assigns the highest possible float value
for num in xrange(1000):
W = np.random.randn(10, 3073) * 0.0001 # generate random parameters
loss = L(X, Y, W) # get the loss over the entire training set
if loss < bestloss: # keep track of the best solution
bestloss = loss
bestW = W
return bestloss, bestW
def random_local_search(X, Y):
W = np.random.randn(10, 3073) * 0.001 # generate random starting W
bestloss = float("inf")
step_size = 0.0001
for i in xrange(1000):
Wtry = W + np.random.randn(10, 3073) * step_size
loss = L(Xtr_cols, Ytr, Wtry)
if loss < bestloss:
W = Wtry
bestloss = loss
return bestloss, W
def eval_numerical_gradient(f, x):
"""
a naive implementation of numerical gradient of f at x
- f should be a function that takes a single argument
- x is the point (numpy array) to evaluate the gradient at
derived from calculus: df/dx = lim[h->0]((f(x+h) - f(x)) / h)
"""
fx = f(x) # evaluate function value at original point
grad = np.zeros(x.shape)
h = 0.00001
# iterate over all indexes in x
it = np.nditer(x, flags=['multi_index'], op_flags=['readwrite'])
while not it.finished:
# evaluate function at x+h
ix = it.multi_index
old_value = x[ix]
x[ix] = old_value + h # increment by h
fxh = f(x) # evalute f(x + h)
x[ix] = old_value # restore to previous value (very important!)
# compute the partial derivative
grad[ix] = (fxh - fx) / h # the slope
it.iternext() # step to next dimension
return grad
def gradient_descent(f, x, W):
step_size = .0001
while True:
W -= step_size * eval_gradient(f, x)
|
2bdfef6f41c390db1779c63227f73b814386a1b8 | sarauwu/summerimmersion | /da.py | 1,273 | 3.71875 | 4 | '''
In this project, you will visualize the feelings and language used in a set of
Tweets. This starter code loads the appropriate libraries and the Twitter data you'll
need!
'''
from wordcloud import WordCloud
import json
from textblob import TextBlob
import matplotlib.pyplot as plt
#Get the JSON data
tweetFile = open("twitter.json", "r")
tweetData = json.load(tweetFile)
tweetFile.close()
# Continue your program below!
#store each tweet's polarity and subectivity in the list
#create a list called polarity and subjectivity
polarity = []
subjectivity = []
all=[]
for tweet in tweetData:
all.append(tweet["text"])
temp = TextBlob(tweet["text"])
polarity.append(temp.sentiment.polarity)
subjectivity.append(temp.sentiment.subjectivity)
print(polarity)
print(subjectivity)
print(" Polarity Average:", sum(polarity)/len(polarity))
print(" Subjectivity Average:", sum(subjectivity)/len(subjectivity))
print("".join(all))
#Set a clean upper y-axis limit
plt.hist(polarity, 5)
plt.title('Polarity')
plt.xlabel('the polarity')
plt.ylabel('the # of tweets')
plt.show()
plt.hist(subjectivity, 5)
plt.xlabel('the Subjectivity')
plt.ylabel('the # of tweeets')
plt.title('Subjectivity')
plt.show()
""
|
50ec5e9bb1f12198613e7dd78b07f40f4bf5ec7d | MikSavenka/python_home_tasks | /1_1.py | 221 | 3.75 | 4 | # Get input arguments (sys.argv) and print them and their sum
import sys
s = sum(int(i) for i in sys.argv[1:])
args = ''
for arg in sys.argv[1:]:
args += arg + ", "
print("Got {0}. Sum is {1}.".format(args[:-2], s))
|
4a74c4daefbfad8cfeb973d8cb284e7e82e58356 | Adpeen/Some-Random-Stuff-I-created | /Joke App.py | 1,379 | 3.90625 | 4 | from tkinter import *
import random
joke = ""
def Joke():
global joke
jokes = list(my_jokes.keys())
joke = random.choice(jokes)
entry.delete(0.0, END)
output.delete(0.0, END)
entry.insert(END, joke)
def Answer():
output.delete(0.0, END)
try:
answer = my_jokes[joke]
except:
answer = "There is no entry for this question."
output.insert(END, answer)
window = Tk()
window.title("Hello World!")
Button(window, text="Get Joke", width=15, command=Joke).grid(row=3, column=0, sticky=W)
Button(window, text="Get Answer", width=15, command=Joke).grid(row=3, column=0, sticky=E)
entry = Text(window, width=50, height=2, wrap=WORD, background="green")
entry.grid(row=1, column=0, sticky=W)
output = Text(width=50, height=6, wrap=WORD, background="green")
output.grid(row=1, column=0, columnspan=2, sticky=W)
my_jokes = {
"I told my wife she was drawing her eyebrows too high." : "She looked surprised.",
"I tried to catch fog yesterday." : "Mist.",
"And the Lord said unto John: ‘Come forth and you will receive eternal life’." : "But John came fifth, and won a toaster.",
"I went to a really emotional wedding the other day." : "Even the cake was in tiers.",
"Someone stole my mood ring." : "I don’t know how I feel about that."
}
window.mainloop()
|
fcb14f19f6b43e58dd14f0985c5c53493f37f299 | froycard/ProjectEuler-33 | /solution.py | 613 | 3.546875 | 4 | from fractions import Fraction
from itertools import permutations
def one_dig_div(x,y):
if x[0]==y[0]: a=x[1]
else: a=x[0]
if x[1]==y[1]: b=y[0]
else: b=y[1]
return a/b
ans=Fraction(1,1)
perm = permutations(range(1,10), 2)
perm=list(perm)
for num in perm:
for den in perm:
if num == den: continue
if den[0] in num or den[1] in num:
if (num[0]*10+num[1])/(den[0]*10+den[1]) == one_dig_div(num,den):
print(num[0]*10+num[1],"/", den[0]*10+den[1])
ans*=Fraction(num[0]*10+num[1],den[0]*10+den[1])
print("Sol.: ", ans.denominator)
|
0ad6b04ad246ede1317c2da178c27a8b62ae1893 | mjoze/kurs_python | /codewars/recursive_reverse_string.py | 909 | 4.25 | 4 | """
##Do you know how to write a recursive function? Let's test it!
* Definition: Recursive function is a function that calls itself during its execution *
Classic factorial counting on Javascript
function factorial(n) {
return n <= 1 ? 1 : n * factorial(n-1)
}
Your objective is to complete a recursive function reverse() that receives str as
String and returns the same string in reverse order
Rules:
reverse function should be executed exactly N times. N = length of the input string
helper functions are not allowed
changing the signature of the function is not allowed
Examples:
reverse("hello world") = "dlrow olleh" (N = 11)
reverse("abcd") = "dcba" (N = 4)
reverse("12345") = "54321" (N = 5)
All tests for this Kata are randomly generated, besides checking the reverse logic they will
count how many times the reverse() function has been executed.
"""
def reverse(str):
return str[::-1]
|
3bba34e12c30c167f3ad5b7632a3968769ca9882 | WazedKhan/Tic_Tac_Toe-Game | /TicTacToe.py | 1,878 | 3.765625 | 4 | board = {'Top-L': ' ', 'Top-M': ' ', 'Top-R': ' ',
'Mid-L': ' ', 'Mid-M': ' ', 'Mid-R': ' ',
'Low-L': ' ', 'Low-M': ' ', 'Low-R': ' '}
def winner(board):
# Colunm
if board['Mid-R'] == board['Top-R'] == board['Low-R'] != ' ':
return 'win'
elif board['Mid-M'] == board['Top-M'] == board['Low-M'] != ' ':
return 'win'
elif board['Mid-L'] == board['Top-L'] == board['Low-L'] != ' ':
return 'win'
# Row
elif board['Top-L'] == board['Top-M'] == board['Top-R'] != ' ':
return 'win'
elif board['Mid-L'] == board['Mid-M'] == board['Mid-R'] != ' ':
return 'win'
elif board['Low-L'] == board['Low-M'] == board['Low-R'] != ' ':
return 'win'
#Cros
elif board['Top-L'] == board['Mid-M'] == board['Low-R'] != ' ':
return 'win'
elif board['Top-R'] == board['Mid-M'] == board['Low-L'] != ' ':
return 'win'
def print_Theboard(board):
print(board['Top-L'] + '|' + board['Top-M'] + '|' + board['Top-R'] )
print('-+-+-')
print(board['Mid-L'] + '|' + board['Mid-M'] + '|' + board['Mid-R'] )
print('-+-+-')
print(board['Low-L'] + '|' + board['Low-M'] + '|' + board['Low-R'] )
turn = 'X'
time_to_run = len(board)
while time_to_run != 0:
print_Theboard(board)
move = input(f'Enter Place no for {turn} :')
if board.get(move) != ' ':
time_to_run += 1
print(f'This place taken by {board.get(move)}, Plz choose another place! ')
else:
board[move] = turn
if turn == 'X':
turn = 'O'
else:
turn = 'X'
result = winner(board)
if result == 'win':
print('We have winner!')
break
time_to_run -= 1
print(f'It is the {time_to_run-1} turn: ')
print_Theboard(board) |
878e8722a01be94ed9b4fb7e9d5f760660d78355 | sgouda0412/Coding-Questions | /algoexpert/easy/remove_duplicates_from_linked_list.py | 461 | 3.75 | 4 | # This is an input class. Do not edit.
class LinkedList:
def __init__(self, value):
self.value = value
self.next = None
def removeDuplicatesFromLinkedList(linkedList):
currentNode = linkedList
while currentNode is not None:
checkNode = currentNode.next
while checkNode is not None and checkNode.value == currentNode.value:
checkNode = checkNode.next
currentNode.next = checkNode
currentNode = checkNode
return linkedList
|
1e512beedfd930b088265c5187aaa9216f3352c3 | CodingDojoDallas/python_oct_2017 | /Daryll_Dade/Python_Fundamentals/15List to Dict/List_to_Dict.py | 881 | 3.765625 | 4 | name = ["Anna", "Eli", "Pariece", "Brendan", "Amy", "Shane", "Oscar"]
favorite_animal = ["horse", "cat", "spider", "giraffe", "ticks", "dolphins", "llamas"]
"""def make_dict(arr1, arr2):
new_dict = {}
compare = [len(arr1),len(arr2)]
if (max(compare) == compare[0]):
keyslist = arr1
else:
keylist = arr2
if (min(compare) == compare[1]):
valueslist = arr1
else:
valueslist = arr2
for x in range (0,len(keyslist)):
new_dict += keyslist[x]:valueslist[x]
return new_dict"""
def make_dict(arr1, arr2):
newdict = {}
if len(arr1) >= len(arr2):
newdict = dict.fromkeys(arr1,arr2)
if len(arr2) < len(arr1):
newdict = dict.fromkeys(arr2,arr1)
print newdict
i = 0
for c in newdict:
newdict[c] = arr2[i]
i += 1
print newdict
make_dict(name, favorite_animal)
|
e0e14f6b9abd89f0ef7549cc6902fce98182d9cd | lhwd521/python | /calc.py | 2,632 | 3.640625 | 4 | #coding=utf-8
import random
pom = ">"
def start():
print u"""--------------------------------------------
开始计算游戏吧!
--------------------------------------------
"""
def newuser():
name = raw_input("请输入您的姓名:".decode('utf-8').encode('gbk') + pom)
return name
def random_new(num):
x = random.randint(0, num)
y = random.randint(1, num)
return x, y
def add(num1, num2):
num3 = num1 + num2
return num3
def minus(num1, num2):
num3 = num1 - num2
return num3
def multiply(num1, num2):
num3 = num1 * num2
return num3
def division(num1, num2):
num3 = num1 / num2
return num3
start()
name = newuser()
print "\n\n\t\t欢迎%s!\n\n".decode('utf-8').encode('gbk') % name
print u"计算类型: 1、加法\n\t 2、减法\n\t 3、乘法\n\t 4、除法(舍余)\n"
calctype = raw_input("请选择计算类型".decode('utf-8').encode('gbk') + pom)
while not calctype.isdigit():
calctype = raw_input("请选择计算类型".decode('utf-8').encode('gbk') + pom)
else:
calctype = int(calctype)
if(calctype == 1):
calctype = "+"
elif(calctype == 2):
calctype = "-"
elif(calctype == 3):
calctype = "*"
elif(calctype == 4):
calctype = "/"
else:
print u"输入错误,退出程序。"
exit()
print u"\n难度: 1、初级\n 2、中级\n 3、高级"
level = raw_input("\n请选择难度".decode('utf-8').encode('gbk') + pom)
while not level.isdigit():
level = raw_input("请选择难度".decode('utf-8').encode('gbk') + pom)
else:
level = int(level)
if(level == 1):
level = 10
elif(level == 2):
level = 100
elif(level == 3):
level = 1000
else:
print u"输入错误,退出程序。"
exit()
count = right = worng = 0
time = raw_input("\n请输入计算次数".decode('utf-8').encode('gbk') + pom)
while not time.isdigit():
time = raw_input("请输入计算次数".decode('utf-8').encode('gbk') + pom)
else:
time = int(time)
while count < time:
x, y = random_new(level)
print "\n%d %s %d = ?" % (x, calctype, y)
num_input = raw_input("请输入答案".decode('utf-8').encode('gbk') + pom)
try:
num_input = int(num_input)
except:
pass
if(calctype == "+"):
num_sum = add(x, y)
elif(calctype == "-"):
num_sum = minus(x, y)
elif(calctype == "*"):
num_sum = multiply(x, y)
else:
num_sum = division(x, y)
if(num_input == num_sum):
print u"正确"
right = right + 1
else:
print u"错误 %d %s %d = %d" % (x, calctype, y, num_sum)
worng = worng + 1
count = count + 1
else:
print u"\n结束"
print "姓名:%s 共完成%d题,正确%d题,错误%d题。".decode('utf-8').encode('gbk') % (name, time, right, worng)
end = raw_input() |
a79289a65b7f23290ca85640436eee09748ec418 | JasonOnes/PythonWork | /fibo.py | 1,116 | 4.25 | 4 | """
Write a function that outputs a list of fibbonacci numbers.
Input is how many numbers to calculate.
>>> fibo(10)
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34]
>>> fibo(20)
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34]d
>>> fibo(30)
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34]
Write a Generator function named 'fib_infinite()' to calculate fibbonacci numbers to infinity.
>>> fibo_iterator = fib_infinite()
>>> next(fib_infinite)
0
>>> next(fib_infinite)
1
>>> next(fib_infinite)
1
>>> next(fib_infinite)
2
>>> next(fib_infinite)
3
>>> next(fib_infinite)
5
>>> next(fib_infinite)
8
>>> next(fib_infinite)
13
"""
def fibo(x):
f = list([0])
num = 0
num_b = 1
# f = [(num[n] + num[n+1]) for num in m ]
while num < x:
num, num_b = num_b, num + num_b
#num_b = num + num_b
print(num)
f.append(num)
print(f)
#print(f[-1])
#fibo(7)
def largest_fibo(x):
#fibo(x)
print(fibo[x][-1])
largest_fibo(7)
class Fibo(object):
def __init__(self):
self = self
#self.num = self + num
def next(self):
new_self = fibo(self)
print(new_self)
|
bcd3d0643493588c032eb4bf9e60e6dbb40c0f35 | RamgopalBhadu/Python-with-DS-and-Algo | /Linked list/k_reverse.py | 1,202 | 3.59375 | 4 | #!/usr/bin/env python
# coding: utf-8
# In[ ]:
class Node:
def __init__(self, data):
self.data = data
self.next = None
def kReverse(head, k) :
prev = None
curr = head
temp = None
tail = None
newHead = None
join = None
t = 0
while (curr) :
t = k
join = curr
prev = None
while (curr and t > 0):
temp = curr.next
curr.next = prev
prev = curr
curr = temp
t = t - 1
if (newHead == None):
newHead = prev
if (tail != None):
tail.next = prev
tail = join
return newHead
pass
def ll(arr):
if len(arr)==0:
return None
head = Node(arr[0])
last = head
for data in arr[1:]:
last.next = Node(data)
last = last.next
return head
def printll(head):
while head:
print(head.data, end=' ')
head = head.next
print()
# Main
# Read the link list elements including -1
arr=list(int(i) for i in input().strip().split(' '))
# Create a Linked list after removing -1 from list
l = ll(arr[:-1])
i=int(input())
l = kReverse(l, i)
printll(l)
|
f138a6ee857b585d8e8d04ec7b94016d855127e4 | assem-ch/owtf | /tests/testing_framework/doubles/files.py | 893 | 3.578125 | 4 |
class FileMock():
"""
This class simulates a file object, in order to be sure about the content
of the file, and speed up the execution of tests, avoiding the access to
the filesystem.
"""
def __init__(self, lines):
self.lines = lines
self.max = len(lines) - 1
self.iterator_counter = 0
def __iter__(self):
# A file object has to be iterable
return self
def next(self):
# Iterable implementation
if self.iterator_counter > self.max:
self.iterator_counter = 0
raise StopIteration
else:
line = self.lines[self.iterator_counter]
self.iterator_counter += 1
return line
def __next__(self): # For python 3.x compatibility
self.next()
def read(self):
return "".join(self.lines)
def close(self):
pass |
2ea56b21d236cd5a85f17faf0055e5568b95a4a4 | Ahtaylor/Rider-Clustering | /clustfunc.py | 10,199 | 3.765625 | 4 | #!/usr/bin/env python3
# adjaceancy.py
# Functions to cluster people together based on distance.
import numpy as np
import numpy.ma as ma
def adjaceancy(riderlist):
adj = np.empty((len(riderlist), len(riderlist)))
for r1 in range(len(riderlist)):
for r2 in range(r1 + 1):
adj[r1,r2] = str(np.sqrt((riderlist[r1].get('x') - riderlist[r2].get('x'))**2 + ((riderlist[r1].get('y') - riderlist[r2].get('y'))**2)))
adj[r2,r1] = adj[r1,r2]
if r1 == r2:
adj[r1,r2] = np.nan
print(adj)
return adj
def cluster(adj,riderlist):
# initialize variables that will store cluster and keep track of clustering status
num_rid = len(adj[0])
num_ungrp = num_rid
clus_size = 3
clusters = []
clus_ind = []
clustered = False
# Makes adj into a masked array so that elements can be masked and hidden for argmin search
adj = ma.masked_array(adj)
maskarr = ma.getmaskarray(adj)
# intializes with each person in their own cluster, clus_ind follows the mutations of the
# adjaceancy matrix
for i in range(num_rid):
clus_ind.append([i])
# Additional variables that are used in the else case of the semiclustered conditional
adjprime = np.copy(adj)
indprime = clus_ind.copy()
# Loop runs until all riders are in a cluster, ideally of more than 1 person
while not clustered:
semiclustered = maskarr.all()
# By default nan are masked and any two clusters who sum of elements is greater than
# 3 is masked. When all elements become masked then maskarr.all() returns true and
# then we move onto the else section of the loop.
if not semiclustered:
# finds the shortest distance, stores the coordinates, and constructs values for
# what rows and columns to removed later
short = np.nanargmin(adj)
row = int(short//num_ungrp)
column = int(short%num_ungrp)
first = np.maximum(row,column)
second = np.minimum(row,column)
# Grouping indices in temp that correspond to specific riders, converts to names at
# the end
temp =[]
for i in clus_ind[row]:
temp.append(i)
for i in clus_ind[column]:
temp.append(i)
# Removes lists that have been combined
clus_ind.pop(first)
clus_ind.pop(second)
# creates array of values representing distance between new cluster and old clusters
# Additionally, maskcomb is used to keep track of what values of combined should be
# masked.
combined = []
maskcomb = []
adj.mask = ma.nomask
for i in range(num_ungrp):
combined.append(np.maximum(adj[row][i],adj[column][i]))
maskcomb.append(maskarr[row][i] or maskarr[column][i])
combined.pop(first)
combined.pop(second)
maskcomb.pop(first)
maskcomb.pop(second)
combined = np.asarray(combined)
maskcomb = np.asarray(maskcomb)
# Deletes the old rows and columns of the recently combined clusters
adj = np.delete(adj,first, axis=0)
adj = np.delete(adj,first, axis=1)
adj = np.delete(adj,second, axis=0)
adj = np.delete(adj,second, axis=1)
maskarr = np.delete(maskarr,first,axis=0)
maskarr = np.delete(maskarr,first,axis=1)
maskarr = np.delete(maskarr,second,axis=0)
maskarr = np.delete(maskarr,second,axis=1)
# If comdition is met then the cluster isn't full and it is put back into clus_ind
# and adj. If it isn't met then temp is added to the cluster list and adjprime and
# indprime are altered to account for those elements not being valid options if
# the semiclustered branch is entered.
if len(temp) < clus_size:
clus_ind.insert(0,temp)
adj = np.insert(adj, 0, combined,axis=0)
maskarr = np.insert(maskarr, 0, maskcomb, axis=0)
combined = np.insert(combined,0, np.nan,axis=0)
maskcomb = np.insert(maskcomb,0,True,axis=0)
adj = np.insert(adj, 0, combined.transpose(),axis=1)
maskarr = np.insert(maskarr, 0, maskcomb.transpose(), axis=1)
else:
clusters.append(temp)
temp.sort(reverse=True)
for i in temp:
loc = np.argwhere(np.asarray(indprime) == i)[0][0]
indprime.pop(loc)
adjprime = np.delete(adjprime,loc,axis=0)
adjprime = np.delete(adjprime,loc,axis=1)
num_ungrp -= 1
num_ungrp -= 1
if num_ungrp <= 1:
clustered = True
if len(clus_ind) != 0:
clusters.append(clus_ind[0])
# Masks any values that represent connections between clusters with total number of
# elements greater than clus_size (3)
for i in range(num_ungrp):
for j in range(num_ungrp):
if (len(clus_ind[i]) + len(clus_ind[j])) > clus_size:
maskarr[i,j] = True
maskarr[j,i] = True
adj.mask = maskarr # Mask is reapplied for searching at the beginning of the loop
else:
print('Entered semicluster step')
num_ungrp = len(indprime)
# Search for shortest distance similary to before
short = np.nanargmin(adjprime)
row = int(short//num_ungrp)
column = int(short%num_ungrp)
first = np.maximum(row,column)
second = np.minimum(row,column)
# In this section each element of indprime will be a list of length 1 so a loop is
# not necessary
temp = []
temp.append(indprime[row][0])
temp.append(indprime[column][0])
indprime.pop(first)
indprime.pop(second)
combined = []
for i in range(num_ungrp):
combined.append(np.maximum(adjprime[row][i],adjprime[column][i]))
combined.pop(first)
combined.pop(second)
combined = np.asarray(combined)
adjprime = np.delete(adjprime,first,axis=0)
adjprime = np.delete(adjprime,first,axis=1)
adjprime = np.delete(adjprime,second,axis=0)
adjprime = np.delete(adjprime,second,axis=1)
# Two are removed to accound for the two elements removed that will not be put back
num_ungrp -= 2
# Once two are clustered, a third or more depending on clus_size are clustered, so
# long as the cluster is under the limit and there are elements left to cluster
while (len(temp) < clus_size and len(indprime) > 0):
short = np.nanargmin(combined)
ele = int(short%num_ungrp)
temp.append(indprime[ele][0])
indprime.pop(ele)
combined = np.delete(combined,ele,axis=0)
adjprime = np.delete(adjprime,ele,axis=0)
adjprime = np.delete(adjprime,ele,axis=1)
clusters.append(temp)
# Edge cases where indprime either has a leftover cluster of one person, or no one.
if len(indprime) == 1:
clusters.append(indprime[0][0])
clustered = True
elif len(indprime) == 0:
clustered = True
# converts list of list of indices, into list of list of names
num_clus = len(clusters)
print(clusters)
for i in range(num_clus):
for j in range(len(clusters[i])):
clusters[i][j] = riderlist[clusters[i][j]]
return clusters
def LocGrpMatch(Groups,PickupPoints):
for Group in Groups:
xtot = 0
ytot = 0
for i in Group:
xtot += float(i['x'])
ytot += float(i['y'])
xcenter = xtot/len(Group)
ycenter = ytot/len(Group)
# The above finds the epicenter of the group
FinalPickupDisp = [9999999]
FinalPickupName = ['Filler']
# "empty" lists, My strategy here was to find
# find the net displacement of each possible
# pickup point to the group's epicenter.
# I needed both information, the total distance
# and the actual name of the pickup point.
# My strategy was to find the displacement for
# each point, and if that was smaller than the
# displacement of any other already in the list
# then it will be appended (i.e. the last point
# listed will always be the closest)
for PickupPoint in PickupPoints:
LocX = float(PickupPoint['x'])
LocY = float(PickupPoint['y'])
xdisp = LocX-xcenter
ydisp = LocY-ycenter
disp = xdisp**2 + ydisp**2
if disp < min(FinalPickupDisp):
FinalPickupDisp.append(disp)
FinalPickupName.append(PickupPoint)
Group.append(FinalPickupName[-1])
# The closest point is the last item, so I
# append that to the group of people.
# since 'name' is a common element to both the
# people list and the location list, I print
# the 'name' elements of all the items
return Groups
# Group is a list of lists (the original group of people from the
# the clustering algorithm, plus the location)
|
edb41d61c912984941dda7d3e4d0c8df4f147acd | Eduardo-Mendieta-Est/curso_python_basico | /practica4.py | 1,053 | 3.96875 | 4 | # Generadores: -------------------------------
#Estructuras que extraen valores de una función y se almacenan en objetos iterables
#que se pueden recorrer.
def funcion_tradicional_genera_pares(limite):
num = 1
lista_pares = []
while num<limite:
lista_pares.append(num*2)
num+=1
return lista_pares
print(funcion_tradicional_genera_pares(10))
def funcion_generadora_genera_pares(limite):
num = 1
while num < limite:
yield num*2
num+=1
objeto_generador = funcion_generadora_genera_pares(10)
print(next(objeto_generador))
print(next(objeto_generador))
print(next(objeto_generador))
# yield from: --------------------------------------
# Simplifica el codigo de lo generadores en el caso de utilizar bucles for anidados
# *ciudades: permite recibir varios argumentos en forma de tupla.
def devuelve_ciudades(*ciudades):
for ciudad in ciudades:
yield from ciudad #Devuelve una a una cada letra de la ciudad
ciudades_devueltas = devuelve_ciudades('Madrid', 'Paris')
|
ee588e5c73703bff04f1d3460c3f2be2303dd11c | isaiahcoe/basic-age-solver- | /Age Solvery.py | 193 | 4.125 | 4 | #THIS IS AMAZING CODE CREATED BY ISAIAH
#GITHUB PLEASE DO NOT STEAL THIS AMAZING CODE
birth_year = input('what year were you born? ')
age = 2021 - int(birth_year)
print(f'Your age is: {age}')
|
985cd4532c12f099f8455fa45c5b1a748bfab945 | HelmuthMN/python-studies | /chapter9/reading_files/read_python.py | 355 | 3.734375 | 4 | filename = 'reading_files/learning_python.txt'
with open(filename) as file_object:
print(file_object.read())
with open(filename) as file_object:
for l in file_object:
print(l)
with open(filename) as file_object:
lines = file_object.readlines()
pi_string = ''
for line in lines:
pi_string += line.rstrip()
print(pi_string) |
6c0aa3fcf440ba3b1b4570273243cacceb29b54c | safelyafnan/Muhammad-Safely-Afnan_I0320070_M-Wildan-Rusydani_Tugas6 | /I0320070_exercise 6.2.py | 146 | 3.8125 | 4 | #input untuk nilai n
n = int(input("masukan banyak pengulangan : "))
#melakukan pengulangan
i = 1
while 1 <= n:
print(1)
i = i + 1 |
1f66c2d6b18ab487899c1ac07bf409c0d1126219 | Dushyanttara/Competitive-Programing | /conditional_tests.py | 1,624 | 4.28125 | 4 | #Dushyant Tara(18-06-2020): This program helps you understand conditionals by practice
#Exercises
#Conditional tests
car = 'subaru'
print("Is car == 'subaru'? I predict True.")
print(car == 'subaru')
print("\nIs car == 'audi'? I predict False")
print(car == 'audi')
fruit = 'pineapple'
print("is fruit == 'pineapple'? I predict True")
print(fruit == 'pineapple')
fruits = ['apple','orange','mango','banana','apricot','avocado']
print("is pineapple present in your list?")
print('pineapple' in fruits)
print("is orange in the list?")
print('orange' in fruits)
cities_lived = ['Ambala', 'Chandigarh', 'Goa', 'Gurgaon', 'Bangalore', 'Mumbai','Jaipur']
print("Have you lived in Amritsar?")
print('Amritsar' in cities_lived)
print("Have you lived in Goa?")
print('Goa' in cities_lived)
friends = ['Sidhant', 'Umesh', 'Ishmin', 'Nidhi', 'Vyom', 'Clyde']
print("is Umesh your first friend?")
print(friends[0].lower() == 'Umesh'.lower())
print("is Umesh your second friend?")
print(friends[1].lower() == 'Umesh'.lower())
print("is Sidhant your close friend?")
print('Sidhant' in friends)
print("is Salim your friend?")
print('Salim' in friends)
defaulter_students = ['amar', 'modi', 'sonia', 'kejriwal','rahul' ]
student = 'arvind'
print("is Arvind a good student?")
print(student not in defaulter_students)
print("\nsite loads")
page1_loads = 100
page2_loads = 200
page3_loads = 500
page4_loads = 600
print((page1_loads >= 100) and (page2_loads < 1000))
print((page1_loads > 50) or (page3_loads > 5000))
print((page3_loads < 5000) and (page4_loads > 50))
|
ef309613c2cb542557ebe4e8efa7892b9f36ce68 | utpalsacheen/Python_programs | /tigera.py | 741 | 3.8125 | 4 | from array import *
class TrainRide:
def __init__(self):
self.station= [1,2,3,4,5]
self.seats = [1,2,3,4,5,6,7,8,9]
self.reserved = {}
def findAvailableSeats(self, start, end):
for seat, station in self.reserved.items():
if str(start) == station:
self.seats.append(seat)
del self.reserved[seat]
if self.seats:
seat = self.seats.pop(0)
print(self.seats)
self.reserved[str(seat)] = str(end)
return seat
return "No Seats available!"
def main():
tr = TrainRide()
seat = tr.findAvailableSeats(1,2)
print("Available Seat: ",seat)
seat = tr.findAvailableSeats(1,2)
print("Available Seat: ",seat)
seat = tr.findAvailableSeats(2,4)
print("Available Seat: ",seat)
if __name__ == "__main__":
main() |
c13d83d7512d0feeb29da137462e11f7024e0f08 | thevivekshukla/learning-python | /basics/myprogram.py | 205 | 3.984375 | 4 | greeting = input("Enter some greeting message: ")
print(greeting)
a = 2
b = 3
print(a + b)
def curr_converter(rate, euros):
dollars = rate*euros
return dollars
print(curr_converter(10, 56))
|
1dbcca822d3d64f04870f25ba9ba847c568be229 | xys234/coding-problems | /algo/dp/text_justification.py | 1,751 | 4.1875 | 4 | """
"""
from math import pow
def cost(w, page_width):
"""
calculate the cost of a line of words based on page width
:param w:
:param page_width:
:return:
"""
char_len = sum([len(i) for i in w]) + len(w) - 1 # character plus the spaces between words
if char_len > page_width:
return float("inf")
else:
return pow(page_width - char_len, 3)
def justify_text(w, page_width):
"""
Justify the text based on minimizing the spaces. It is assumed no word is longer than page width
:param w:
:param page_width:
:return:
"""
n = len(w)
c, p = [0] * (n+1), [0] * (n+1)
c[n] = 0 # cost from the index described below to the end of the input word list
p[n] = 0 # the index of the word immediately after the ending word of the first line
for i in range(n-1, -1, -1):
q = float("inf")
for j in range(i+1, n+1):
if q > cost(w[i:j], page_width) + c[j]:
q = cost(w[i:j], page_width) + c[j]
c[i] = q
p[i] = j
return c, p
def print_text(w, p, page_width):
"""
:param w: a list of n words
:param p: a list of indices of the word immediately after the ending word of the first line for various suffix of w
:param page_width: page width
:return: print the words in left justification with page width
"""
i = 0
while i < len(w):
line = " ".join(w[i:p[i]]).ljust(page_width)
print(line)
i = p[i]
if __name__=="__main__":
page_width = 16
w = ["blah", "blah", "blah", "blah", "reallylongword"]
p = [1,3,3,3,4]
c, p = justify_text(w, page_width)
print_text(w, p, page_width)
|
3c8fcbbe88fcc2ae8ba0e0c2467bf00c8ea537f7 | PranavDev/Searching_Techniques | /Linear_Search.py | 561 | 3.9375 | 4 | # Implementing Linear Search using Python
# Date: 01/05/2021
# Author: Pranav H. Deo
import numpy as np
def Linear_Search(L, element):
loc = 999999
for index, ele in enumerate(L):
if ele == element:
loc = index
return loc
# Main
MyList = np.random.randint(0, 500, 100)
print(MyList)
search_number = int(input('> Enter the Number : '))
loc = Linear_Search(MyList, search_number)
if loc != 999999:
print('\n> Element ', search_number, ' found at location : ', loc+1)
else:
print('\n> Element ', search_number, ' not found')
|
e5992fd33a8207f2a4c318e4bb2c94c932ad2ed8 | TracyOgutu/Password-Locker | /run2.py | 6,619 | 3.875 | 4 | #!/usr/bin/env python3.6
import random
from user import User
from credential import Credential
def create_user(usern, userpass):
new_user = User(usern, userpass)
return new_user
def save_users(user):
user.save_user()
def del_user(user):
user.delete_user()
def login(user, passw):
login = User.login(user, passw)
if login != False:
return User.login(user, passw)
def generate_password(name):
password = Credential.generate_password()
return password
def find_user(username):
return User.find_by_username(username)
def checking_existing_users(username):
return User.user_exist(username)
def display_users():
return User.display_users()
def create_credential(nameofuser, accname, accpass):
new_credential = Credential(nameofuser, accname, accpass)
return new_credential
def save_credentials(credential):
credential.save_credential()
def del_credential(credential):
credential.delete_credential()
def find_credential(accountname):
return Credential.find_by_accountname(accountname)
def checking_existing_credentials(accountname):
return User.user_exist(accountname)
def display_credential():
return Credential.display_credentials()
def main():
print("Welcome to Password Locker. What is your name?")
usern = input()
print(f"Hello {usern}. What would you like to do?")
print('\n')
while True:
print('''Use these short codes :
cp - create a password locker account \n
du - display the users available\n
lg - Log in to your password locker account\n
ex - exit the password locker\n ''')
short_code = input().lower()
if short_code == 'cp':
'''
Creates Password Locker Account
'''
print("\n")
print("New Password Locker Account")
print("-"*10)
print("User name ...")
usern = input()
print("Password ...")
userpass = input()
# Create and save new user
save_users(create_user(usern, userpass))
print("\n")
print(f"{usern} Welcome to Password Locker")
print("\n")
elif short_code == 'du':
'''
Displays names of registered users
'''
if display_users():
print("\n")
print("Current users of Password Locker")
print("-"*10)
for user in display_users():
print(f"{user.username}")
print("-"*10)
else:
print("\n")
print("Password Locker has no users yet.\n Be the first user :)")
print("\n")
elif short_code == 'lg':
'''
Logs in the user into their Password Locker account
'''
print("\n")
print("Log into Password Locker Account")
print("Enter the user name")
user = input()
print("Enter the password")
passw = input()
if login(user, passw) == None:
print("\n")
print("Please try again or create an account")
print("\n")
else:
login(user, passw)
print("\n")
print(f'''{user} Welcome to your Credentials\n
Use these short codes to get around''')
while True:
print(''' Short codes:
ac - add a credential \n
dc - display credentials \n
ex - exit Credentials''')
# Get short code from the user
short_code = input().lower()
if short_code == 'ac':
print("\n")
print("New Credential")
print("-"*10)
print("Your Username")
username = input()
print("Name of the account ...")
accname = input()
print(
'''Choose password option\n ap:Automatically generated password \n mp.Make your own password''')
option = input()
if option == 'mp':
print("Password of the credential ...")
acc_pass = input().lower()
else:
x = []
r = range(10, 500)
for n in r:
x.append(str(n))
acc_pass = (username+accname+random.choice(x))
print(f"Your generated password is: {acc_pass}")
# else:
# print("Please select the correct short code")
# Create and save new user
save_credentials(create_credential(
username, accname, acc_pass))
print("\n")
print(
f"Credentials for {accname} have been created and saved")
print("\n")
elif short_code == 'dc':
if display_credential():
print("Here is a list of all your credentials")
print('\n')
for credential in display_credential():
print(
f"Username: {credential.user_name} \nAccount: {credential.accountname}\nPassword: {credential.accountpassword}\n")
print('\n')
else:
print('\n')
print("You don't have any credentials saved yet")
print('\n')
elif short_code == 'ex':
print("You have exited your credentials.")
break
else:
print("Try again. Please enter correct short codes")
elif short_code == 'ex':
print("Thank you. See you next time.")
break
else:
print("Try again. Please enter correct short codes")
if __name__ == '__main__':
main()
|
c4dfe7e3a0b3466acacfeed8906939c2a6501a61 | nixxby/alien-invasion | /alien_invasion/scoreboard.py | 2,283 | 3.5 | 4 | import pygame.font
from pygame.sprite import Group
from alien_invasion.ship import Ship
class Scoreboard():
"""To report live score in a scoreboard"""
def __init__(self,setting,screen,stats):
"""Initialize scoreboard attributes"""
self.screen = screen
self.setting = setting
self.stats = stats
self.screen_rect = screen.get_rect()
self.text_color = (30,30,30)
self.font = pygame.font.SysFont(None,48)
self.prep_ship()
self.prep_score()
self.prep_high_score()
self.prep_level()
def prep_high_score(self):
self.rounded_high_score = int(round(self.stats.high_score,-1))
self.high_score_str = "{:,}".format(self.rounded_score)
self.high_score_img = self.font.render(self.high_score_str,True,self.text_color,self.setting.bg_color)
self.high_score_rect = self.high_score_img.get_rect()
self.high_score_rect.centerx = self.screen_rect.centerx
self.high_score_rect.top = 20
def prep_score(self):
"""Turns score into a rendered img on screen"""
self.rounded_score = int(round(self.stats.score,-1))
self.score_str = "{:,}".format(self.rounded_score)
self.score_img = self.font.render(self.score_str,True,self.text_color,self.setting.bg_color)
self.score_rect = self.score_img.get_rect()
self.score_rect.right = self.screen_rect.right - 20
self.score_rect.top = 20
def prep_level(self):
"""Display level on screen"""
self.level_str = str(self.stats.level)
self.level_img = self.font.render(self.level_str,True,self.text_color,self.setting.bg_color)
self.level_rect = self.level_img.get_rect()
self.level_rect.right = self.screen_rect.right - 20
self.level_rect.top = self.score_rect.bottom + 10
def prep_ship(self):
"""Display ships available on top left"""
self.ships = Group()
for ship_num in range(self.stats.ships_left):
ship = Ship(self.screen,self.setting)
ship.rect.x = ship.rect.width * ship_num +10
ship.rect.y = 10
self.ships.add(ship)
def show_score(self):
"""display scoreboard & levelboard on screen"""
self.screen.blit(self.score_img,self.score_rect)
self.screen.blit(self.high_score_img,self.high_score_rect)
self.screen.blit(self.level_img,self.level_rect)
self.ships.draw(self.screen)
|
e32147afac3f1b4c55c38fdf1891c229a7db96a4 | Rudrajit12/Lab_Exam | /wordcount.py | 284 | 3.71875 | 4 | import re
import string
freq = {}
file = open('sample.txt','r')
text = file.read().lower()
pattern = re.findall(r'\b[a-z]{3,15}\b',text)
for word in pattern:
count = freq.get(word,0)
freq[word] = count + 1
freq_list = freq.keys()
for words in freq_list:
print words, freq[words] |
55335e83defaf036add9feffea6258b252fbd534 | sakshichavre20/Eulers-Projects | /Python/square.py | 527 | 3.671875 | 4 | sum1=0
sum2 = 0
squares = []
#find squares upto 100
def square():
global squares,sum1
for i in range (1,101):
sq=i**2
squares.append(sq)
for i in squares:
sum1=sum1+i
square()
#find addition of all numbers upto 100
def results():
global sum2
for i in range(1,101):
sum2=sum2+i
results()
#find square of addition of all numers upto 100
sumnum=sum2**2
#substract square of sum of all numbers-sum of squares of all the numbers
result=sumnum-sum1
print(result)
|
5c9fc5d42b359a122534991835e3cb04493be230 | CleitonSilvaT/URI_Python | /1-Iniciante/2028.py | 986 | 3.90625 | 4 | # -*- coding: utf-8 -*-
# Computar elementos da sequencia, em ordem inversa
def sequencia(num, seq):
if(num == 0):
return seq.append(num)
seq += num * [num]
return sequencia(num - 1, seq)
if __name__ == '__main__':
# Variavel
caso_teste = 1
while(True):
# Condicao de parada
try:
entrada = int(input())
except(EOFError):
break
lista = []
sequencia(entrada, lista)
# Resultado
if(entrada == 0):
print('Caso {:d}: {:d} numero'.format(caso_teste, len(lista)))
else:
print('Caso {:d}: {:d} numeros'.format(caso_teste, len(lista)))
# Imprimindo lista no padrao, considerando construcao em ordem inversa
for i in range(len(lista)-1, -1, -1):
if(i > 0):
print(lista[i], end=' ')
else:
print(lista[i])
# Espaco entre entradas
print()
caso_teste += 1 |
4606f278cb7c5a94058a78c70fd03795b282190d | Andrey-Strelets/Python_hw | /hw05/dz5_fizzbuzz.py | 654 | 4.28125 | 4 | # Продолжаем идеализировать fizzbuzz, теперь применяем функции и map везде, где можно и нельзя!
rint ("Enter first number :")
number1 = int(input())
print ("Enter second number :")
number2 = int(input())
print ("Enter third number :")
# number3 = int(input())
number3 = [5, 18, 9]
def fizzbuzz(num):
for num in range(1, num + 1):
if num % 2 == 0:
print("F",end='')
if num % 5 == 0:
print ("B", end='')
if num % 2 != 0 and num % 5 != 0:
print (num, end='')
print (" ", end ='')
print("\n")
fizz_buzz_number = list(map(fizzbuzz, number3))
print(fizz_buzz_number)
|
4bb152b990e86c9032072f399e94817fa140cf83 | Littlemansmg/pyClass | /Week 2 Assn/Project 4/4-2.py | 343 | 4.1875 | 4 | # created by Scott "LittlemanSMG" Goes on 11/05/2019
def miles_to_feet(miles):
feet = miles * 1520
return int(feet)
def main():
miles_input = input("How many miles did you walk?: ")
miles_input = float(miles_input)
print("You walked {} feet.".format(miles_to_feet(miles_input)))
if __name__ == "__main__":
main()
|
56259f1dc1775d67b219b3856fc3252b107f0f94 | ams103/-vningar | /TextAdventure.py | 567 | 3.609375 | 4 | import random, os, sys
from time import sleep
from typewriter import typewriter
typewriter("Welcome to xxx!!!")
print()
typewriter("What do you wish to be called? ")
name = input()
typewriter("What race do you wanna be? Type \"raceinfo " "to find out details.")
print()
races = ["Dwarf", "Elf","Human", "Orc"]
typewriter("Do wish to be a dwarf, elf, human or an orc? ")
print()
race = input()
r = len(races)
for r in races:
if race == "raceinfo":
print(r, end='')
sys.stdout.flush()
sleep(0.5)
print()
#elif race == "Dwarf"
|
4ca70d473207e49a30e34c1c56e1b89aebbf6ec0 | Yang1k/tools | /webshell_scan/scan/scan_file/scan/scan/scan.py | 589 | 3.640625 | 4 | import sys
import os
import re
import zipfile
# 解压
def unpack(file_path):
f = zipfile.ZipFile(file_path,'r')
for file in f.namelist():
f.extract(file,"D:\write\scan\\file")
unpack("D:\write\scan\scan.zip")
#获取所有文件路径
def get_filepath(file_dir):
file_path = []
for root,dirs,files in os.walk(file_dir):
for name in files:
file_path.append(os.path.join(root,name))
return file_path
print(get_filepath("D:\write\scan\\file"))
# for name in all_file:
# f = open(name)
# lines = f.readlines(); |
ecc4977a1c51aa34d7815723004f7ff10f38c361 | ps4417/algorithm | /Codeup/코드업 데이터정렬/1172.py | 242 | 3.8125 | 4 | # 세 수 정렬하기
#세 수를 오름차순으로 정렬하려고 한다. (낮은 숫자 -> 높은 숫자)
# 예)
# 5 8 2 ====> 2 5 8 로 출력
data = list(map(int,input().split()))
data.sort()
for i in data:
print(i,end=' ') |
f05300ba871f04484f4e2e73de1f5af3a2bec045 | ufomaeoju/Python-Challenge | /PyBank/main.py | 1,118 | 3.875 | 4 | #The total number of months included in the dataset
import os
import csv
budget_csv = os.path.join("budget_data.csv")
#print("Working")
file = open(budget_csv)
numline = len(file.readlines())
print ("The total number of lines in" , int(numline - 1))
#The net total amount of "Profit/Losses" over the entire period
a = []
with open(budget_csv, newline="") as csvfile:
csvreader = csv.reader(csvfile, delimiter=",")
csv_header = next(csvfile)
#print(f"Header: {csv_header}")
for row in csvreader:
number = int(row[1])
a.append(number)
# sum = sum += row[1]
total = sum(a)
print("The Total is" ,total)
#The average of the changes in "Profit/Losses" over the entire period
def Average(x):
print("The Average is" ,x/len(a))
Average(total)
#The greatest increase in profits (date and amount) over the entire period
def Max(x):
max_num = max(a)
print("The Max is" , max_num)
Max(total)
#The greatest decrease in losses (date and amount) over the entire period
def Min(x):
min_num = min(a)
print("The Min is" , min_num)
Min(total)
|
36e3b05b756260b74d60b6b7b99407b64991aaab | ASHISH-KUMAR-PANDEY/python | /Economial_Numbers.py | 580 | 3.703125 | 4 | def prime_factors(n):
i=0;primes=[]
while i*i<n:
i+=2
while n%i==0:
primes.append(i)
n//=i
if i==2:i=1
if n>1:primes.append(n)
return primes
def is_economical(n):
ln=len(str(n))
p=prime_factors(n)
c=[];e=0
for i in p:
if i not in c:
c.append(i)
if p.count(i)>1:
e+=len(str(i)+str(p.count(i)))
else:
e+=len(str(i))
if e==ln:
return 'Equidigital'
elif e<ln:
return 'Frugal'
return 'Wasteful'
|
fa055698f86eb688e098e523d0baa238f64d39a4 | HansleeLX/Python | /basic03.py | 79 | 3.6875 | 4 | age=14
if age <= 18:
print 'your age is', age
else:
print 'adult'
|
2052e4a541996eda732090f0314b2678d4932035 | IS2511/spbstu-homework | /python/task-1.2.5.py | 673 | 3.53125 | 4 |
# xxx: Today I will generate random numbers
# yyy: But LCG is pseudo-random
# zzz: It is?!
# zzz: I'm re-generating all my SSH keys
# if (type(tonumber(arg[1])) ~= "number") or (type(tonumber(arg[2])) ~= "number") then
# print("Usage: "..arg[0].." <seed> <count>")
# os.exit()
# end
# C++11 constants are used for reference
lcg_config = {"a":48271, "c":0, "m":((2**31)-1)}
seed = 123 # Used as a starting point for LCG
length = 10 # How many to generate
print("Generating "+str(length)+" numbers using seed "+str(seed)+"...")
def lcg(x):
return ( lcg_config["a"]*x + lcg_config["c"] ) % lcg_config["m"]
x = seed
for i in range(length):
x = lcg(x)
print(x)
|
15a2284eb9be467f2667c5d5172a54d871aefecd | austindavidbrown/austindavidbrown.github.io | /ML_algorithms/multinomial_logistic_regression.py | 2,599 | 3.546875 | 4 | import numpy as np
import matplotlib.pyplot as plt
class MultRegression():
@staticmethod
def softmax(M):
exps = np.exp(M)
S_exps = (exps @ np.ones(M.shape[1]))[:, np.newaxis]
return 1/S_exps * exps
@staticmethod
def entropy(Y, P):
n_samples = P.shape[0]
n_classes = P.shape[1]
return -1/n_samples * np.ones(n_samples).T @ (Y * np.log(P) @ np.ones(n_classes))
def train(self, X, y, max_iter = 501, learning_rate = .1):
n_samples = X.shape[0]
n_features = X.shape[1]
n_classes = np.unique(y).shape[0]
# Convert to a multinomial vector
Y = np.zeros((n_samples, n_classes))
Y[np.arange(n_samples), np.array(y.T, dtype = int)] = 1
self.W = np.zeros((n_features, n_classes))
self.b = np.zeros((1, n_classes))
for i in range(0, max_iter):
# Forward pass
A_o = X @ self.W + self.b * np.ones((n_samples, n_classes))
O = MultRegression.softmax(A_o)
if i % 100 == 0:
print(f"Iteration: {i}, Training Loss: {MultRegression.entropy(Y, O)}")
# Backward pass
dW = 1/n_samples * X.T @ (O - Y)
db = 1/n_samples * np.ones((n_samples, 1)).T @ (O - Y)
# Gradient step
self.W = self.W - learning_rate * dW
self.b = self.b - learning_rate * db
def predict(self, X):
n_samples = X.shape[0]
n_classes = self.W.shape[1]
A_o = X @ self.W + self.b * np.ones((n_samples, n_classes))
O = MultRegression.softmax(A_o)
return np.argmax(O, axis = 1)
###
# Opdigits test dataset
###
test = np.loadtxt("data/optdigits_test.txt", delimiter = ",")
X = test[:, 0:64]
y = test[:, 64]
# Train/test split
n_samples = X.shape[0]
n_TRAIN = int(.75 * n_samples)
I = np.arange(0, n_samples)
TRAIN = np.random.choice(I, n_TRAIN, replace = False)
TEST = np.setdiff1d(I, TRAIN)
X_train = X[TRAIN, :]
y_train = y[TRAIN]
X_test = X[TEST, :]
y_test = y[TEST]
mlr = MultRegression()
mlr.train(X_train, y_train)
print("Train accuracy:", 1/X_train.shape[0] * np.sum((mlr.predict(X_train) == y_train).astype(int)))
print("Test accuracy:", 1/X_test.shape[0] * np.sum((mlr.predict(X_test) == y_test).astype(int)))
###
# Blobs
###
from sklearn.model_selection import train_test_split
from sklearn.datasets import make_blobs
X, y = make_blobs(centers=4, n_samples = 5000)
X_train, X_test, y_train, y_test = train_test_split(X, y)
W, b = MultRegression.train(X_train, y_train)
print("Train accuracy:", 1/X_train.shape[0] * np.sum(MultRegression.predict(X_train, W, b) == y_train))
print("Test accuracy:", 1/X_test.shape[0] * np.sum(MultRegression.predict(X_test, W, b) == y_test))
|
c500cdd2eeb633e0edb20c24e99969598e71849d | rkooo567/CS61A_practice | /Link.py | 2,094 | 4.1875 | 4 | # Linked List is either empty or a first value and the rest of the linked list
class Link(object):
empty = ()
def __init__(self, first, rest=empty):
assert rest is Link.empty or isinstance(rest, Link)
self.first = first
self.rest = rest
def is_empty(self):
if self.first == Link.empty:
return True
else:
return False
def show_link(self):
if self.rest == self.empty:
return str(self.first) + " -> nothing"
return str(self.first) + " -> " + self.rest.show_link()
def __getitem__(self, i):
if i == 0:
return self.first
else:
return self.rest[i - 1]
def __len__(self):
return 1 + len(self.rest)
s = Link(3, Link(4, Link(5)))
square = lambda x: x * x
odd = lambda x: x % 2 == 1
def extend_link(s, t):
if s is Link.empty:
return t
else:
return Link(s.first, extend_link(s.rest, t))
def map_link(f, s):
"""
apply function f to every element in the Linked List s
"""
if s is Link.empty:
return Link.empty
else:
return Link(f(s.first), map_link(f, s.rest))
def filter_link(filter, s):
""" Return a link with elements of s for which f returns True """
if s is Link.empty:
return s
else:
if filter(s.first):
return Link(s.first, filter_link(filter, s.rest))
else:
return filter_link(filter, s.rest)
def join_link(s, seperator):
""" Return a string of all elements in s seperated by seperator. """
assert type(seperator) == str, "seperator should be the string type"
if s.rest is Link.empty:
return str(s.first)
else:
return str(s.first) + seperator + join_link(s.rest, seperator)
def partitions(n, m):
""" Return a linked list of partitions of n & parts of up to m.
Each partition is represented as a linked list
"""
if n == 0:
return Link(Link.empty)
elif n < 0 or m == 0:
return Link.empty
else:
using_m = partitions(n - m, m)
with_m = map_link(lambda p: Link(m, p), using_m)
without_m = partitions(n , m - 1)
return extend_link(with_m, without_m)
def print_partitions(n, m):
links = partitions(n, m)
lines = map_link(lambda line: join_link(line, ' + '), links)
map_link(print, lines)
|
8362e4bfe7f9feabfbb771714aee76d9e468e0c9 | elena314/yandex-algos-training | /hw8/e.py | 1,836 | 3.859375 | 4 | # https://contest.yandex.ru/contest/28069/problems/E/
class BSTNode:
def __init__(self, key=None):
self.key = key
self.left = None
self.right = None
def insert_recursive(self, key):
if self.key is None:
self.key = key
return self
if key == self.key:
return self
if key < self.key:
if self.left:
return self.left.insert_recursive(key)
self.left = BSTNode(key)
return self.left
if self.right:
return self.right.insert_recursive(key)
self.right = BSTNode(key)
return self.right
def __iter__(self):
if self.left:
for node in self.left:
yield node
yield self
if self.right:
for node in self.right:
yield node
def leaves(keys):
bst = BSTNode()
for key in keys:
bst.insert_recursive(key)
results = []
for node in bst:
if not node.left and not node.right:
results.append(node.key)
return results
assert leaves([7, 3, 2, 1, 9, 5, 4, 6, 8]) == [1, 4, 6, 8]
assert leaves([7, 3, 3, 3, 2, 1, 9, 5, 4, 6, 8]) == [1, 4, 6, 8]
assert leaves([9, 4, 2, 1]) == [1]
assert leaves([1, 6, 8, 2]) == [2, 8]
assert leaves([1, 7]) == [7]
assert leaves([7, 1]) == [1]
assert leaves([3, 1, 2]) == [2]
assert leaves([3, 1, 2, 0]) == [0, 2]
assert leaves([5, 4, 3, 2, 1, 0, -1, -2, -3, -4, -5]) == [-5]
assert leaves([-5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5]) == [5]
assert leaves([4, 2, 4, 6, 2, 4, 1, 6, 2, 4, 3, 1, 6, 2, 4, 5, 3, 1, 6, 2, 4, 7, 5, 3, 1, 6, 2, 4]) == \
[1, 3, 5, 7]
def main():
keys = list(map(int, input().split()))[:-1]
for key in leaves(keys):
print(key)
if __name__ == '__main__':
main()
|
f77d7545e824baec6286ff2ea8113fd36a1dc59c | Nekotopec/code-challenge-answer | /task2/src/validators.py | 1,346 | 4.0625 | 4 | import datetime
import re
class DateValidator():
""" Class for input parametrs validation."""
def date_validation(self, month, year):
# Validate month.
if not month.isdigit():
print('Input the month using digits.')
return False
elif int(month) > 12 or int(month) < 1:
print('Month must be from 1 to 12, not {}'.format(month))
return False
# Validate Year.
if not year.isdigit():
print('Input the year using digits.')
return False
elif int(year) < 2015:
print('Input year after the 2015th.')
return False
# Validate date.
day = datetime.datetime.now().strftime('%d')
# Fix ValueError when day is out of range for month.
try:
date = datetime.datetime(int(year), int(month), int(day))
except ValueError:
date = datetime.datetime(int(year), int(month), 28)
if datetime.datetime.now() < date:
print('You input a date from the future.')
return False
return True
def resolution_validation(resolution):
# Validate resolution.
if not re.search(r'\b\d{3,4}x\d{3,4}\b', resolution):
print('You input resolution in the invalid format.')
return False
return True
|
f4c31de36b051ab903dce04064f41d4a5c2df700 | salamf/Ferry-Avg-Monthly-Delay-Calculator | /src/cipher.py | 1,865 | 3.6875 | 4 | #!/usr/bin/env python3
class DecryptException(Exception):
pass
def decode_line(alphabet, line, key):
""" Decrypts an encrypted string, and returns the result """
res = ""
for index, letter in enumerate(line):
line_char_val = alphabet.index(letter)
key_char_val = alphabet.index(key[index % len(key)])
letter_pos = (line_char_val - key_char_val) % len(alphabet)
res += alphabet[letter_pos]
return res
def check_str(lis):
""" Checks if the decrypted information was decrypted properly """
return '!' and '@' and '#' and '$' and '%' and '^' and '&' and '*' and '(' and ')' \
and '-' and '_' and '+' and '=' and '~' and '`' and '{' and '}' and '[' and ']' \
and '\\' and ';' and ':' and '"' and "'" and '/' and '?' and '<' and '>' \
and '.' and '|' not in ''.join(lis)
class FileDecoder(object):
""" FileDecoder iterable class """
def __init__(self, key, filename, alphabet):
self.key = key
self.filename = filename
self.alphabet = alphabet
whole_str = self.open()
self.header_line = whole_str[0].split(',')
self.input_string = whole_str[1:]
def open(self):
with open(self.filename, 'r') as input_file:
try:
whole_str = decode_line(self.alphabet, input_file.read(), self.key).splitlines()
if not check_str(whole_str):
raise DecryptException from None
except Exception:
raise DecryptException from None
return whole_str
def __repr__(self):
return "FileDecoder(key='{}', file='{}')".format(self.key, self.filename)
def __len__(self):
return len(self.input_string) + 1
def __iter__(self):
for line in self.input_string:
yield line.split(',')
|
d9b41c1df8a34978cea5ee03a5d218d0428bb526 | sumanblack666/datacamp-python-data-science-track | /Manipulating DataFrames with pandas/Chapter 4 - Grouping data.py | 5,744 | 4.15625 | 4 | #Chapter 4 - Grouping data
#Grouping by multiple columns
# Group titanic by 'pclass'
by_class = titanic.groupby('pclass')
# Aggregate 'survived' column of by_class by count
count_by_class = by_class['survived'].count()
# Print count_by_class
print(count_by_class)
# Group titanic by 'embarked' and 'pclass'
by_mult = titanic.groupby(['embarked','pclass'])
# Aggregate 'survived' column of by_mult by count
count_mult = by_mult['survived'].count()
# Print count_mult
print(count_mult)
#-----------------------------------------------------------------------------------#
#Grouping by another series
# Read life_fname into a DataFrame: life
life = pd.read_csv(life_fname, index_col='Country')
# Read regions_fname into a DataFrame: regions
regions = pd.read_csv(regions_fname, index_col='Country')
# Group life by regions['region']: life_by_region
life_by_region = life.groupby(regions['region'])
# Print the mean over the '2010' column of life_by_region
print(life_by_region['2010'].mean())
#Computing multiple aggregates of multiple columns
# Group titanic by 'pclass': by_class
by_class = titanic.groupby('pclass')
# Select 'age' and 'fare'
by_class_sub = by_class[['age','fare']]
# Aggregate by_class_sub by 'max' and 'median': aggregated
aggregated = by_class_sub.agg(['max','median'])
# Print the maximum age in each class
print(aggregated.loc[:, ('age','max')])
# Print the median fare in each class
print(aggregated.loc[:, ('fare','median')])
#-----------------------------------------------------------------------------------#
#Aggregating on index levels/fields
# Read the CSV file into a DataFrame and sort the index: gapminder
gapminder = pd.read_csv('gapminder.csv', index_col=['Year','region','Country']).sort_index()
# Group gapminder by 'Year' and 'region': by_year_region
by_year_region = gapminder.groupby(level=['Year','region'])
# Define the function to compute spread: spread
def spread(series):
return series.max() - series.min()
# Create the dictionary: aggregator
aggregator = {'population':'sum', 'child_mortality':'mean', 'gdp':spread}
# Aggregate by_year_region using the dictionary: aggregated
aggregated = by_year_region.agg(aggregator)
# Print the last 6 entries of aggregated
print(aggregated.tail(6))
#-----------------------------------------------------------------------------------#
#Grouping on a function of the index
# Read file: sales
sales = pd.read_csv('sales.csv', index_col='Date', parse_dates=True)
# Create a groupby object: by_day
by_day = sales.groupby(sales.index.strftime('%a'))
# Create sum: units_sum
units_sum = by_day['Units'].sum()
# Print units_sum
print(units_sum)
#-----------------------------------------------------------------------------------#
#Detecting outliers with Z-Scores
# Import zscore
from scipy.stats import zscore
# Group gapminder_2010: standardized
standardized = gapminder_2010.groupby('region')['life','fertility'].transform(zscore)
# Construct a Boolean Series to identify outliers: outliers
outliers = (standardized['life'] < -3) | (standardized['fertility'] > 3)
# Filter gapminder_2010 by the outliers: gm_outliers
gm_outliers = gapminder_2010.loc[outliers]
# Print gm_outliers
print(gm_outliers)
#-----------------------------------------------------------------------------------#
#Filling missing data (imputation) by group
# Create a groupby object: by_sex_class
by_sex_class = titanic.groupby(['sex','pclass'])
# Write a function that imputes median
def impute_median(series):
return series.fillna(series.median())
# Impute age and assign to titanic.age
titanic.age = by_sex_class.age.transform(impute_median)
# Print the output of titanic.tail(10)
print(titanic.tail(10))
#-----------------------------------------------------------------------------------#
#Other transformations with .apply
# Group gapminder_2010 by 'region': regional
regional = gapminder_2010.groupby('region')
# Apply the disparity function on regional: reg_disp
reg_disp = regional.apply(disparity)
# Print the disparity of 'United States', 'United Kingdom', and 'China'
print(reg_disp.loc[['United States','United Kingdom','China']])
#Grouping and filtering with .apply()
# Create a groupby object using titanic over the 'sex' column: by_sex
by_sex = titanic.groupby('sex')
# Call by_sex.apply with the function c_deck_survival and print the result
c_surv_by_sex = by_sex.apply(c_deck_survival)
# Print the survival rates
print(c_surv_by_sex)
#-----------------------------------------------------------------------------------#
#Grouping and filtering with .filter()
# Read the CSV file into a DataFrame: sales
sales = pd.read_csv('sales.csv', index_col='Date', parse_dates=True)
# Group sales by 'Company': by_company
by_company = sales.groupby('Company')
# Compute the sum of the 'Units' of by_company: by_com_sum
by_com_sum = by_company['Units'].sum()
print(by_com_sum)
# Filter 'Units' where the sum is > 35: by_com_filt
by_com_filt = by_company.filter(lambda g:g['Units'].sum() > 35)
print(by_com_filt)
#-----------------------------------------------------------------------------------#
#Filtering and grouping with .map()
# Create the Boolean Series: under10
under10 = (titanic['age'] < 10).map({True:'under 10', False:'over 10'})
# Group by under10 and compute the survival rate
survived_mean_1 = titanic.groupby(under10)['survived'].mean()
print(survived_mean_1)
# Group by under10 and pclass and compute the survival rate
survived_mean_2 = titanic.groupby([under10, 'pclass'])['survived'].mean()
print(survived_mean_2)
#-----------------------------------------------------------------------------------#
#-----------------------------------------------------------------------------------# |
981c9b798a254e3286cb04c6dd6e50e00b7f9367 | Charmi15/dailypractice | /rev.py | 149 | 4.0625 | 4 | first_name = input("Please enter your first name")
last_name = input("Please enter your last name")
print(last_name[::-1] + " " + first_name[::-1])
|
9d308dc9942c46cfb67d75c5c4e03fb3c650a55e | adityasunny1189/100DaysOfPython | /DSA/Sorting/merge_subarray.py | 574 | 3.8125 | 4 | def merge(arr, low, mid, high):
left = arr[low: mid+1]
right = arr[mid+1: high+1]
i = 0
j = 0
k = low
while i < len(left) and j < len(right):
if left[i] < right[j]:
arr[k] = left[i]
i += 1
k += 1
else:
arr[k] = right[j]
j += 1
k += 1
while i < len(left):
arr[k] = left[i]
i += 1
k += 1
while j < len(right):
arr[k] = right[j]
j += 1
k += 1
arr = [3, 2, 1]
merge(arr, 0, len(arr)//2, len(arr))
print(arr)
|
9e49af14a36527aa2a6262fdd39f1954dd947ecd | waltercoan/ALPCBES2017 | /maiormenorpessoa.py | 904 | 4.03125 | 4 | #http://www.pythontutor.com/visualize.html#mode=edit
altura = 0
pessoa=0
sexo = ''
omaior=0
omenor=0
somaaltfem=0
contfem=0
contmasc=0
sexodomaior=''
while(pessoa < 10):
print("Pessoa > ", pessoa)
print("Digite sua altura")
altura = float(input())
print("Digite o sexo (M/F)")
sexo = input()
if sexo == 'f' or sexo == 'F':
somaaltfem = somaaltfem + altura
contfem = contfem + 1
else:
contmasc = contmasc + 1
if altura > omaior:
omaior = altura
sexodomaior = sexo
if pessoa == 0:
omenor = altura
else:
if altura < omenor:
omenor = altura
pessoa = pessoa + 1
print("A maior altura e: ", omaior, " do sexo: ", sexodomaior)
print("A menor altura e: ", omenor)
mediafem = somaaltfem / contfem
print("A media da altura das mulheres e", mediafem)
print("O numero total de homens e", contmasc)
|
8adb675c4dfebb33a371c3579d838e4fa5b97881 | flovera1/CrackingTheCodeInterview | /Python/Chapter4TreesAndGraphs/dijkstra.py | 881 | 3.65625 | 4 | import heapq
def calculate_distances(valGraph, valStarting_vertex):
distances = {vertex:float('infinity') for vertex in valGraph}
distances[valStarting_vertex] = 0
entry_lookup = {}
pq = []
for vertex, distance in distances.items():
entry = [distance, vertex]
entry_lookup[vertex] = entry
heapq.heappush(pq, entry)
while(len(pq) > 0):
current_distance, current_vertex = heapq.heappop(pq)
for neighbor, neighbor_distance in enumerate(valGraph[current_vertex]):
distance = distances[current_vertex] + neighbor_distance
if distance < distances[neighbor]:
distances[neighbor] = distance
entry_lookup[neighbor][0] = distance
print(entry_lookup)
return distances
valGraph = {"a": {"b", 10}, "b": {"c", 15}}
print(calculate_distances(valGraph, "a")) |
53324f7cc8d9fa2681ae21f7853289ab0dbc6c95 | SIDORESMO/crAssphage | /bin/tree_collapser.py | 1,173 | 3.53125 | 4 | """
Tree collapser.
Collapse nodes in a phylogenetic tree.
(c) 2018 Alessandro Rossi
"""
import os
import sys
import argparse
from ete3 import Tree
def collapse_nodes(inputfile, threshold, output_name):
"""
Collapse nodes less than threshold
:param inputfile: The tree file
:param threshold: The threshold on which to collapse
:param output_name: The output file name
:return:
"""
input_tree = Tree(inputfile)
for node in input_tree.get_descendants():
if node.support < threshold and node.is_leaf() == False:
node.delete(preserve_branch_length=True)
Tree.write(input_tree, outfile=output_name)
if __name__ == '__main__':
parser = argparse.ArgumentParser(description="Collapse tree nodes below a certain threshold")
parser.add_argument('-f', help='Input tree file', required=True)
parser.add_argument('-t', help='Threshold for collapsing the nodes (float)', required=True, type=float)
parser.add_argument('-o', help='output tree file', required=True)
parser.add_argument('-v', help='verbose output', action="store_true")
args = parser.parse_args()
collapse_nodes(args.f, args.t, args.o) |
843e82e118041526099395e85faa8b0f66ab3a84 | zuodanlee/snake | /entities.py | 2,433 | 3.625 | 4 | from math import floor
import random
from main import *
def round_to_multiple(num, base):
return base * floor(num/base)
class Snake():
def __init__(self, x, y):
self.x = x
self.y = y
self.direction = "R"
self.true_direction = "R"
self.body = [(x, y, block_size, block_size), (x-block_size, y, block_size, block_size)]
def get_rect(self):
return (self.x, self.y, block_size, block_size)
def turn(self, direction):
if (direction == "L" and self.true_direction != "R") or \
(direction == "R" and self.true_direction != "L") or \
(direction == "U" and self.true_direction != "D") or \
(direction == "D" and self.true_direction != "U"):
self.direction = direction
def move(self, apple):
alive = True
if self.direction == "L":
self.x -= block_size
elif self.direction == "R":
self.x += block_size
elif self.direction == "U":
self.y -= block_size
elif self.direction == "D":
self.y += block_size
self.true_direction = self.direction
new_block = (self.x, self.y, block_size, block_size)
if not (0 <= self.x <= width-block_size) or \
not (0 <= self.y <= height-block_size) or \
self.check_collide(new_block):
alive = False
else:
if self.get_rect() == apple.get_pos():
self.eat(apple)
else:
self.body.pop()
self.body.insert(0, new_block)
return alive
def eat(self, apple):
apple.respawn(self)
def check_collide(self, new_block):
for block in self.body:
if new_block == block:
return True
return False
class Apple():
def __init__(self, snake):
snake_body = snake.body
self.x = None
self.y = None
while (self.x, self.y, block_size, block_size) in snake_body or \
self.x == None or \
self.x == width or \
self.y == height:
self.x = round_to_multiple(random.randint(0, width), block_size)
self.y = round_to_multiple(random.randint(0, height), block_size)
def get_pos(self):
return (self.x, self.y, block_size, block_size)
def respawn(self, snake):
self.__init__(snake)
|
5128b6d75cee6db905df53aee7d5a4ebea393329 | ks2019575001/python | /2.py | 238 | 3.859375 | 4 | abc = input("문자열 : ")
print("개별 문자 출력 :", end="")
for i in range(len(abc)):
print(abc[i], end="")
print()
print("역순 개별 문자 출력 :", end="")
for i in range(len(abc)-1,-1,-1):
print(abc[i], end="")
|
38808cc4b7daade88fb3021951d8a1b801337473 | mkruzil/extract | /extract.py | 1,063 | 3.765625 | 4 | '''
===========================================================================
Filename: extract.py
Description: Extracts tablular data from ASCII text copied off a web page
Author: Michael Kruzil (mkruzil@mikruweb.com)
Date Created: 7/21/2019 3:00 PM
===========================================================================
'''
import functions
#Convert the content in the file to a string variable
txt = functions.openTXT("content.txt")
#Step 1: Indicate the start and end markers of the table content in the string
start_marker = "Start extraction here"
end_marker = "End extraction here"
#Step 2: Extract the table content from the string
txt = functions.trimText(start_marker, end_marker, txt)
#Step 3: Convert the table content to a table array
rows = functions.convertWebTextToTable(txt)
#Step 4: Pop off the headings row
headings = functions.getHeadings(rows)
#Print the table data
print(headings)
print(rows)
#Save the table to a CSV file
functions.saveCSV(headings, rows, "results.csv")
|
855b17bfdfe1cff30ed4201c0b4a1f8617b2b437 | danitaanubhuti/PYTHON | /input-1.py | 224 | 4.375 | 4 | #TO INPUT A STRING AND DISPLAY IT
str=input("enter a sting")
print("the sring entered is: ",str)
m=int(input("enter an integer"))
x=float(input("enetr a fractional value"))
print("entered numbers are:\n n1=\n n2="m,x)
|
fb909b22063df39393ead3bc5c5d8dad38cb8a7c | jashingden/Python | /Python教材/example/EX07_01.py | 550 | 3.90625 | 4 | #-*-coding:UTF-8 -*-
# EX07_01.py
#
# 例外處理範例
#
num1 = 10
num2 = 0
nums = [1,3,5,7,9]
try:
#除以0,導致例外產生 ZeroDivisionError
print(num1/num2)
#使用沒有宣告過的變數 NameError
print(num1*num3)
#索引值超出範圍 IndexError
print(nums[100])
except ZeroDivisionError:
print('Error發生,除以0')
except NameError:
print('Error發生,使用沒有宣告過的變數')
except IndexError:
print('Error發生,索引值超出範圍')
except:
print('Error發生')
|
fc9bbc7bf8cce8375463a160a69597c6c8c906e1 | 8563a236e65cede7b14220e65c70ad5718144a3/python3-standard-library-solutions | /Chapter01/0031_re_fullmatch.py | 440 | 3.734375 | 4 | """
Listing 1.31
The fullmatch() method requires that the entire input string match
the pattern
"""
import re
def main():
text = "This is some text -- with punctuation"
pattern = "is"
print("Text :", text)
print("Pattern :", pattern)
m = re.search(pattern, text)
print("Search :", m)
s = re.fullmatch(pattern, text)
print("Full match :", s)
if __name__ == "__main__":
main()
|
fe82df835eb46e1dfb3d6341abc5762b8bbd844c | Servsobhagya/assignment | /asig13.py | 1,316 | 4.21875 | 4 | # f=open('new.txt','r')
# x=int(input("enter any:"))
# fd=f.readlines()
# while x:
# print(fd[-x])
# x=x-1
# f.close
# Write a Python program to count the frequency of words in a file.
# count=0
# f=open('new.txt','r')
# for line in f:
# words=line.split()
# count +=len(words)
# print(count)
#Write a Python program to copy the contents of a file to another file
# with open('new.txt','r') as f1:
# with open('txt.txt','w') as f2:
# for line in f1:
# f2.write(line)
#Write a Python program to combine each line from first file with the corresponding line in second file.
with open('new.txt','r')as f1:
with open('txt.txt','r')as f2:
for line1,line2 in zip(f1,f2):
print(line1+line2)
#Write a Python program to write 10 random numbers into a file. Read the file and then sort the numbers and then store it to another file.
import os
import random
random_list=[]
random_list1=[]
for x in range (100):
random_list.append(x)
random.shuffle(random_list)
with open('1.txt','w') as f1:
for x in range(10):
f1.write(str(random_list[x])+"\n")
os.remove('2.txt')
with open('1.txt','r+') as f1:
with open('2.txt','w') as f2:
random_list=f1.readlines()
for x in range(len(random_list1)):
random_list1[x]=int(random_list1[x])
random_list1.sort()
for x in random_list1:
f2.write(str(x)+"\n") |
1c96f6ca6044b16ba489615727f971207a638285 | chrylzzz/first_py | /day12/5.家具案例.py | 1,086 | 3.8125 | 4 | class Fur():
def __init__(self, name, area):
self.name = name
self.area = area
# def __str__(self):
# return f'家具名字:{self.name},家具面积:{self.area}'
class Home():
# 这是构造方法,构造的时候传入参数
def __init__(self, address, area):
self.area = area
self.address = address
# 剩余面积
self.free_area = area
# 家具列表
self.furs = []
def __str__(self):
return f'家具地址:{self.address},还剩下:{self.free_area},有那些家具:{self.furs}'
def add_fur(self, item):
# 该家具的面积 <=剩余的面积 ,可以添置
if item.area <= self.free_area:
# 这里注意为name,如果直接传入 item这个对象,好像item对象有_str_()方法也不toString
self.furs.append(item.name)
self.free_area -= item.area
else:
print('没地方啊')
fur = Fur('椅子', 10)
fur2 = Fur('桌子', 2)
home = Home('beij', 1000)
home.add_fur(fur)
home.add_fur(fur2)
print(home)
|
e6b761942bdd42553a1944fad7f4b92a8d13ef35 | Dongzi-dq394/leetcode | /python_solution/0270.py | 738 | 3.703125 | 4 | # Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def closestValue(self, root: TreeNode, target: float) -> int:
# Solution by myself: Recursion + Binary Search (40ms: 74.57%)
cand = [float('Inf'), None]
def helper(node):
if node:
diff = abs(target-node.val)
if diff<cand[0]:
cand[0], cand[1] = diff, node.val
if node.val<=target:
helper(node.right)
else:
helper(node.left)
helper(root)
return cand[1] |
b61ab75e388f257570538186c6c66725439f6280 | aadharna/Destiny | /OutlierDetectionandRemoval.py | 2,902 | 3.75 | 4 | import pandas as pd
import numpy as np
def normalize(df):
result = df.copy()
for feature_name in df.columns:
max_value = df[feature_name].max()
min_value = df[feature_name].min()
result[feature_name] = (df[feature_name] - min_value) / (max_value - min_value)
return result
#____________________________________________________________________________________
#____________________________________________________________________________________
#____________________________________________________________________________________
#DETERMINE OUTLIERS
df1 = pd.read_csv("batchUdacity_TOTAL.csv", index_col="Unnamed: 0")
df1.fillna(-1, inplace=True)
print(df1.head(), df1.shape)
# Display the outliers
outliers = []
for feature in df1.columns:
#Calculate Q1 (10th percentile of the data) for the given feature
Q1 = np.percentile(df1[feature], 10)
#Calculate Q3 (90th percentile of the data) for the given feature
Q3 = np.percentile(df1[feature], 90)
#Use the interquartile range to calculate an outlier step (1.5 times the interquartile range)
step = (Q3 - Q1) * (1.5)
print(Q1, Q3, step, " for features --", feature)
#print("Data points considered outliers for the feature, ", feature)
#display(df[~((df[feature] >= Q1 - step) & (df[feature] <= Q3 + step))])
outliers.append(df1[~((df1[feature] >= Q1 - step) & (df1[feature] <= Q3 + step))].index.values)
# print(outliers)
for arrays, names in zip(outliers, df1.columns):
print(names, len(arrays))
outlierdict = {}
outlierdict.clear()
highoutlierlist = []
for arrays in outliers:
for people in arrays:
if people in outlierdict.keys():
outlierdict[people] += 1
else:
outlierdict[people] = 1
for key in outlierdict.keys():
if outlierdict[key] > 2:
#print(key, outlierdict[key])
highoutlierlist.append(key)
print(len(highoutlierlist))
print(float(len(highoutlierlist)/df1.shape[0]))
outlierMatches = []
removal = []
previousMatch = 0
counter = 0
match = {}
#matches = []
temp = None
attributes = df1.columns.values.tolist()
print(len(attributes))
#attributes.remove("percentContribution")
for index, row in df1.iterrows():
currentMatch = int(row["matchId"])
if index in highoutlierlist:
if currentMatch not in outlierMatches:
outlierMatches.append(currentMatch)
continue
if not currentMatch == previousMatch:
counter += 1
match[currentMatch] = []
previousMatch = currentMatch
for index, row in df1.iterrows():
currentMatch = int(row["matchId"])
if currentMatch in outlierMatches:
removal.append(index)
good_data = df1.drop(df1.index[removal]).reset_index(drop=True)
good_data.to_csv("batchUdacity_CLEANED.csv")
|
de587de82722e858d758acf660ecd831e84be71d | MaciejKaca/Python | /List.py | 326 | 4.09375 | 4 | def filter_list(list):
new_list=[]
for element in list:
if type(element) is int:
new_list.insert(len(new_list), element)
return new_list
def filter_list1(list): #using list comprehensions
return [element for element in list if type(element) is int]
print(filter_list1([12, "A", 3, "d"])) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.