blob_id
stringlengths 40
40
| repo_name
stringlengths 6
108
| path
stringlengths 3
244
| length_bytes
int64 36
870k
| score
float64 3.5
5.16
| int_score
int64 4
5
| text
stringlengths 36
870k
|
---|---|---|---|---|---|---|
44408436b8299a52ca3c8849b70e6b81fca2b066 | woongsup123/jigsaw-solver | /node.py | 1,799 | 3.65625 | 4 | class Node:
def __init__(self, node_number):
self.rotate_sum = 0
self.directions = [-1, -1, -1, -1]
self.location = [False, False, False, False] # NE, SE, SW, NW
self.node_number = node_number
def print_node(self):
print(self.directions)
print(self.rotate_sum)
print(self.location)
def get_direction_at(self, num):
return self.directions[num]
def get_rotate_sum(self):
return self.rotate_sum
def get_directions(self):
return self.directions
def get_num_of_connected_edges(self):
sum = 0
for direction in self.directions:
if direction != -1:
sum += 1
return sum
def get_location_index(self):
i = 0
while not self.location[i]:
i += 1
return i
def get_node_number(self):
return self.node_number
def is_NE(self):
return self.location[0]
def is_NW(self):
return self.location[3]
def set_north(self, north):
self.directions[0] = north
def set_east(self,east):
self.directions[1] = east
def set_south(self,south):
self.directions[2] = south
def set_west(self,west):
self.directions[3] = west
def set_location(self, index):
self.location[index] = True
def add_rotate_sum(self, num):
self.rotate_sum += num
def rotate_once(self):
self.directions = self.directions[-1:] + self.directions[:-1]
def set_connection(self, direction, piece):
if direction == 0:
self.set_north(piece)
elif direction == 1:
self.set_east(piece)
elif direction == 2:
self.set_south(piece)
else:
self.set_west(piece)
|
7635fb1160dd0e034e84c1f6610b496705f90ede | chenyang929/Problem-Solving-with-Algorithms-and-Data-Structures-using-Python-Notes | /04 递归/to_str.py | 264 | 3.578125 | 4 | # to_str.py
def to_str(n, base):
cover_str = '0123456789ABCDEF'
if n < base:
return cover_str[n]
else:
return to_str(n//base, base) + cover_str[n%base]
if __name__ == '__main__':
print(to_str(20, 8))
print(to_str(10 ,2))
|
0404323c3a9a60789a53571afc4750d3ad6d93c7 | kailunfan/lcode | /107.二叉树的层次遍历-ii.py | 1,424 | 3.921875 | 4 | #
# @lc app=leetcode.cn id=107 lang=python
#
# [107] 二叉树的层次遍历 II
#
# https://leetcode-cn.com/problems/binary-tree-level-order-traversal-ii/description/
#
# algorithms
# Easy (64.90%)
# Likes: 235
# Dislikes: 0
# Total Accepted: 58.7K
# Total Submissions: 89.6K
# Testcase Example: '[3,9,20,null,null,15,7]'
#
# 给定一个二叉树,返回其节点值自底向上的层次遍历。 (即按从叶子节点所在层到根节点所在的层,逐层从左向右遍历)
#
# 例如:
# 给定二叉树 [3,9,20,null,null,15,7],
#
# 3
# / \
# 9 20
# / \
# 15 7
#
#
# 返回其自底向上的层次遍历为:
#
# [
# [15,7],
# [9,20],
# [3]
# ]
#
#
#
# @lc code=start
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def levelOrderBottom(self, root):
"""
:type root: TreeNode
:rtype: List[List[int]]
"""
res,stack = [],[root]
while stack:
tmp_stack,tmp_res = [], []
for i in stack:
if i:
tmp_res.append(i.val)
tmp_stack.extend([i.left,i.right])
if tmp_res:
res.insert(0,tmp_res)
stack = tmp_stack
return res
# @lc code=end
|
a2f855aa29da3b4b8e4a36b44e714f3924b66eab | droconnel22/QuestionSet_Python | /leet_code/hash_maps/anagram.py | 2,044 | 4.3125 | 4 | #!/bin/python3
import math
import os
import random
import re
import sys
"""
Two words are anagram of one another if their letters can be
re-arranged to form the other word.
In this challenge you will be given a string.
YOu must split it into two contigous substrings, then
determine the minimum number of characters to change
to make the two substring into anagrams of one another.
Example:
abccde
1. break it into two parts
abc
cde
Note that all letters have been used
the substrings are contigous and their lenghts are equal
you can change a and b in the first substring to d and e
to have dec and cde
which are anagram
Here two changes were necessary
Description
Complete the anagram function in the editor below
It should return the min number of character to change to
make the words anagrams or -1 if its not possible
takes in a string:
Sample Input
6
aaabbb
ab
abc
mnop
xyyx
xaxbbbxx
Sample Output
3
1
-1
2
0
1
Explanation:
Test Case #01: We split s into two strings S1='aaa' and S2='bbb'
we have to replace all three of the characters from the first string
to make the strings anagrams.
Test case #2: ab
you have to replace 'a' with 'b' which will generate 'bb'
test case #3: abc
it is not possible for two string of unequal of length to be
anagrams of one another
test csae #4: mnop
mn op
2?
test case #5:
xyyx
xy and yx are already anagrams of one another
Test Case #06
xaxb bbxx
1
a-> b
Revisit case 1
aaa
bbb
a:3
b:0
a:0
b:3
"""
# Complete the anagram function below.
def anagram(s):
if(len(s) % 2 != 0):
return -1
a = s[:len(s)//2]
b = s[len(s)//2:]
count = 0
for letter in list(string.ascii_lowercase):
diff = a.count(letter)-b.count(letter)
if diff > 0:
count+=diff
return count
if __name__ == '__main__':
fptr = open(os.environ['OUTPUT_PATH'], 'w')
q = int(input())
for q_itr in range(q):
s = input()
result = anagram(s)
fptr.write(str(result) + '\n')
fptr.close()
|
ddae4cf870ada38f5688099a4d2cabd4921fe8cf | xent3/Python | /Ödev1/Ödev_8.py | 635 | 4.21875 | 4 | """
Kullanıcıdan aldığınız bir sayının "Armstrong" sayısı olup olmadığını bulmaya çalışın.
Örnek olarak, Bir sayı eğer 4 basamaklı ise ve oluşturan rakamlardan herbirinin 4. kuvvetinin toplamı( 3 basamaklı sayılar için 3.kuvveti ) o sayıya eşitse bu sayıya "Armstrong" sayısı denir.
Örnek olarak : 1634 = 1^4 + 6^4 + 3^4 + 4^4
"""
sayı=input("Lütfen sayı giriniz:")
liste = list(sayı)
print(liste)
üst = int(len(liste))
toplam = 0
for i in liste:
toplam = toplam + (int(i) ** üst)
if(int(toplam) == int(sayı)):
print("Armstrong sayısıdır")
else:
print("Değildir")
|
d6b9df9369de4bdfa9159e410451e614b48a23c8 | Beomsudev/Git | /DAY10/P1/02_arrayDimShape.py | 846 | 3.71875 | 4 | # 02_arrayDimShape.py
# 배열의 크기(dimension)와 형상(shape)
import numpy as np
# ndarray : n(정수) d(차원) array(행렬/배열)
data = np.array([[1,2,3], [4,5,6]])
data2 = np.array([[1,2,3], [4,5,6], [7,8,9]])
print(type(data))
print('rank(차원) : ', data.ndim) # ndim 속성 이라고함
print('형상 : ', data.shape) # shape 속성
print('몇행? : ', data.shape[0])
print('몇열? : ', data.shape[1])
# int8, int16, int32, float64
print('자료형 : ', data.dtype) # dtype 속성
print(data)
print(data[0][1], data[1][1], data[1][2])
print('-' * 30)
print( data * data)
print('-' * 30)
mylist = [1, 2]
print(mylist+mylist)
print('-' * 30)
print( data * 10)
print('-' * 30)
print( data + data)
print('-' * 30)
print( 1 / data)
print('-' * 30)
print( data ** 0.5) # 루트
print('-' * 30) |
1112a4063c80da87ac644f33943ae62177281c04 | projeto-de-algoritmos/PD_01Knapsack | /knapsack.py | 874 | 3.65625 | 4 | # -*- coding: utf-8 -*-
def knapSack(W, wt, val, n):
K = [[0 for x in range(W + 1)] for x in range(n + 1)]
for i in range(n + 1):
for w in range(W + 1):
if i == 0 or w == 0:
K[i][w] = 0
elif wt[i-1] <= w:
K[i][w] = max(val[i-1] + K[i-1][w-wt[i-1]], K[i-1][w])
else:
K[i][w] = K[i-1][w]
return K[n][W]
if __name__ == '__main__':
print("Insira os valores de cada item intercalado por espaços: ")
val = list(map(int, input().split()))
# val = [60, 100, 120]
print("Insira os peso de cada item intercalado por espaços: ")
wt = list(map(int, input().split()))
W = int(input("Insira a capacidade da mochila: "))
n = len(val)
print("A valor máximo que se pode carregar na mochila é: {}".format(knapSack(W, wt, val, n))) |
80577190a80a442882851864dd12fde02219bb10 | TEAMLAB-Lecture/basic-math-ebbunnim | /basic_math.py | 440 | 3.625 | 4 | def get_greatest(number_list):
return max(number_list)
def get_smallest(number_list):
return min(number_list)
def get_mean(number_list):
return sum(number_list)/len(number_list)
def get_median(number_list):
number_list.sort()
l=len(number_list)
if l%2:
return number_list[l//2]
a,b=number_list[l//2-1],number_list[l//2]
return (a+b)/2
print(get_mean([54, 56, 30, 12, 58, 25, 17, 48, 80, 23])) |
479fcc95db51207baff93d75463111bdb204866e | gcolson11/Capstone_Books | /collaborative_filtering.py | 14,063 | 3.6875 | 4 | # Code for building the book recommendation system and Web App
import pandas as pd
import numpy as np
from math import sqrt
from statistics import pstdev
import random
import streamlit as st
ratings_file = 'Data/ratings_cleaned.csv'
books_file = 'Data/books_cleaned.csv'
#ratings_file = '/Users/gregoryolson/Documents/Data Science CT/Capstone/Capstone_Books/Data/ratings_cleaned.csv'
#books_file = '/Users/gregoryolson/Documents/Data Science CT/Capstone/Capstone_Books/Data/books_cleaned.csv'
ratings = pd.read_csv(ratings_file)
books = pd.read_csv(books_file)
st.set_page_config(initial_sidebar_state="expanded")
# create collaborative filtering class
class Collaborative_Filtering:
def __init__(self, books, ratings, user_input):
self.books = books
self.ratings = ratings
self.user_input = user_input
self.books_cf = None
self.input = None
self.new_books_cf = None
self.genre_list = None
self.user_subset_group = None
self.sim_dict = None
self.pearson_df = None
self.top_users_rating = None
self.recommendation_df = None
self.recommendation = None
# make dataframe with only essential columns, convert year column to type int and rename
def books_cfdf(self):
self.books_cf = self.books[['id', 'title', 'authors', 'original_publication_year', 'genre1', 'genre2', 'genre3', 'small_image_url']]
self.books_cf['original_publication_year'] = self.books_cf['original_publication_year'].astype(int)
self.books_cf = self.books_cf.rename(columns={'original_publication_year': 'year'})
self.ratings = self.ratings.rename(columns={'book_id': 'id'})
return self.books_cf
# filter the books by title, merge df's and drop year column
def user_input_filter(self):
input_id = self.books_cfdf()[self.books_cfdf()['title'].isin(self.user_input['title'].tolist())]
self.input = pd.merge(input_id, self.user_input)
self.input = self.input.drop('year', axis=1).reset_index(drop=True)
return self.input
# remove input books from books_cf
def remove_input_books(self):
input_book_list = self.user_input_filter()['id'].tolist()
self.new_books_cf = self.books_cfdf()[~self.books_cfdf()['id'].isin(input_book_list)]
return self.new_books_cf
# create a list of genres
def add_genres(self):
self.genre_list = []
id_list = self.user_input_filter()['id'].tolist()
# for loop that appends unique genre tags to genre_list
for item in id_list:
temp = self.books.loc[self.books['id'] == item]
for i in range(24,27):
a = temp.iloc[0, i]
if a not in self.genre_list:
self.genre_list.append(a)
return self.genre_list
##NEW STEP - make average rating for each genre among user inputs
def genre_ratings(self):
avg_genre_rating = []
ag = self.add_genres()
for item in ag:
uifs = self.user_input_filter()
temp_gdf = uifs.loc[(uifs['genre1'] == item) | (uifs['genre2'] == item) | (uifs['genre3'] == item)]
c = temp_gdf['rating'].mean()
avg_genre_rating.append(c)
self.genre_rating_dict = {ag[i]: avg_genre_rating[i] for i in range(len(ag))}
return self.genre_rating_dict
# filter users that have read books that the input has also read
def user_subset(self):
user_subset = self.ratings[self.ratings['id'].isin(self.user_input_filter()['id'].tolist())]
self.user_subset_group = user_subset.groupby(['user_id'])
# sort so that users with book most in common with the input will have priority
self.user_subset_group = sorted(self.user_subset_group, key=lambda x: len(x[1]), reverse=True)
# limit number of users we look through to 100
self.user_subset_group = self.user_subset_group[0:100]
return self.user_subset_group
# calculate the pearson correlation or cosine similarity
def correlation(self):
self.sim_dict = {}
std = pstdev(self.user_input_filter()['rating'].tolist())
# for loop that calculates Pearson correlation and stores values in above dict
for name, group in self.user_subset():
group = group.sort_values(by='id')
self.input = self.user_input_filter().sort_values(by='id')
num_ratings = len(group)
# store books from input that share book id with books in each group in df
temp_df = self.input[self.input['id'].isin(group['id'].tolist())]
# store both ratings in list for calculations
rating_list = temp_df['rating'].tolist()
group_list = group['rating'].tolist()
if std == 0:
# calculate cosine similarity
cos_sim = np.dot(rating_list, group_list)/(np.linalg.norm(rating_list)*np.linalg.norm(group_list))
self.sim_dict[name] = cos_sim
else:
# calculate each component of Pearson correlation
Sxx = sum([i**2 for i in rating_list]) - (sum(rating_list)**2 / float(num_ratings))
Syy = sum([i**2 for i in group_list]) - (sum(group_list)**2 / float(num_ratings))
Sxy = sum([i*j for i, j in zip(rating_list, group_list)]) \
- (sum(rating_list) * sum(group_list) / num_ratings)
# calculate Pearson corr if Sxx and Syy not 0, else set = 0
if Sxx != 0 and Syy != 0:
self.sim_dict[name] = Sxy/sqrt(Sxx*Syy)
else:
self.sim_dict[name] = 0
return self.sim_dict
# convert dictionary to dataframe
def to_df(self):
self.sim_df = pd.DataFrame.from_dict(self.correlation(), orient='index')
self.sim_df.columns = ['similarity_index']
self.sim_df['user_id'] = self.sim_df.index
self.sim_df.index = range(len(self.sim_df))
return self.sim_df
# get top 50 similar users, merge top_users with ratings, then multiply user similarity by user ratings
def top_users(self):
top_users = self.to_df().sort_values(by='similarity_index', ascending=False)[0:50]
self.top_users_rating = top_users.merge(self.ratings, left_on='user_id', right_on='user_id', how='inner')
self.top_users_rating['weighted_rating'] = self.top_users_rating['similarity_index'] * self.top_users_rating['rating']
return self.top_users_rating
# method that calculates weighted average rec score
def rec_df(self):
# apply a sum to the top_users after grouping by user_id
top_users_sum = self.top_users().groupby('id').sum()[['similarity_index','weighted_rating']]
top_users_sum.columns = ['sum_similarity_index','sum_weighted_rating']
# find the weighted average and sort values in order of highest weights descending
self.recommendation_df = pd.DataFrame()
self.recommendation_df['weighted average rec score'] = top_users_sum['sum_weighted_rating'] \
/ top_users_sum['sum_similarity_index']
# return df of recommendations sorted by weighted average rec score
self.recommendation_df['id'] = top_users_sum.index
self.recommendation_df = self.recommendation_df.sort_values(by='weighted average rec score', ascending=False)
return self.recommendation_df
# drop id column, return final recommendation
def recommendations(self):
rib = self.remove_input_books()
recdf = self.rec_df()
fives = recdf.loc[recdf['weighted average rec score'] == 5]
if len(fives) > 10:
self.recommendation = rib.loc[rib['id'].isin(recdf['id'].head(len(fives)).tolist())]
count = 0
scores = []
genre_df = self.add_genres()
gr = self.genre_ratings()
for index, row in self.recommendation.iterrows():
if row['genre1'] in genre_df:
count += 5 * (gr[row['genre1']] - 3)
if row['genre2'] in genre_df:
count += 3 * (gr[row['genre2']] - 3)
if row['genre3'] in genre_df:
count += 1 * (gr[row['genre3']] - 3)
scores.append(count)
count = 0
self.recommendation['genre_score'] = scores
self.recommendation = self.recommendation.sort_values(by=['genre_score', 'id'], ascending=[False, True])
self.recommendation = self.recommendation.drop(['genre1', 'genre2', 'genre3', 'genre_score'], axis=1)
self.recommendation = self.recommendation.head(10)
else:
self.recommendation = rib.loc[rib['id'].isin(recdf['id'].head(10).tolist())]
self.recommendation = self.recommendation.drop(['genre1', 'genre2', 'genre3'], axis=1)
self.recommendation = self.recommendation.head(10)
return self.recommendation
# method that returns each url of the user inputted books
def book_images(self):
input_df = pd.DataFrame.from_dict(self.user_input)
input_df = self.books[self.books['id'].isin(self.user_input_filter()['id'])]
image_list = input_df['image_url'].tolist()
return image_list
# Make Web App
def app():
# Write in title and first instructions on Web App
st.title('Read-y Books Recommender')
st.write("Welcome! To receive book recommendations, fill out the information in the left sidebar. \
When you are finished rating, click the buttom that appears to receive your recommendations. \
You can also select the option below to have a recommendation randomly generated.")
choice = st.radio(' ', ['Input your own book ratings', 'Or randomly generate a recommendation'])
# create empty list to store pairs of book title and rating
d = []
button = False
# if user chooses to input their own data
if choice == 'Input your own book ratings':
# let's user choose number of books they'd like to rate
st.sidebar.write('---')
st.sidebar.title('Rate books below')
j = st.sidebar.number_input('How many books would you like to rate?', value=3, min_value=1, max_value=50, step=1)
st.sidebar.write('---')
# Initialize first keys for selectbox
keys1, keys2 = 0, 1
# first element of dropdown list is a placeholder value '-'
title_list = ['-'] + books['title'].tolist()
# for loop that appends book title and rating to list and then appends list to dictionary at every iteration
for i in range(j):
b = []
# user selects book title
words = 'Select book ' + str(i+1)
book_choice = st.sidebar.selectbox(words, title_list, key=keys1)
keys1 += 2
if book_choice == '-':
pass
else:
b.append(book_choice)
# user selects rating
rating_choice = st.sidebar.slider('Rating', min_value=0, max_value=5, value=0, key=keys2)
keys2 += 2
st.sidebar.markdown('---')
if rating_choice == 0:
pass
else:
b.append(rating_choice)
# if both title and rating are filled in, append these inputs to d
if len(b) == 2:
d.append(b)
# create dataframe of user inputs to be used in collaborative filtering
if len(d) == j: # ensure that all boxes are filled in
button = st.sidebar.button('Click to generate recommendations')
if button == True:
user_input = pd.DataFrame(d, columns=['title', 'rating'])
line = 'You rated ' + str(j) + ' books'
st.markdown('---')
st.subheader(line)
st.write(' ')
else:
pass
# if user chooses to have books randomly chosen for them
elif choice == 'Or randomly generate a recommendation':
# number of books we will rate
button = True
j = 5
# for loop that randomly selects 5 books and gives them a rating of 4 or 5
for i in range(5):
b = []
b.append(random.choice(books['title'].tolist()))
b.append(random.choice([1,2,3,4,5]))
d.append(b)
# create dataframe of user inputs to be used in collaborative filtering
user_input = pd.DataFrame(d, columns=['title', 'rating'])
st.markdown('---')
st.subheader("We rated 5 books")
st.write(' ')
# continue with making recommendation and displaying in app
if button == True:
# instantiate Collaborative_Filtering class
cf = Collaborative_Filtering(books, ratings, user_input)
bi = cf.book_images()
uif = cf.user_input_filter()
# display book cover, rating, title and author of input books
for i in range(j):
col1, mid, col2, mid, col3 = st.beta_columns([1,2,1,1,20])
with col1:
st.image(bi[i], width=60)
with col2:
st.write(str(uif.values[i][7])) #6
with col3:
st.write(uif.values[i][1], '-', uif.values[i][2])
st.markdown('---')
st.subheader('Based on the selected books here are some recommendations:')
st.write(' ')
#images = cf.rec_images()
recs = cf.recommendations()
# display book cover, recommendation ranking, title and author of book recommendations
for i in range(len(recs)):
col1, mid1, col2, mid2, col3 = st.beta_columns([1,2,1,1,20])
with col1:
st.image(recs.values[i][-1], width=60) #images[i]
with col2:
st.write(str(i+1))
with col3:
st.write(recs.values[i][1], '-', str(recs.values[i][2]))
|
26614f5cbe266818c5f34b536b9f921c922a18d2 | WSMathias/crypto-cli-trader | /innum.py | 2,012 | 4.5625 | 5 | """
This file contains functions to process user input.
"""
# return integer user input
class Input:
"""
This class provides methods to process user input
"""
def get_int(self, message='Enter your number: ', default=0, warning=''):
"""
Accepts only integers
"""
hasInputNumbers = False
while hasInputNumbers==False:
try: # try to convert user input into a integer number
userInput = input(message)
if userInput is '':
if default == 0:
message = message+'\r'
continue
else:
return default
userInput = int(userInput)
hasInputNumbers=True
return userInput
except ValueError: # if it gives a ValueError, return to line 2!
print("[!] invalid input try again")
# return floating point user input
def get_float(self, message='Enter your number: ', default=0,warning=''):
"""
Accepts integer and floating point numbers
"""
hasInputNumbers = False
while hasInputNumbers==False:
try: # try to convert user input into a floating number
userInput = input(message)
if userInput is '':
if default == 0:
continue
else:
return default
userInput = float(userInput)
hasInputNumbers=True
return userInput
except KeyboardInterrupt :
raise
except ValueError: # if it gives a ValueError, return to line 2!
print("[!] invalid input try again")
def get_coin(self, message='Enter Coin symbol : ', default='', warning=''):
"""
Accepts Coin Symbol
"""
return input(message)
#TODO: Logic need to be implimented |
d9501dc4070b15277b7742828329f656887c9199 | IBordfeld/ToDoList | /ToDoList.py | 2,228 | 4 | 4 | # Isaac Bordfeld and Karley Conroy
# ToDoList
class ToDoList:
def __init__(self):
self.ToDo = {}
self.OpenList()
# function used to add a new list in the program
def addParentList(self, ListName):
self.ToDo[ListName] = list()
# function used to remove a list from a program
def removeParentList(self, ListName):
try:
del self.ToDo[ListName]
except:
# will print if the list name entered doesnt exist or it is spelt wrong
print("Not a current list, make sure you have correct spelling and capitalization!")
# function that will add a task to an existing list
def addToDoList(self, ListName, task):
self.ToDo.get(ListName).append(task)
# function that will remove a task from an existing list
def removeFromToDoList(self, ListName, task):
try:
self.ToDo.get(ListName).remove(task)
except:
#will print if the item is not in the list or it is spelt incorrectly
print("\nItem not found in list! Make sure capitalization is correct!\n")
#used to save the list
def SaveLists(self):
#writes to the text file
fptr = open("ToDo.txt", "w")
for listName, task in self.ToDo.items():
fptr.write(listName + ":")
run_time = len(task)
for i in range(run_time - 1):
fptr.write(task[i] + ",")
fptr.write(task[-1] + "\n")
fptr.close()
print("List saved! Have a good day!")
# used to open the text file
def OpenList(self):
# will read from the text
fptr = open("ToDo.txt", "r")
for ToDo in fptr.readlines():
tempList = ToDo.split(":")
tempList = [tempList[0], tempList[1].strip("\n").split(",")]
self.ToDo[tempList[0]] = tempList[1]
fptr.close()
# will print the context of the list
def printList(self):
listString = ""
for name, listItems in self.ToDo.items():
listString += name + ":\n"
for task in listItems:
listString += f"- {task}\n"
return listString[:-1]
def getList(self):
return self.ToDo
|
b55508a6427a7646b6397e3e9a7e5a4c686658c7 | chandramohank/Logical-Programes | /Python/findthesecondlowest.py | 371 | 3.75 | 4 |
import sys
def findtheSecondLowest(inputarray):
first,second=sys.maxsize ,sys.maxsize
for i in range(0,len(inputarray)):
if inputarray[i] < first:
second=first
first=inputarray[i]
elif inputarray[i]<second and inputarray[i]!=first:
second=inputarray[i]
return second
findtheSecondLowest([2,5,3,7,4])
|
a738bb798113738fe937e80c71d20eae2ce194fb | cmwright12/QED-promoter_prediction | /Python/Sample_scripts/sample_script.py | 757 | 4.40625 | 4 | # defining variables
#x = 40
#city = "Jackson"
#fruits = ["fruits", 8, "abc", x]
#print(x)
#print(city)
#print(fruits)
# lists versus sets
#mylist = [1, 2, 2, 7, 3, 8, 2, 7]
#print(mylist)
#print(len(mylist))
#print(type(mylist))
#myset = set(mylist)
#print(myset)
#print(len(myset))
#print(type(myset))
# Playing with lists
mylist = [1, 2, 3, 4, 5, 6, 7, 8]
print(mylist)
# element in 3-rd position; index starts at 0
print(mylist[2])
# elements in positions 4-7
print(mylist[4:8])
print(mylist[4:10])
# Playing with strings
mystring = "Alexander Reed"
print(mystring)
print(mystring[0])
print(mystring[:10])
# last element
print(mystring[-1])
# last name
print(mystring[-4:])
# you can add strings
first = "Alexander"
last = "Reed"
print(first + " " + last)
|
ef4c4b85636ff0aaeb1475e9b3da912949ad6996 | Vijf/blockathon | /var/PyBlockchain-master/PyBlockchain/baseblock.py | 1,644 | 3.5 | 4 | """Base classes for all objects."""
from hashlib import sha256
class BaseBlock(object):
"""base block"""
@staticmethod
def calculate_hash_block(unverified_block):
"""
a nonce "seals" a block to the blockchain.
parameters
----------
unverified_block : Block object
refers to a block that has not yet been added to the blockchain. we
will generate an acceptable block hash for new block.
returns
-------
block_hash: hash
representing hash of new block, satisfying proof of work conditions.
"""
msg = unverified_block.prev_hash + unverified_block.root_hash + str(unverified_block.nonce)
block_hash = BaseBlock.generate_block_hash(msg)
while not BaseBlock.is_proof_of_work(block_hash):
unverified_block.nonce += 1 # increment until block hash is satisfactory
msg = unverified_block.prev_hash + unverified_block.root_hash + str(unverified_block.nonce)
block_hash = BaseBlock.generate_block_hash(msg)
return block_hash
@staticmethod
def generate_block_hash(message):
return sha256(message).hexdigest()
@staticmethod
def is_proof_of_work(hash_block):
"""
in this toy example, a valid block hash will start with 0. this condition
is known as "proof of work."
parameter
---------
hash_block : str
representing hex digest
returns
-------
boolean, whether hash_output is acceptable or not.
"""
return hash_block[0] is "0"
|
a9aeb4a7acb0524aa03d249d039bfc27e5f658ce | franciscoguemes/python3_examples | /advanced/tkinter/40_place_example.py | 1,657 | 4.34375 | 4 | #!/usr/bin/python3
# The place layout manager places the widgets at the specific position you want.
# Example inspired from: https://www.youtube.com/watch?v=D8-snVfekto&t=1479s
# For an in-detail explanation about place visit: https://effbot.org/tkinterbook/place.htm
import tkinter
HEIGHT = 700
WIDTH = 800
window = tkinter.Tk()
window.title("Using place()")
canvas = tkinter.Canvas(window, height=HEIGHT, width=WIDTH)
canvas.pack()
frame = tkinter.Frame(window,bg="#80c1ff")
# On the X axis of the window, the frame will have:
# 10% margin on the left
# it will take 80% of the width
# 10% margin on the right --> 100 - 10 -80 = 10
# On the Y axis of the window, the frame will have:
# 10% margin on top
# It will take 50% of the height
# 40% margin on the bottom --> 100 - 10 - 50 = 40
frame.place(relx=0.1,rely=0.1, relwidth=0.8, relheight=0.5)
# The rest of the items in the application are positioned relatively to the frame
button = tkinter.Button(frame,text="Test button", bg="gray")
# On the X axis of the frame, the button will have:
# 0% margin on the left
# it will take 25% of the frame's width
# 75% margin on the right --> 100 - 0 -25 = 75
# On the Y axis of the frame, the button will have:
# 0% margin on top
# It will take 25% of the frame's height
# 75% margin on the bottom --> 100 - 0 -25 = 75
button.place(relx=0, rely=0, relwidth=0.25, relheight=0.25)
label = tkinter.Label(frame, text="This is a label", bg="yellow")
label.place(relx=0.3, rely=0, relwidth=0.45, relheight=0.25)
entry = tkinter.Entry(frame, bg="green")
entry.place(relx=0.8, rely=0, relwidth=0.2, relheight=0.2)
window.mainloop() |
ff339003d1f00ab402d33dbbed22ed1d48e7db81 | anobhama/Intern-Pie-Infocomm-Pvt-Lmt | /Array/ArrInMatrix.py | 216 | 3.8125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Tue Aug 11 10:49:35 2020
@author: Anobhama
"""
#array using matrix function
from numpy import *
arr1=array([[1,2,3,4,9,0],[5,6,7,8,1,2]])
arr2=matrix(arr1)
print("array",arr2)
|
af0f8fbfce6070e42b64c6d24daa67ca4673988f | balamini-dev/exercices_python | /LOTO_Version 1 (sans fonction) - Partie 1 fonctionnel.py | 756 | 3.640625 | 4 | import random
grille_visiteur=[0]*6
for i in range (len(grille_visiteur)):
numero_visiteur = int(input("veuillez entrer 1 numéro compris entre 1 et 49 : "))
grille_visiteur[i]= numero_visiteur
print("Votre grille est : ")
print(grille_visiteur)
grille_loto=[0]*6
for i in range (len(grille_loto)):
grille_loto[i] = random.randint(1, 9)
print(grille_loto)
grille_final =[0]*6
for i in range (len(grille_visiteur)):
if grille_visiteur[i] in grille_loto:
grille_final[i]=grille_visiteur[i]
print(grille_final)
print("Vous avez trouvé le ou les numéros : ")
for i in range(len(grille_final)):
if grille_final[i]!=0:
print(grille_final[i])
|
5e8e140326002d4ad6d4c999ce947f067a326965 | thanh-falis/Python | /bai__54/Parameter.py | 437 | 3.53125 | 4 | """
- Python hỗ trợ parameter mặc định khi khai báo hàm
- Hàm print() thường dùng cũng có parameter mặc định
"""
def fl(n, m = 0):
s = 0
for i in range(1, n + m, 1):
s += 1
return s
print(fl(5))
print(fl(5, 1))
def fl2(n, m = 1, k = 2):
s = 0
for i in range(1, m+n+k, 1):
s += i
return s
print("*"*30)
print(fl2(5))
print(fl2(5, 3))
print(fl2(5, 3, 1))
print(fl2(5, k=4))
|
f918c0ff34fde19b1e2de29cec5d62c11ed55de6 | Tejagani/cricket | /tkint5.py | 1,040 | 3.703125 | 4 | import tkinter as tk
root=tk.Tk()
v=tk.IntVar()
def test():
if v.get()==1:
print("python selected")
elif v.get()==2:
print("perl selected")
b1=tk.Button(root,
text="find",
padx=40,
command=test)
l1=tk.Label(root,
text="choose a programming language",
justify=tk.LEFT,
padx=20)
l1.pack()
l2=tk.Label(root,
text="",
justify=tk.CENTER,
font="20",
padx=20)
l1.pack()
r1=tk.Radiobutton(root,
text="python",
padx=20,
variable=v,
value=1)
r1.pack(anchor=tk.W)
r2=tk.Radiobutton(root,
text="perl",
padx=20,
variable=v,
value=2)
r2.pack(anchor=tk.W)
b1.pack(anchor=tk.W)
l2.pack(anchor=tk.W)
root.mainloop()
|
498ac593e31603e23b349c16abf26770265d7be5 | Killerpol/PC2 | /p1.py | 288 | 4.0625 | 4 | x = int(input("Ingrese una coordenada x"))
y = int(input("Ingrese una coordenada y"))
##Importamos libreria math para hacer funcionar el math.sqrt que seria raiz cuadrada.
import math
##Posicion cero o origen
x0 = 0
y0 = 0
distancia = math.sqrt( (x-x0)**2 +(y-y0)**2 )
print (distancia) |
5dc7330050df4a4bf23049151d356aee27542480 | hansen487/CS-UY1114 | /Fall 2016/CS-UY 1114/HW/HW3/hc1941_hw3_q2.py | 629 | 3.828125 | 4 | """
Name: Hansen Chen
Section: EXB3
netID: hc1941
Description: Program that computes how much customer pays
"""
item1=int(input("Enter price of first item: "))
item2=int(input("Enter price of second item: "))
clubcard=str(input("Does the customer have a club card? (Y/N): "))
tax=float(input("Enter tax rate, e.g. 5.5 for 5.5% tax: "))
total=item1+item2
print("Base price =",total)
if (item1>item2):
item2=item2/2
else:
item1=item1/2
total=item1+item2
if (clubcard=='y'):
total=total*0.9
print("Price after discounts =",total)
tax=tax/100
tax=1+tax
total=total*tax
total=round(total, 2)
print("Total price =",total) |
2daf5d102fc9b1b124d21e3b202d5bce63b9861f | samyunwei/LearnPython | /hotel.py | 777 | 3.59375 | 4 | # -*-coding:utf-8 -*-
# File Name: hotel.py
# Author: Sam
# mail: [email protected]
#########################################################################
#!/usr/bin/env python
class HotelRoomClac(object):
'Hotel room rate calculator'
def __init__(self,rt,sales=0.085,rm=0.1):
''''HotelRoomClac default argument:
sales tax == 8.5% and room tax == 10%'''
self.salesTax = sales
self.roomTax = rm
self.roomRate = rt
def calcTotal(self,days=1):
'Calculate total;default to daily rate'
daily = round((self.roomRate * (1+self.roomTax + self.salesTax)),2)
return float(days) * daily
sfo =HotelRoomClac(299)
print sfo.calcTotal()
print sfo.calcTotal(2)
sea = HotelRoomClac(189,0.086,0.058)
print sea.calcTotal(4)
|
b72555a9018c0bfa330a193ad5cc3d8d0e0b0c57 | pogross/bitesofpy | /75/cal.py | 549 | 3.921875 | 4 | import re
from typing import Dict
def get_weekdays(calendar_output: str) -> Dict[int, str]:
"""Receives a multiline Unix cal output and returns a mapping (dict) where
keys are int days and values are the 2 letter weekdays (Su Mo Tu ...)"""
weekday_names = calendar_output.splitlines()[1].split()
weeks = [re.findall(r"[0-9]+", line) for line in calendar_output.splitlines()[2:]]
weekday_mapping = {
int(day): weekday for week in weeks for day, weekday in zip(week, weekday_names)
}
return weekday_mapping
|
52f6d74d26fd0be5e86adc7818557e337898d6ee | Santos1000/Curso-Python | /PYTHON/pythonDesafios/desafio072.py | 587 | 3.9375 | 4 | cont = ('zero' ,'um' ,'dois' ,'tres' ,'quatro' ,'cinco' ,'seis' ,
'sete' ,'oito' ,'nove' ,'dez' ,'onze' ,'doze' ,'treze' ,
'catorze' ,'quinze' ,'desesseis' ,'desessete' ,'desoito','vinte')
resp =' '
while True:
numero = int(input(' Digite um número entre 0 e 20: '))
if 0 <= numero <=20:
break
print('Tente novamente', end='.')
print(f'Você digitou o número {cont[numero]}')
resp = ' '
while resp not in "NSsn":
resp = str( input( 'Quer continuar:[s;n] ' ) ).strip().upper()[0]
if resp == 'N':
print( '{:-^40}'.format('PROGRAMA ENCERRADO'))
|
4ca63a7a9aaa432f4dcba077e9af8131c296b3dd | tainenko/Leetcode2019 | /leetcode/editor/en/[2363]Merge Similar Items.py | 2,978 | 3.921875 | 4 | # You are given two 2D integer arrays, items1 and items2, representing two sets
# of items. Each array items has the following properties:
#
#
# items[i] = [valuei, weighti] where valuei represents the value and weighti
# represents the weight of the iᵗʰ item.
# The value of each item in items is unique.
#
#
# Return a 2D integer array ret where ret[i] = [valuei, weighti], with weighti
# being the sum of weights of all items with value valuei.
#
# Note: ret should be returned in ascending order by value.
#
#
# Example 1:
#
#
# Input: items1 = [[1,1],[4,5],[3,8]], items2 = [[3,1],[1,5]]
# Output: [[1,6],[3,9],[4,5]]
# Explanation:
# The item with value = 1 occurs in items1 with weight = 1 and in items2 with
# weight = 5, total weight = 1 + 5 = 6.
# The item with value = 3 occurs in items1 with weight = 8 and in items2 with
# weight = 1, total weight = 8 + 1 = 9.
# The item with value = 4 occurs in items1 with weight = 5, total weight = 5.
# Therefore, we return [[1,6],[3,9],[4,5]].
#
#
# Example 2:
#
#
# Input: items1 = [[1,1],[3,2],[2,3]], items2 = [[2,1],[3,2],[1,3]]
# Output: [[1,4],[2,4],[3,4]]
# Explanation:
# The item with value = 1 occurs in items1 with weight = 1 and in items2 with
# weight = 3, total weight = 1 + 3 = 4.
# The item with value = 2 occurs in items1 with weight = 3 and in items2 with
# weight = 1, total weight = 3 + 1 = 4.
# The item with value = 3 occurs in items1 with weight = 2 and in items2 with
# weight = 2, total weight = 2 + 2 = 4.
# Therefore, we return [[1,4],[2,4],[3,4]].
#
# Example 3:
#
#
# Input: items1 = [[1,3],[2,2]], items2 = [[7,1],[2,2],[1,4]]
# Output: [[1,7],[2,4],[7,1]]
# Explanation:
# The item with value = 1 occurs in items1 with weight = 3 and in items2 with
# weight = 4, total weight = 3 + 4 = 7.
# The item with value = 2 occurs in items1 with weight = 2 and in items2 with
# weight = 2, total weight = 2 + 2 = 4.
# The item with value = 7 occurs in items2 with weight = 1, total weight = 1.
# Therefore, we return [[1,7],[2,4],[7,1]].
#
#
#
# Constraints:
#
#
# 1 <= items1.length, items2.length <= 1000
# items1[i].length == items2[i].length == 2
# 1 <= valuei, weighti <= 1000
# Each valuei in items1 is unique.
# Each valuei in items2 is unique.
#
#
# Related Topics Array Hash Table Sorting Ordered Set 👍 223 👎 9
# leetcode submit region begin(Prohibit modification and deletion)
from collections import defaultdict
class Solution:
def mergeSimilarItems(self, items1: List[List[int]], items2: List[List[int]]) -> List[List[int]]:
ret = []
cnt = defaultdict(int)
for val, weight in items1:
cnt[val] += weight
for val, weight in items2:
cnt[val] += weight
for key in range(1, 1001):
if key in cnt:
ret.append([key, cnt[key]])
return ret
# leetcode submit region end(Prohibit modification and deletion)
|
51ab2c00fbbbd19c48389687faa44fcef1542fdd | 84danie/CS408PythonDemo | /demo.py | 3,285 | 4.09375 | 4 | # CS 408 - Group Project - Python Demo
# Joshua Camacho and Danielle Holzberger
#
# Root approximation using bisection and Newton's method
# with graphic results
import math
import matplotlib.pyplot as plt
import numpy as np
#Function whose roots are to be calculated
def f1(x):
return 2*math.pow(x,3)-11.7*math.pow(x,2)+17.7*x-5
#Deriviative of the function
def f1D(x):
return 6*math.pow(x, 2)-(2*11.7)*x+17.7
#Calculates the approximate error between iterations
def approxError(c,p):
return abs((c-p)/c) if c!=0 else 100000000000
#Determines the root of a function by providing
#values that bracket the root
def bisection(f, a, b, maxIterations, epsilon):
if f(a)*f(b) > 0:
print('Values of a and b do not bracket the root')
return
c = 0
errors = {}
for n in range(0,maxIterations):
prevC = c
c = (a+b) / 2
errors[n] = approxError(c,prevC)
if errors[n] < epsilon or f(c) == 0:
return zip(*sorted(errors.items()))
if f(a)*f(c) < 0:
b = c
else:
a = c
#Determines the root of a function by using
#an initial guess
def newton(f, fp, x, maxIterations, epsilon, delta):
errors = {}
for n in range(0,maxIterations):
if abs(fp(x)) < delta or abs(fp(x)) == 0:
print("Derivative approaching zero- cannot find root")
return
prevX = x
x-= f(x) / fp(x)
errors[n] = approxError(x,prevX)
if errors[n] < epsilon or f(x) == 0:
return zip(*sorted(errors.items()))
print('Enter the desired error: ')
error1 = input()
print('Enter the maximum number of iterations:')
maxIterations = input()
#Comparion of methods for root 1
b1iterations,b1error = bisection(f1,-1,1,int(maxIterations),float(error1))
n1iterations,n1error = newton(f1,f1D,.5,int(maxIterations),float(error1),.00001)
plt.figure(1)
plt.subplot(311)
plt.plot(b1iterations[1:],b1error[1:],'b',label = 'Bisection Method')
plt.plot(n1iterations[1:],n1error[1:],'r',label = 'Newton\'s Method')
plt.yscale('log')
plt.xscale('log')
plt.title('Number of Iterations vs. Approximate Error for Root 1')
plt.xlabel('Number of Iterations')
plt.ylabel('Approximate Error')
plt.legend()
#Comparison of methods for root 2
plt.subplot(312)
b2iterations,b2error = bisection(f1,1,2,int(maxIterations),float(error1))
n2iterations,n2error = newton(f1,f1D,1.5,int(maxIterations),float(error1),.00001)
plt.plot(b2iterations[1:],b2error[1:],'b',label = 'Bisection Method')
plt.plot(n2iterations[1:],n2error[1:],'r',label = 'Newton\'s Method')
plt.yscale('log')
plt.xscale('log')
plt.title('Number of Iterations vs. Approximate Error for Root 2')
plt.xlabel('Number of Iterations')
plt.ylabel('Approximate Error')
plt.legend()
#Comparison of methods for root 3
plt.subplot(313)
b3iterations,b3error = bisection(f1,3,4,int(maxIterations),float(error1))
plt.plot(b3iterations[1:],b3error[1:],'b',label = 'Bisection Method')
n3iterations,n3error = newton(f1,f1D,3,int(maxIterations),float(error1),.00001)
plt.plot(n3iterations[1:],n3error[1:],'r',label = 'Newton\'s Method')
plt.yscale('log')
plt.xscale('log')
plt.title('Number of Iterations vs. Approximate Error for Root 3')
plt.xlabel('Number of Iterations')
plt.ylabel('Approximate Error')
plt.legend()
plt.show()
|
50dcc02772117019845185ac80796bc1dbb0803e | ClaudioCarvalhoo/you-can-accomplish-anything-with-just-enough-determination-and-a-little-bit-of-luck | /problems/AE88.py | 667 | 3.609375 | 4 | # Numbers In Pi
# O(n³+m)
# n = len(pi) | m = len(numbers)
def numbersInPi(pi, numbers):
numbers = set(numbers)
res = explore(pi, numbers, 0, 0, [None for _ in pi])
return res if res != float('inf') else -1
def explore(pi, numbers, i, spaces, necessarySpacesAfter):
cur = ""
best = float('inf')
for j in range(i, len(pi)):
cur += pi[j]
if cur in numbers:
if j == len(pi)-1:
return spaces
spacesAfter = necessarySpacesAfter[j+1]
if spacesAfter == None:
spacesAfter = explore(pi, numbers, j+1, spaces+1, necessarySpacesAfter)
necessarySpacesAfter[j+1] = spacesAfter - spaces
best = min(best, spacesAfter)
return best
|
cb67d23c791f5c02f2d555b2169cd981020b7c7c | balmydawn/- | /Base/Day05/Exercises/习题3.py | 371 | 3.765625 | 4 | # 编写一段代码,让用户输入两个数字,求两个数之间所有整数的和(不包括两个数),并打印
num1 = int(eval(input('输入第一个数:')))+ 1
num2 = input('输入第二个数:')
if type(eval(num2)) is float:
num2 = int(eval(num2))
else:
num2 = int(num2) - 1
res = 0
while num1 <= num2:
res = res + num1
num1 += 1
print(res)
|
012fa11116891811442027db929a5420442cbe3a | GodsloveIsuor123/holbertonschool-higher_level_programming-3 | /0x0B-python-input_output/4-append_write.py | 264 | 4 | 4 | #!/usr/bin/python3
'''
file: 4-append_write.py
functions:
-> append_write
'''
def append_write(filename="", text=""):
''' appends a string at the end of a text file '''
with open(filename, 'a', encoding="utf-8") as file:
return file.write(text)
|
7b17274aac6c92a871ea055d36c1922566b19615 | samuelbeaubien/FrozenLake_OpenAI | /tests.py | 163 | 3.515625 | 4 | # Test getting inputs from the user
move = input("Enter a move (0, 1, 2, 3): ")
print (type(move))
move_int = int(move, 10)
print (move_int)
print (type(move_int)) |
6ccc7b7e7c143a6a8a101a54f24052e1e906c1e0 | Offliners/Python_Practice | /code/024.py | 189 | 4.3125 | 4 | # using the third parameter
# in a range
str = "abcdefghijklmn"
# print every second character
print(str[::2])
# print every third character
print(str[::3])
# Output:
# acegikm
# adgjm
|
4c0a535de8d60c844497d731f063d6ecdcf76f79 | rhaussmann/data_sci | /ex_pyplot.py | 5,850 | 3.578125 | 4 | # https://matplotlib.org/gallery/index.html#pyplot-examples
from __future__ import division
from matplotlib import colors as mcolors
import matplotlib.pyplot as plt
import numpy as np
def easy_subplots():
x = np.random.randn(50)
# old style
fig = plt.figure()
ax1 = fig.add_subplot(221)
ax2 = fig.add_subplot(222, sharex=ax1, sharey=ax1)
ax3 = fig.add_subplot(223, sharex=ax1, sharey=ax1)
ax3 = fig.add_subplot(224, sharex=ax1, sharey=ax1)
# new style method 2; use an axes array
fig, axs = plt.subplots(2, 2, sharex=True, sharey=True)
axs[0, 0].plot(x)
plt.show()
def scatter_plot():
# Fixing random state for reproducibility
np.random.seed(19680801)
N = 50
x = np.random.rand(N)
y = np.random.rand(N)
colors = np.random.rand(N)
area = np.pi * (15 * np.random.rand(N)) ** 2 # 0 to 15 point radii
plt.scatter(x, y, s=area, c=colors, alpha=0.5)
plt.show()
def pie_chart():
# Pie chart, where the slices will be ordered and plotted counter-clockwise:
labels = 'Frogs', 'Hogs', 'Dogs', 'Logs'
sizes = [15, 30, 45, 10]
explode = (0, 0.1, 0, 0) # only "explode" the 2nd slice (i.e. 'Hogs')
fig1, ax1 = plt.subplots()
ax1.pie(sizes, explode=explode, labels=labels, autopct='%1.1f%%',
shadow=True, startangle=90)
ax1.axis('equal') # Equal aspect ratio ensures that pie is drawn as a circle.
plt.show()
def simple_plot():
plt.plot([1, 2, 3, 4])
plt.ylabel('some numbers')
plt.show()
def annotated_plot():
ax = plt.subplot(111)
t = np.arange(0.0, 5.0, 0.01)
s = np.cos(2 * np.pi * t)
line, = plt.plot(t, s, lw=2)
plt.annotate('local max', xy=(2, 1), xytext=(3, 1.5),
arrowprops=dict(facecolor='black', shrink=0.05),
)
plt.ylim(-2, 2)
plt.show()
def histogram_multihist():
np.random.seed(19680801)
n_bins = 10
x = np.random.randn(1000, 3)
fig, axes = plt.subplots(nrows=2, ncols=2)
ax0, ax1, ax2, ax3 = axes.flatten()
colors = ['red', 'tan', 'lime']
ax0.hist(x, n_bins, normed=1, histtype='bar', color=colors, label=colors)
ax0.legend(prop={'size': 10})
ax0.set_title('bars with legend')
ax1.hist(x, n_bins, normed=1, histtype='bar', stacked=True)
ax1.set_title('stacked bar')
ax2.hist(x, n_bins, histtype='step', stacked=True, fill=False)
ax2.set_title('stack step (unfilled)')
# Make a multiple-histogram of data-sets with different length.
x_multi = [np.random.randn(n) for n in [10000, 5000, 2000]]
ax3.hist(x_multi, n_bins, histtype='bar')
ax3.set_title('different sample sizes')
fig.tight_layout()
plt.show()
def boxplot_violin():
fig, axes = plt.subplots(nrows=1, ncols=2, figsize=(9, 4))
# Fixing random state for reproducibility
np.random.seed(19680801)
# generate some random test data
all_data = [np.random.normal(0, std, 100) for std in range(6, 10)]
# plot violin plot
axes[0].violinplot(all_data,
showmeans=False,
showmedians=True)
axes[0].set_title('Violin plot')
# plot box plot
axes[1].boxplot(all_data)
axes[1].set_title('Box plot')
# adding horizontal grid lines
for ax in axes:
ax.yaxis.grid(True)
ax.set_xticks([y + 1 for y in range(len(all_data))])
ax.set_xlabel('Four separate samples')
ax.set_ylabel('Observed values')
# add x-tick labels
plt.setp(axes, xticks=[y + 1 for y in range(len(all_data))],
xticklabels=['x1', 'x2', 'x3', 'x4'])
plt.show()
def barchart():
n_groups = 5
means_men = (20, 35, 30, 35, 27)
std_men = (2, 3, 4, 1, 2)
means_women = (25, 32, 34, 20, 25)
std_women = (3, 5, 2, 3, 3)
fig, ax = plt.subplots()
index = np.arange(n_groups)
bar_width = 0.35
opacity = 0.4
error_config = {'ecolor': '0.3'}
rects1 = ax.bar(index, means_men, bar_width,
alpha=opacity, color='b',
yerr=std_men, error_kw=error_config,
label='Men')
rects2 = ax.bar(index + bar_width, means_women, bar_width,
alpha=opacity, color='r',
yerr=std_women, error_kw=error_config,
label='Women')
ax.set_xlabel('Group')
ax.set_ylabel('Scores')
ax.set_title('Scores by group and gender')
ax.set_xticks(index + bar_width / 2)
ax.set_xticklabels(('A', 'B', 'C', 'D', 'E'))
ax.legend()
fig.tight_layout()
plt.show()
def named_colors():
colors = dict(mcolors.BASE_COLORS, **mcolors.CSS4_COLORS)
# Sort colors by hue, saturation, value and name.
by_hsv = sorted((tuple(mcolors.rgb_to_hsv(mcolors.to_rgba(color)[:3])), name)
for name, color in colors.items())
sorted_names = [name for hsv, name in by_hsv]
n = len(sorted_names)
ncols = 4
nrows = n // ncols + 1
fig, ax = plt.subplots(figsize=(8, 5))
# Get height and width
X, Y = fig.get_dpi() * fig.get_size_inches()
h = Y / (nrows + 1)
w = X / ncols
for i, name in enumerate(sorted_names):
col = i % ncols
row = i // ncols
y = Y - (row * h) - h
xi_line = w * (col + 0.05)
xf_line = w * (col + 0.25)
xi_text = w * (col + 0.3)
ax.text(xi_text, y, name, fontsize=(h * 0.8),
horizontalalignment='left',
verticalalignment='center')
ax.hlines(y + h * 0.1, xi_line, xf_line,
color=colors[name], linewidth=(h * 0.6))
ax.set_xlim(0, X)
ax.set_ylim(0, Y)
ax.set_axis_off()
fig.subplots_adjust(left=0, right=1,
top=1, bottom=0,
hspace=0, wspace=0)
plt.show()
named_colors()
|
bef6ab5427693cf403f193728060b74296195b1e | Tim-Sotirhos/statistics-exercises | /probability_distributions.py | 6,035 | 4.4375 | 4 | # Probability Distribution
import numpy as np
import math
from scipy import stats
import matplotlib.pyplot as plt
import pandas as pd
# 1.) A bank found that the average number of cars waiting during the noon hour at a drive-up window follows a Poisson distribution with a mean of 2 cars.
# Make a chart of this distribution and answer these questions concerning the probability of cars waiting at the drive-up window.
def cars_at_bank_at_noon():
x = range(8)
y = stats.poisson(2).pmf(x)
plt.figure(figsize=(9, 6))
plt.bar(x, y, edgecolor='black', color='white', width=1)
plt.xticks(x)
plt.ylabel('P(X = x)')
plt.xlabel('Average cars at drive_up window')
print(cars_at_bank_at_noon())
# 1.a) What is the probability that no cars drive up in the noon hour?
stats.poisson(2).pmf(0)
(stats.poisson(2).rvs(10000) == 0).mean()
# 1.b) What is the probability that 3 or more cars come through the drive through?
stats.poisson(2).sf(2)
(stats.poisson(2).rvs(10000) >= 3).mean()
# 1.c) How likely is it that the drive through gets at least 1 car?
stats.poisson(2).sf(0)
(stats.poisson(2).rvs(10000) > 0).mean()
# 2.) Grades of State University graduates are normally distributed with a mean of 3.0 and a standard deviation of .3. Calculate the following:
# 2.a) What grade point average is required to be in the top 5% of the graduating class?
gpa = np.random.normal(3, .3, (10000))
stats.norm(3, .3).isf(.05)
np.percentile(gpa, 95)
# 2.b) What GPA constitutes the bottom 15% of the class?
stats.norm(3, .3).ppf(.15)
np.percentile(gpa, 15)
# 2.c) An eccentric alumnus left scholarship money for students in the third decile from the bottom of their class.
# Determine the range of the third decile. Would a student with a 2.8 grade point average qualify for this scholarship?
stats.norm(3, .3).ppf([.2,.3])
# Or
stats.norm(3, .3).ppf(.3)
stats.norm(3, .3).ppf(.2)
np.percentile(gpa, [20, 30])
# 2.d) If I have a GPA of 3.5, what percentile am I in?
1 - stats.norm(3, .3).sf(3.5)
# Or
stats.norm(3, .3).cdf(3.5)
(gpa <= 3.5).mean()
# 3.) A marketing website has an average click-through rate of 2%.
# One day they observe 4326 visitors and 97 click-throughs.
# How likely is it that this many people or more click through?
stats.binom(4326, .02).sf(96)
((np.random.random((10000, 4326)) <= .02).sum(axis=1) >= 97).mean()
# 4.) You are working on some statistics homework consisting of 100 questions where all of the answers are a probability rounded to the hundreths place.
# Looking to save time, you put down random probabilities as the answer to each question.
# 4.a) What is the probability that at least one of your first 60 answers is correct?
stats.binom(60,.01).sf(0)
((np.random.random((10000, 60)) <= .01).sum(axis=1) > 0).mean()
# 5.) The codeup staff tends to get upset when the student break area is not cleaned up.
# Suppose that there's a 3% chance that any one student cleans the break area when they visit it, and,
# on any given day, about 90% of the 3 active cohorts of 22 students visit the break area.
# How likely is it that the break area gets cleaned up each day?
# How likely is it that it goes two days without getting cleaned up?
# All week?
n_students = round(.9*66)
# cleanded each day
stats.binom(n_students, .03).sf(0)
# not cleaned two day
(stats.binom(n_students, .03).cdf(0))**2
# not cleaned all week
(stats.binom(n_students, .03).cdf(0))**5
# 6.) You want to get lunch at La Panaderia, but notice that the line is usually very long at lunchtime.
# After several weeks of careful observation,
# you notice that the average number of people in line when your lunch break starts is normally distributed with a mean of 15 and standard deviation of 3.
# If it takes 2 minutes for each person to order, and 10 minutes from ordering to getting your food, what is the likelihood that you have at least 15 minutes left to eat your food before you have to go back to class?
# Assume you have one hour for lunch, and ignore travel time to and from La Panaderia.
mean = 15
std= 3
time_to_order = 2
lunch_hour = 60
eat_time = 15
prep_time = 10
people = round((lunch_hour - eat_time - prep_time - time_to_order) // time_to_order)
lunch_line = stats.norm(15,3).cdf(people)
lunch_line
(np.random.normal(15,3, 10000) <= 16).mean()
# 7.) Connect to the employees database and find the average salary of current employees, along with the standard deviation.
# Model the distribution of employees salaries with a normal distribution and answer the following questions:
def get_db_url(user, password, host, database_name):
url = f'mysql+pymysql://{user}:{password}@{host}/{database_name}'
return url
import env
from env import host, user, password
url = get_db_url(user,password, host, "employees")
url
# Read the salaries tables into a dataframes
salaries_query = "SELECT * FROM salaries WHERE to_date > NOW()"
salaries = pd.read_sql(salaries_query, url)
(salaries.tail(25))
average_salary = salaries.salary.mean()
std_salary = salaries.salary.std()
salary_distribution = stats.norm(average_salary, std_salary)
# 7.a) What percent of employees earn less than 60,000?
percent_under_60k = salary_distribution.cdf(60000)
(salaries.salary < 60000).mean()
# 7.b) What percent of employees earn more than 95,000?
percent_above_95k = salary_distribution.sf(95000)
(salaries.salary > 95000).mean()
# 7.c) What percent of employees earn between 65,000 and 80,000?
percent_above_65k = salary_distribution.cdf(65000)
percent_below_80k = salary_distribution.cdf(80000)
percent_between_65k_and_80k = percent_below_80k - percent_above_65k
((salaries.salary > 65000) & (salaries.salary < 80000)).mean()
# Or using SF
percent_above_65k = salary_distribution.sf(65000)
percent_below_80k = salary_distribution.sf(80000)
percent_between_65k_and_80k = percent_above_65k - percent_below_80k
# 7.d) What do the top 5% of employees make?
top_five_percent_salary = salary_distribution.isf(.05)
salaries.salary.quantile(.95) |
9e645c1c9c934ae57187fb6294a2428b8a955ad5 | claytonjwong/Sandbox-Python | /fizz_buzz.py | 1,132 | 3.9375 | 4 | """
412. Fizz Buzz
Write a program that outputs the string representation of numbers from 1 to n.
But for multiples of three it should output “Fizz” instead of the number and for the multiples of five output “Buzz”. For numbers which are multiples of both three and five output “FizzBuzz”.
n = 15,
Return:
[
"1",
"2",
"Fizz",
"4",
"Buzz",
"Fizz",
"7",
"8",
"Fizz",
"Buzz",
"11",
"Fizz",
"13",
"14",
"FizzBuzz"
]
"""
class Solution(object):
def fizzBuzz(self, n):
ret = []
#
# iterate from 1 to n inclusive
#
for i in range ( 1, n+1 ):
if i%3==0 and i%5==0:
ret.append("FizzBuzz")
elif i%3==0:
ret.append("Fizz")
elif i%5==0:
ret.append("Buzz")
else:
ret.append(str(i))
return ret
def main():
import pdb
pdb.set_trace()
solution = Solution()
print ( solution.fizzBuzz(15) )
if __name__ == "__main__":
main()
|
294820bc4c447ebb3d9a679f04cf4d82b71cb836 | rolfwessels/bar-craft-keg-cleaner | /misc/StartcodePUMPTEST.py | 817 | 3.609375 | 4 |
import RPi.GPIO as GPIO
import time
GPIO.setmode(GPIO.BCM)
# init list with pin numbers
pinList = [2, 3, 4, 5, 6, 12, 13, 19]
"""
2-Air
3_DUMP
4-H2O PMP
5 - H"O
6-SANRECIRC
12-SAN
13-
19-H2O RECIRC
"""
# loop through pins and set mode and state to 'low'
for i in pinList:
GPIO.setup(i, GPIO.OUT)
GPIO.output(i, GPIO.HIGH)
# time to sleep between operations in the main loop
SleepTimePMP = 3
try:
count = 2
while (count > 0):
'print '' The count is:', count
for i in pinList:
G
GPIO.output(13, GPIO.HIGH)
print ('End')
# End program cleanly with keyboard
except KeyboardInterrupt:
'print' " Quit"
# Reset GPIO settings
GPIO.cleanup()
|
45269148de868a50c87103e809fb27ca3fc8fec2 | allenGKC/Leetcode_Practice | /python_code/Pow(x, n).py | 548 | 3.921875 | 4 | '''
Problem:Pow(x, n)
Implement pow(x, n).
'''
class Solution(object):
def myPow(self, x, n):
"""
:type x: float
:type n: int
:rtype: float
"""
if not n:
return 1
if n<0:
return 1/self.myPow(x, -n)
if n == 1:
return x
if not n%2:
return self.myPow(x*x, n/2)
return x*self.myPow(x*x, n/2)
'''
short method:
return x ** n
'''
'''
Test Case:
'''
if __name__ == '__main__':
|
3dc03d4c0650b3c762d205f16380af76bdae657b | Sheetal2304/if_else | /Age.py | 329 | 4.03125 | 4 | age=int(input("enter the number"))
if age<5:
print("baccha hai")
elif age>=5 and age <18:
print("school ja skta h")
elif age>=18 and age <21:
print("vote daal skta h")
elif age>=21 and age <24:
print("drive kr skta h")
elif age>=24 and age <25:
print("shaadi kr skta h")
elif age>=25:
print("legally drink kr skta hai") |
c11ca88fceba34ac84fea10277e9d720996012de | Aissen-Li/lintcode | /124.longestConsecutive.py | 1,123 | 3.65625 | 4 | class Solution:
"""
@param num, a list of integer
@return an integer
"""
def longestConsecutive(self, num):
nums = set(num)
res = 0
for currentNum in num:
if currentNum in nums:
tempLen = 0
leftNum = currentNum - 1
rightNum = currentNum + 1
nums.remove(currentNum)
while leftNum in nums:
nums.remove(leftNum)
tempLen += 1
leftNum -= 1
while rightNum in nums:
nums.remove(rightNum)
tempLen += 1
rightNum += 1
res = max(res, tempLen)
return res
class Solution2:
"""
@param num, a list of integer
@return an integer
"""
def longestConsecutive(self, num):
res, nums = 0, set(num)
for low in num:
if low - 1 not in nums:
high = low + 1
while high in nums:
high += 1
res = max(res, high - low)
return res
|
389d749c093ebbca3a974601928e6fda5d75f172 | jnixon7007/Functions_Parameters-Global_Variables | /diceRoller.py | 847 | 3.96875 | 4 | #Dice Roll program
#This program rolls a dice and prints out the dices face
import random,time
s1 = "- - - - -\n| |\n| O |\n| |\n- - - - -\n"
s2 = "- - - - -\n| O |\n| |\n| O |\n- - - - -\n"
s3 = "- - - - -\n| O |\n| O |\n| O |\n- - - - -\n"
s4 = "- - - - -\n| O O |\n| |\n| O O |\n- - - - -\n"
s5 = "- - - - -\n| O O |\n| O |\n| O O |\n- - - - -\n"
s6 = "- - - - -\n| O O |\n| O O |\n| O O |\n- - - - -\n"
def roll():
print("rolling.....")
time.sleep(0.5)
roll = random.randint(1,6)
return roll
def show_dice(roll):
if roll == 1:
print(s1)
elif roll == 2:
print(s2)
elif roll == 3:
print(s3)
elif roll == 4:
print(s4)
elif roll == 5:
print(s5)
else:
print(s6)
roll=roll()
show_dice(roll)
|
a10c14aecbe96f0f8a0eb7617a7e3e39ed122268 | pattric0222/Python | /week2/test1.py | 249 | 4.0625 | 4 | first = input("Input First Number \n")
second = input("Input Second Number \n")
print("{} = {} : ".format(first,second),first == second)
print("{} > {} : ".format(first,second),first > second)
print("{} < {} : ".format(first,second),first < second)
|
71c513fa365a859abc90c6cd52cbde80090b9ea3 | wenyaowu/leetcode-js | /problems/splitArrayLargestSum.py | 1,380 | 3.921875 | 4 | """
Given an array which consists of non-negative integers and an integer m, you can split the array into m non-empty continuous subarrays. Write an algorithm to minimize the largest sum among these m subarrays.
Note:
If n is the length of array, assume the following constraints are satisfied:
1 ≤ n ≤ 1000
1 ≤ m ≤ min(50, n)
Examples:
Input:
nums = [7,2,5,10,8]
m = 2
Output:
18
Explanation:
There are four ways to split nums into two subarrays.
The best way is to split it into [7,2,5] and [10,8],
where the largest sum among the two subarrays is only 18.
"""
class Solution:
def splitArray(self, nums: List[int], m: int) -> int:
lo = max(nums)
hi = sum(nums)
while lo < hi:
mid = (lo+hi)//2
if self.split(mid, nums, m): # Can be split into equal or more than m partitions
# mid words, we want to be greedy, try smaller sum
hi = mid
else:
# mid doesn't work, move to mid+1
lo = mid + 1
return lo
def split(self, target, nums, m):
currentSum = 0
partitions = 1
for num in nums:
currentSum += num
if currentSum > target:
partitions += 1
currentSum = num
if partitions > m:
return False
return True
|
78638fbb27e51d492866598778007ff9651a1c89 | Brukvo/PyBasics | /lesson06/task02.py | 1,519 | 4.03125 | 4 | """
2. Реализовать класс Road (дорога), в котором определить атрибуты:
length (длина), width (ширина).
Значения данных атрибутов должны передаваться при создании экземпляра класса.
Атрибуты сделать защищенными.
Определить метод расчета массы асфальта, необходимого для покрытия всего
дорожного полотна. Использовать формулу: длина * ширина * масса асфальта для
покрытия одного кв метра дороги асфальтом, толщиной в 1 см * число см толщины
полотна. Проверить работу метода.
Например: 20м * 5000м * 25кг * 5см = 12500 т
"""
class Road:
def __init__(self, length: int, width: int):
self._length = length
self._width = width
def get_length(self):
return self._length
def get_width(self):
return self._width
def calc_mass(self, weight: int, thick: int):
total = self._width * self._length * weight * thick
return total
r = Road(1250, 10)
print(f'Ширина дорожного полотна: {r.get_width()}\n',
f'Длина дорожного полотна: {r.get_length()}\n',
f'Общая масса покрытия: {r.calc_mass(12, 4) / 1000} т')
|
87b8dab004797ba1a35dc2e5a9900190436db6ed | cvhs-cs-2017/practice-exam-RushBComrades | /MyFile.py | 289 | 4.34375 | 4 | """Step 3: In MyFile.py, define a function for the turtle program that will draw
a regular polygon with 'n' sides."""
n = int(input())
import turtle
def meme(o):
Vex = turtle.Turtle()
Vex.speed(0)
for x in range (n):
Vex.forward(1)
Vex.right((360/n))
meme(n)
|
c45fd4f5a8e15cd035acf90dac7bafd543d04c90 | Joexder/Python-Curse | /Conditionals.py | 297 | 4 | 4 | x = input("<escribe tu edad: ")
if int(x) > 26:
print("Por mayor")
elif int(x) == 26:
print("En el limite")
else:
print("Por menor")
y = input("Escribe un Color:")
if y == 'red' or y == 'blue' or y == 'yellow':
print("Colores primarios")
else:
print("Colores Secundarios")
|
857d42b5342ee738566323e7c7a13cda4adeefe4 | hoang-ng/LeetCode | /Tree/437.py | 1,315 | 3.5625 | 4 |
# 437. Path Sum III
# You are given a binary tree in which each node contains an integer value.
# Find the number of paths that sum to a given value.
# The path does not need to start or end at the root or a leaf, but it must go downwards (traveling only from parent nodes to child nodes).
# The tree has no more than 1,000 nodes and the values are in the range -1,000,000 to 1,000,000.
# Example:
# root = [10,5,-3,3,2,null,11,3,-2,null,1], sum = 8
# Return 3. The paths that sum to 8 are:
# 1. 5 -> 3
# 2. 5 -> 2 -> 1
# 3. -3 -> 11
from BinaryTree import (generateBinaryTree, TreeNode)
class Solution(object):
def pathSum(self, root, sum):
def dfs(root, preSum, sum):
if not root:
return 0
currSum = preSum + root.val
count = 0
if (currSum - sum) in dic:
count += dic[currSum - sum]
if currSum in dic:
dic[currSum] += 1
else:
dic[currSum] = 1
count += dfs(root.left, currSum, sum)
count += dfs(root.right, currSum, sum)
dic[currSum] -= 1
return count
dic = {0: 1}
return dfs(root, 0, sum)
root = generateBinaryTree([10,5,-3,3,2,-1,11,3,-2,-1,1])
sol = Solution()
sol.pathSum(root, 8)
|
f0f488f2b2ac4f039ff44e2ddf1b34dbb4898be1 | daadestroyer/20MCAOOPS | /LabComponent/App10_generator.py | 684 | 3.75 | 4 | import time
def timeit(func):
def timed(*args, **kw):
starttime = time.time()
result = func(*args, *kw)
endtime = time.time()
print("time taken", endtime-starttime)
return result
return timed
@timeit
def fib(a=0, b=1):
while True:
yield a
a, b = b, a+b
f = fib()
num = int(input("enter range for series"))
for i in range(num):
print(next(f))
# def fib(limit):
# a, b = 0, 1
# while a < limit:
# yield a
# a,b=b,a+b
# x = fib(5)
# # try:
# # while True:
# # print(x.__next__())
# # except StopIteration:
# # print('STOP ITERATING')
# for i in x:
# print(i)
|
2b0bc88b5ad4e7a454728b912dfad2cdd13cdb37 | IhToN/DAW1-PRG | /Ejercicios/PrimTrim/Ejercicio38.py | 516 | 3.578125 | 4 | """
Comprobar las Leyes de Demorgan
a. not (AUB) = not A or not B
b. not(AorB) = not A and not B
La negación de una conjunción es la desconjunción de la negación de los términos.
"""
A, B = {1, 2, 3}, {2, 3, 4}
Universal = {x for x in range(100)}
aleft = Universal - (A | B)
aright = Universal - A & Universal - B
print('Primera ley de Demorgan: ', aleft == aright)
bleft = Universal - (A & B)
bright = Universal - A | Universal - B
print('Segunda ley de Demorgan: ', bleft == bright)
|
43303916c52c7b6277582892af4d2b3eef492db3 | jwyx3/practices | /leetcode/binary-search/bs-answer/preimage-size-of-factorial-zeroes-function.py | 1,117 | 3.609375 | 4 | # https://leetcode.com/problems/preimage-size-of-factorial-zeroes-function/
# https://leetcode.com/problems/preimage-size-of-factorial-zeroes-function/solution/
# Time: O(log5(10*K)*log2(10*K))
# Space: O(1)
class Solution(object):
def preimageSizeFZF(self, K):
"""
:type K: int
:rtype: int
"""
# 2 * 5 = 10. count(2) > count(5)
# so f(x) = K. -> f(x) = x/5 + x/(5**2) + x/(5**3) + ... = K
# assume x0 is the smallest number f(x0) = K
# then 5 numbers which belongs to [x0, x0+4] are valid. -> count is 5
# otherwise, 0
# find x which f(x) = K. return 5 if found, otherwise, return 0
def check(x):
count, d = 0, 5
while x >= d:
count += x / d
x /= d
return count
lo, hi = 0, 10*K + 1
while lo < hi:
mid = (lo + hi) / 2
count = check(mid)
if count == K:
return 5
elif count > K:
hi = mid
else:
lo = mid + 1
return 0
|
f2ad155fb39c8cbaec3d8cc4b1155c7d3a153976 | guedanie/python-exercises | /warm-up.py | 1,248 | 4.03125 | 4 | # Take the word EASY: Its first three letters — E, A and S — are the fifth, first, and nineteenth letters,
# respectively, in the alphabet. If you add 5, 1, and 19, you get 25, which is the value of the
# alphabetical position of Y, the last letter of EASY.
## Cna you think of a common five-letter word that works in the opposite way -
# in which the value of the alphabetical positions of its last four letters add up to the
# value of the alphabetical position of its first letter?
import pandas as pd
with open('/usr/share/dict/words') as f:
words = f.read().split('\n')
five_words = [x for x in words if len(x) == 5]
def find_value_of_letter(string):
string = string.lower()
letters = pd.Series(list(string))
alphabet = pd.Index(list("abcdefghijklmnopqrstuvwxyz"))
last_three = letters[-4:]
first = letters[0]
count_last = 0
count_first = 0
list_of_words = []
for x in last_three:
count_last += alphabet.get_loc(x) + 1
for x in first:
count_first += alphabet.get_loc(x) + 1
if count_last == count_first:
list_of_words += [string]
return count_last == count_first
words_value = [x for x in five_words if find_value_of_letter(x)]
words_value |
70ec80f7cafbf0c16d17a8e408d1c86101c69abd | addn2x/python3 | /ex08-strings/string03.py | 277 | 3.765625 | 4 | a = 'This is some text'
b = '123456'
print(a.find('is'))
print(a.find('other'))
print(a.isalpha())
print(a.isdigit())
print(b.isalpha())
print(b.isdigit())
print(a.upper())
print(a.lower())
print(a.split())
print(a.join(b))
print(a + b)
print(a.replace('is', 'was')) |
1a833fd1f61e7f9f8a074cb5fac516909bb7445e | webclinic017/best_performance-python | /algorithm/linear/1.py | 232 | 3.5 | 4 | import numpy as np
A = np.array( [ [1,2,4,1], [2,1,3,1], [5,2,1,4] ], dtype=np.float64 )
print(A)
print(A.shape)
# 오류 발생
#A[0,2] = 1+2j
#A[2,1] = 1+2j
# 0으로 바꿔보기
A[0,2] = 0
A[2,1] = 0
print(A) |
4801233fbca798a2439ad0529ea365b904b29269 | smarky7CD/PyNTRU | /PyNTRU/poly.py | 2,286 | 3.59375 | 4 | #!/usr/bin/env python3
from itertools import zip_longest
class Polynomial():
def __init__(self,c, N):
self._coeff = strip(c,0)
self._N = N
def __add__(self, other):
new_coeff = [sum(x) for x in zip_longest(self, other, fillvalue=0)]
return Polynomial(new_coeff, self._N)
def __sub__(self, other):
return self + (-other)
def scale(self, m):
"""scalar multiplication of polynomial by int m"""
new_coeff = [m*c for c in self]
return Polynomial(new_coeff, self._N)
def __mul__(self, other):
"""convolution product of truncated poly ring"""
if self.isZero() or other.isZero(): return Zero()
tmp_coeff = [0 for _ in range(self._N*2 -1)]
for i,a in enumerate(self):
for j,b in enumerate(other):
tmp_coeff[i+j] += a*b
trunc1 = tmp_coeff[:self._N]
trunc2 = tmp_coeff[self._N:]
new_coeff = [sum(x) for x in zip_longest(trunc1,trunc2,fillvalue=0)]
return Polynomial(new_coeff, self._N)
def __mod__(self, m):
""" Reducing a polynomial's coeff mod m, also does center-lifting """
reduced_coeff = list(map(lambda x: x%m if x%m <= m//2 else x%m - m, self))
return Polynomial(reduced_coeff, self._N)
def __str__(self):
return ' '.join([str(c) for c in self])
def __len__(self):
return len(self._coeff)
def __iter__(self):
return iter(self._coeff)
def __neg__(self):
return Polynomial([-c for c in self], self._N)
def __eq__(self, other):
return self.deg() == other.deg() and all([x==y for (x,y) in zip(self,other)])
def __ne__(self, other):
return self.deg() != other.deg() and all([x!=y for (x,y) in zip(self,other)])
def tail_coeff(self):
return self._coeff[0]
def lead_coeff(self):
return self._coeff[-1]
def deg(self):
return len(self) - 1
def isZero(self):
return self._coeff == [0]
def strip(L, e=0):
""" strip all copies of e from end of list"""
if len(L) == 0: return L
i = len(L) - 1
while i>=0 and L[i] == e:
i -= 1
return L[:i+1]
|
1bb1cb878947ed52d427d0f78fba0ca7f1e9b9e4 | eush77/blackbox | /examples/test/factor.py | 519 | 3.765625 | 4 | #!/usr/bin/python3
from math import sqrt, floor
from collections import defaultdict
def factor(n):
for k in range(2, floor(sqrt(n))+1):
if not n%k:
powers = factor(n // k)
powers[k] += 1
return powers
return defaultdict(int, {n: 1})
if __name__ == '__main__':
n = int(input())
factorization = factor(n)
print(' * '.join('{}{}'.format(prime, '^{}'.format(power) if power>1 else '')
for prime,power in sorted(factorization.items())))
|
c16f8aa85f81d185151c9db2a88e1daa5774fe48 | bgswaroop/tsai-epai-session15 | /session15.py | 1,890 | 3.6875 | 4 | from collections import namedtuple
from datetime import datetime
from itertools import islice
Ticket = namedtuple('Ticket', 'summons_number, plate_id, registration_state, plate_type, issue_date, violation_code, '
'vehicle_body_type, vehicle_make, violation_description')
date_formatter = lambda x: datetime.strptime(x, '%m/%d/%Y')
ticket_datatype = [int, str, str, str, date_formatter, int, str, str, str]
def fetch_data():
"""
Goal 1
Create a lazy iterator that will return a named tuple of the data in each row. The data types should be appropriate
- i.e. if the column is a date, you should be storing dates in the named tuple, if the field is an integer,
then it should be stored as an integer, etc.
:return: generator that returns single ticket at a time
"""
with open('nyc_parking_tickets_extract.csv', 'r') as f:
next(f)
for line in f:
line_data = [x.strip() for x in line.strip().split(',')]
line_data = [item_type(item) for item, item_type in zip(line_data, ticket_datatype)]
yield Ticket(*line_data)
return 'Finished reading the file'
def compute_violations_by_car_make():
"""
Goal 2
Calculate the number of violations by car make.
:return: A dictionary containing the violations per car make
"""
parking_tickets = fetch_data()
violations = {}
for ticket in parking_tickets:
if ticket.vehicle_make in violations:
violations[ticket.vehicle_make] += 1
else:
violations[ticket.vehicle_make] = 1
return violations
def print_data():
"""
Print the entire data
:return:
"""
parking_tickets = fetch_data()
for ticket in islice(parking_tickets, 10000):
print(ticket)
if __name__ == '__main__':
print_data()
print(compute_violations_by_car_make()) |
0adc9c83b412d2cfe8ab01095bcd951f0c6a50c9 | FawneLu/leetcode | /264/Solution.py | 475 | 3.625 | 4 | ```python3
import heapq
class Solution:
def nthUglyNumber(self, n: int) -> int:
heap=[1]
count=1
while count<=n:
target=heapq.heappop(heap)
if target*2 not in heap:
heapq.heappush(heap,target*2)
if target*3 not in heap:
heapq.heappush(heap,target*3)
if target*5 not in heap:
heapq.heappush(heap,target*5)
count+=1
return target
``` |
4d1fc819ef5a7a306b3eaae5d340af3e9fd7cd32 | srividhyaravi/ML_Assignment | /Assignment_MLP/mlp_program.py | 4,158 | 3.609375 | 4 | #!/usr/bin/env python
# coding: utf-8
# In[1]:
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
# In[2]:
#reading the dataset from csv file
def read_data(file):
data = pd.read_csv(file, header=None , index_col=None)
return data
data = read_data('data.txt')
data.head()
# In[3]:
#shuffling and splitting of the dataset
def split_data(data):
df = pd.DataFrame(data)
#shuffle the dataset
df = df.sample(frac=1)
#split the dataset
split = np.random.rand(len(df)) < 0.7
train = np.asmatrix(df[split], dtype = 'float64')
test = np.asmatrix(df[~split], dtype = 'float64')
X_train = train[:, :-1]
y_train = train[:, -1]
X_test = test[:, :-1]
y_test = test[:,-1]
return X_train,y_train,X_test,y_test
X_train,y_train,X_test,y_test = split_data(data)
# In[4]:
#initializing params
alpha = 0.002
epoch = 100
W = np.zeros(X_train.shape[1]+1)
# In[5]:
#activation function
def activation(z):
if z>=0:
return 1
else:
return 0
# In[6]:
#prediction function
def predict(x):
z = np.dot(x, W[1:]) + W[0]
g = activation(z)
return g
# In[7]:
#training to learn the weights
def train(X_train, y_train):
loss_train = []
train_acc = []
epochs = range(1,epoch+1)
for i in range(epoch):
correct = 0
cost = 0
for x, y in zip(X_train, y_train):
prediction = predict(x)
y = np.array(y)[0][0]
x = np.array(x)[0]
error = y - prediction
actual_value = int(y)
if actual_value == prediction:
correct += 1
W[1:] += alpha * error * x[0]
W[0] += alpha * error
cost += error**2
cost = cost/2
training_accuracy = correct/float(X_train.shape[0])*100.0
loss_train.append(cost)
train_acc.append(training_accuracy)
print("epoch:"+str(i)+" weight:"+str(W)+" learning rate:"+str(alpha)+" Training Accuracy:"+str(training_accuracy))
plt.plot(epochs, train_acc, 'g', label='Training accuracy')
plt.xlim(0,epoch)
plt.title('Training accuracy',fontsize=20)
plt.xlabel('Epochs')
plt.ylabel('Accuracy')
plt.legend()
plt.show()
plt.plot(epochs, loss_train, 'g', label='Training loss')
plt.xlim(0,epoch)
plt.title('Training loss',fontsize=20)
plt.xlabel('Epochs')
plt.ylabel('Loss')
plt.legend()
plt.show()
train(X_train, y_train)
# In[8]:
#Testset accuracy, Confusion Matrix and Accuracy metrics
def test(X_test, y_test):
print("Predictions on test data:")
correct = 0
tp,fp,tn,fn = 0,0,0,0
for x,y in zip(X_test,y_test):
prediction = predict(x)
actual_value = int(np.array(y)[0][0])
print("X: "+str(x)+" prediction: "+str(prediction)+" Actual value:"+str(actual_value))
if actual_value == prediction:
correct += 1
if actual_value == 0 and prediction == 0:
tp += 1
if actual_value == 1 and prediction ==1:
tn += 1
if actual_value == 0 and prediction ==1:
fn += 1
if actual_value == 1 and prediction == 0:
fp += 1
test_accuracy = correct/float(X_test.shape[0])*100.0
print("Test Accuracy:"+str(test_accuracy))
print()
print("Accuracy metrics:")
accuracy = (tp+tn)/(tp+tn+fp+fn)
precision = tp/(tp+fp)
recall = tp/(tp+fn)
print("Accuracy: "+str(accuracy))
print("Precision: "+str(precision))
print("Recall: "+str(recall))
print()
print("Confusion matrix:")
cm = [[tp,fp],[fn,tn]]
print(cm)
print()
df_cm = pd.DataFrame(cm, range(2), range(2))
plt.figure(figsize = (10,7))
sns.heatmap(df_cm, annot=True)
plt.title('Confusion Matrix', fontsize = 20)
plt.xlabel('Predicted', fontsize = 15)
plt.ylabel('Actual', fontsize = 15)
plt.show()
test(X_test, y_test)
|
9a824124ce6934707dbce9f9f3dcd457e5a4d855 | aayush2906/data_structures-Python | /InsertionSort.py | 382 | 4.125 | 4 |
def InsertionSort(seq):
for sliceEnd in range(len(seq)):
pos=sliceEnd
while pos > 0 and seq[pos] < seq[pos-1]:
(seq[pos],seq[pos-1])=(seq[pos-1],seq[pos])
pos=pos-1
seq=[]
n=int(input("Size of list::"))
for i in range(0,n):
x=int(input("Enter element::"))
seq.insert(i,x)
InsertionSort(seq)
print("Sorted list",seq)
|
5645e7dbda048b8a2d02ea45d28a9a134a80f0f2 | ardhysevenfold/animasi | /fiqoh.py | 1,299 | 3.515625 | 4 | from tkinter import *
import time
lebar = 600
tinggi = 400
tk = Tk()
canvas = Canvas(tk, width=lebar, height=tinggi)
tk.title("Gambar Bola Banyak Bergerak")
canvas.pack()
bola = canvas.create_oval(10, 10, 70, 70, fill="yellow")
bola2 = canvas.create_oval(10, 10, 70, 70, fill="orange")
bola3 = canvas.create_oval(10, 10, 70, 70, fill="black")
kecepatanx = 5
kecepatany = 5
kecepatanx = 5
kecepatany = 5
kecepatanx = 5
kecepatany = 5
while True:
canvas.move(bola, kecepatanx, kecepatany)
pos = canvas.coords(bola)
if pos[3] >= tinggi or pos[1] <= 0:
kecepatany = -kecepatany
if pos[2] >= lebar or pos[0] <= 0:
kecepatanx = -kecepatanx
tk.update()
time.sleep(0.001)
canvas.move(bola2, kecepatanx, kecepatany)
pos = canvas.coords(bola2)
if pos[3] >= tinggi or pos[1] <= 0:
kecepatany = -kecepatany
if pos[2] >= lebar or pos[0] <= 0:
kecepatanx = -kecepatanx
tk.update()
time.sleep(0.001)
canvas.move(bola3, kecepatanx, kecepatany)
pos = canvas.coords(bola3)
if pos[3] >= tinggi or pos[1] <= 0:
kecepatany = -kecepatany
if pos[2] >= lebar or pos[0] <= 0:
kecepatanx = -kecepatanx
tk.update()
time.sleep(0.001)
tk.mainloop()
|
8382a5c5de68f1d79e21a0fd99baa388f19c7df7 | prasannakumarj/Learning_Python | /Chapter 02_Object_types/2_Lists/prg5.py | 440 | 4.4375 | 4 | #!/usr/bin/python
#Title: List comprehension "expression"
M=[[1,2,3],
[4,5,6],
[7,8,9]] #matrix in the form of list
print('The matrix is:',M)
col1=[i[0] for i in M]
print('Column 1 elements are:',col1)
col2=[i[1] for i in M]
print('Column 2 elements are:',col2)
col3=[i[2] for i in M]
print('Column 3 elements are:',col3)
'''The SYNTAX is:
counter with index for counter in object
Here for loop is used with "i" as a counter'''
|
66f2cfddb4ff48bd193552ce441888dff137087a | ltzone/EE447-Project | /backend/test.py | 431 | 3.609375 | 4 | s = """
for x in range(10):
print(x, end='')
print()
"""
code_exec = compile(s, '<string>', 'exec')
code_eval = compile('10 + 20', '<string>', 'eval')
code_single = compile('name = input("Input Your Name: ")', '<string>', 'single')
a = exec(code_exec)
b = eval(code_eval)
c = exec(code_single)
d = eval(code_single)
print('a: ', a)
print('b: ', b)
print('c: ', c)
print('name: ', name)
print('d: ', d)
print('name; ', name) |
464000d7c90d89720624b8267e9bf2f4081217c6 | LevenWin/Algorithm | /Python/Code/LinkedList/12-13.py | 2,489 | 3.75 | 4 | # -*- coding: UTF-8 -*-
# 入环点
from linkedlist import LinkedLink
from linkedlist import LinkNode
import math
def circleNode(head):
meetNode = circleMeet(head)
if meetNode == None:
return None
cur = head.next
while cur != None and meetNode != None:
if cur == meetNode:
return cur
else:
cur = cur.next
meetNode = meetNode.next
return None
# 入环点
def circleMeet(head):
cur1 = head.next
cur2 = head.next
while cur1 != None and cur2 != None:
cur1 = cur1.next
cur2 = cur2.next.next
if cur1 == cur2:
return cur1
return None
def noCircleMeet(head1, head2):
cur1 = head1.next
cur2 = head2.next
l1 = 1
l2 = 2
while cur1.next != None:
l1 += 1
cur1 = cur1.next
while cur2.next != None:
l2 += 1
cur2 = cur2.next
if cur1 != cur2:
return None
large = l1 - l2
cur1 = head1.next
cur2 = head2.next
if l1 < l2:
large = l2 - l1
cur1 = head2.next
cur2 = head1.next
while cur1 != None and cur2 != None and cur1 == cur2:
if large == 0:
cur2 = cur2.next
cur1 = cur1.next
return cur1
def twoCircleMeet(head1, head2, meet1, meet2):
cur1 = meet1.next
if meet1 == meet2:
return twoCircleMeet2(head1, head2, meet1, meet2)
else:
while cur1 != None and cur1 != meet1:
if cur1 == meet2:
return twoCircleMeet2(head1, head2, meet1, meet2)
return None # 不相交
# 环内相交
def twoCircleMeet1(head1, head2, meet1, meet2):
# 返回meet1 或者meet2应该都行。
# return meet1
return meet2
# 环外相交。同一个入环点
def twoCircleMeet2(head1, head2, meet):
cur1 = head1.next
cur2 = head2.next
l1 = 0
l2 = 0
while cur1 != meet:
cur1 = cur1.next
l1 += 1
while cur2 != meet:
cur2 = cur2.next
l2 += 1
# 后续逻辑跟在两无环链表相交一样
...
pass
if __name__ == "__main__":
link = LinkedLink()
node1 = LinkNode(1)
node2 = LinkNode(2)
node3 = LinkNode(3)
node4 = LinkNode(4)
node5 = LinkNode(5)
node6 = LinkNode(6)
node1.next = node2
node2.next = node3
node3.next = node4
node4.next = node5
node5.next = node6
node6.next = node3
link.head.next = node1
print(circleNode(link.head).value)
|
4b6ac9aa0a2c62eeedf8a2df914cc8fa4c0e0e55 | pickerxxr/CLRS-lab-practice | /Advantage_Shuffle.py | 554 | 3.78125 | 4 | # classic greedy
def advantage_shuffle(arr_1, arr_2):
arr_1_ctr = sorted(arr_1)
arr_1_new = []
for i in arr_2:
ctr = 0
for j in arr_1_ctr:
if j > i:
arr_1_new.append(j)
ctr = 1
break
if ctr == 0:
arr_1_new.append(arr_1_ctr[0])
return arr_1_new
a = [2, 7, 11, 15]
b = [1, 10, 4, 11]
c = [12, 24, 8, 32]
d = [13, 25, 32, 11]
print("A after shuffling:")
print(advantage_shuffle(a, b))
print("C after shuffling:")
print(advantage_shuffle(c, d)) |
59bd6af5bd2c79973183de4e8e7142b74fe1efa9 | ujuc/introcs-py | /introcs/ch1/exp_q/2/1_2_2.py | 253 | 3.546875 | 4 | import math
import sys
from introcs.stdlib import stdio
theta = float(sys.argv[1])
cos = math.cos(theta)
sin = math.sin(theta)
cos_sqrt = cos ** 2
sin_sqrt = sin ** 2
stdio.writeln(f"{cos_sqrt}, {sin_sqrt}")
stdio.writeln(f"{cos_sqrt + sin_sqrt}")
|
aa5aa0ffde657aecf5372241d6d9f6e02dbf4afc | nabilchowdhury/comp551-applied-ml | /Assignment1/Q3.py | 8,436 | 3.625 | 4 | import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
'''
3) Real-life dataset
'''
df = pd.read_csv('./Datasets/communities.csv', header=None)
df[0] = 1
df.drop([i for i in range(1, 5)], axis=1, inplace=True) # These columns are not predictive according to the dataset
df.columns = [i for i in range(df.shape[1])] # Rename columns
df = df.replace('?', np.NaN).astype(np.float64)
'''
Part 1) Fill in missing values
'''
df.fillna(df.mean(), inplace=True)
# print(df.columns[df.isnull().any()].tolist())
N_examples = df.shape[0]
M_cols = df.shape[1]
df = df.sample(frac=1) # This shuffles the examples
data = np.array(df, dtype=np.float64)
'''
Part 2) Fit data and report 5-fold cross-validation error
'''
# Normal equation with regularization (lambda_reg=0 means no regularization)
def fit(X, y, lambda_reg=0):
identity = np.identity(X.shape[1])
# identity[0, 0] = 0 # We do not penalize the bias term
X_square = np.matmul(np.transpose(X), X) + lambda_reg * identity
X_square_inverse = np.linalg.pinv(X_square)
weights = np.matmul(np.matmul(X_square_inverse, np.transpose(X)), y)
return weights
# Gradient descent
def gradient_descent(X, y, lambda_reg=0, alpha=1e-2, epochs=5000, weights=None):
'''
Implementation of vectorized gradient descent with L2 regularization support
:param X: The input matrix N x M, where each row is an example
:param y: The output, N x 1
:param lambda_reg: Regularization hyperparamter (0 means no regularization)
:param alpha: Learning rate
:param epochs: Number of cycles over training data
:param weights: Initial weights can be supplied if desired
:return: The optimal weights after gradient descent
'''
weights = weights if weights is not None else np.random.uniform(high=10, size=[M_cols - 1])
N = len(X)
for epoch in range(epochs):
weights = weights - alpha / N * ( np.matmul(np.transpose(X), np.matmul(X, weights) - y) + lambda_reg * weights)
return weights
def mean_square_error(X, y, W):
y_hat = np.matmul(X, W)
mean_square_err = np.sum(np.square(y - y_hat)) / len(y)
return mean_square_err
def cross_validation_split(X, n_folds=5, filename="file", write_to_csv=False):
'''
Splits the dataset intn n_folds
:param X: The input matrix, N x M
:param n_folds: The number of folds
:param filename: The output file prefix
:param write_to_csv: True if saving each fold required
:return: An array of dictionaries of length n_folds
'''
N = len(X) // n_folds
pairs = []
for i in range(n_folds):
fold_train1 = X[0:i * N]
if i < n_folds - 1:
fold_test = X[i*N:(i+1)*N]
fold_train2 = X[(i+1)*N:]
else:
fold_test = X[i*N:]
fold_train2 = X[N:N]
df_train = pd.DataFrame(np.concatenate((fold_train1, fold_train2)))
df_test = pd.DataFrame(fold_test)
if write_to_csv:
df_train.to_csv('./Datasets/' + filename + '-train' + str(i + 1) + '.csv', header=False, index=False)
df_test.to_csv('./Datasets/' + filename + '-test' + str(i + 1) + '.csv', header=False, index=False)
pairs.append({'train': df_train, 'test': df_test})
return pairs
def write_to_csv(to_df_object, filename, indexname=None):
df_to_csv = pd.DataFrame(to_df_object)
if indexname:
df_to_csv.index.name = indexname
df_to_csv.to_csv(filename + '.csv')
# Generate the files for 5-fold cross-validation
splits = cross_validation_split(data, 5, 'CandC', True)
MSEs_closed_form = []
all_weights = {}
fold = 1
for pair in splits:
X_train = pair['train'].drop([M_cols - 1], axis=1)
y_train = pair['train'][M_cols-1]
X_test = pair['test'].drop([M_cols - 1], axis=1)
y_test = pair['test'][M_cols - 1]
weights = fit(X_train, y_train)
MSEs_closed_form.append(mean_square_error(X_test, y_test, weights))
all_weights['fold' + str(fold)] = weights
fold += 1
MSEs_gd = []
all_weights_gd = {}
weights = np.random.uniform(high=10., size=[M_cols - 1])
fold = 1
for pair in splits:
X_train = pair['train'].drop([M_cols - 1], axis=1)
y_train = pair['train'][M_cols - 1]
X_test = pair['test'].drop([M_cols - 1], axis=1)
y_test = pair['test'][M_cols - 1]
weights_gd = gradient_descent(np.array(X_train), np.array(y_train), epochs=20000, weights=np.copy(weights))
MSEs_gd.append(mean_square_error(X_test, y_test, weights_gd))
all_weights_gd['fold' + str(fold)] = weights_gd
fold += 1
print('least squares:', np.average(MSEs_closed_form))
print('gradient descent:', np.average(MSEs_gd))
# Write weights to file (weight_index refers to w0, w1, etc. The weights for each fold are represented as columns in the csv. There are 5 columns and 123 rows)
write_to_csv(all_weights, 'q3_part2_weights_for_closed_form', 'weight_index')
write_to_csv(all_weights_gd, 'q3_part2_weights_for_gradient_descent', 'weight_index')
'''
Part 3) Ridge-regression: Using only least-squares closed form solution for this part.
'''
INCREMENTS = 100
MSE_vs_lambda = []
lambdas = np.arange(0, 5, 5 / INCREMENTS)
lowest_mse = 999999
best_lambda = -1
for lambda_value in lambdas:
cur_mse = 0
weights_for_folds = {}
fold = 0
for pair in splits:
X_train = pair['train'].drop([M_cols - 1], axis=1)
y_train = pair['train'][M_cols - 1]
X_test = pair['test'].drop([M_cols - 1], axis=1)
y_test = pair['test'][M_cols - 1]
weights = fit(X_train, y_train, lambda_value)
cur_mse += mean_square_error(X_test, y_test, weights)
weights_for_folds['fold' + str(fold)] = weights
cur_mse /= len(splits)
if cur_mse < lowest_mse:
lowest_mse = cur_mse
best_lambda = lambda_value
MSE_vs_lambda.append(cur_mse)
write_to_csv(weights_for_folds, './question3part3/weights_lambda_' + str(lambda_value), 'weight_index')
print('Best lambda:', best_lambda)
for i in range(len(MSE_vs_lambda)):
print('MSE for lambda =', lambdas[i], 'is', MSE_vs_lambda[i])
plt.figure(1)
plt.plot(lambdas[1:], MSE_vs_lambda[1:])
plt.title('Lambda vs MSE')
plt.xlabel('Lambda')
plt.ylabel('MSE')
plt.show()
# Feature selection
# If a feature's associated weight is close to zero, it means that it contributes less to the prediction.
# These features are good candidates for being excluded from the model.
# We can first sort the weights and see which ones contribute the least to prediction
all_weights_feature_selection = {}
fold = 1
for pair in splits:
X_train = pair['train'].drop([M_cols - 1], axis=1)
y_train = pair['train'][M_cols - 1]
X_test = pair['test'].drop([M_cols - 1], axis=1)
y_test = pair['test'][M_cols - 1]
weights = fit(X_train, y_train, lambda_reg=best_lambda) # Regularization with best_lambda from above
all_weights_feature_selection['fold' + str(fold)] = weights
fold += 1
# Now we look for weights that are close to zero in the regularized fit
features_to_drop = set()
for key in all_weights_feature_selection:
w = all_weights_feature_selection[key]
# This basically converts the weight vector [w0, w1...] to [(0, w0), (1, w1),...] so after we sort the weights we know which features they correspond to
all_weights_feature_selection[key] = [(i, abs(w[i])) for i in range(len(w))]
all_weights_feature_selection[key].sort(key=lambda x: x[1])
[features_to_drop.add(x[0]) for x in all_weights_feature_selection[key][:20]]
for val in all_weights_feature_selection.values():
print(val)
MSEs_final = []
all_weights_final = {}
fold = 1
for pair in splits:
X_train = pair['train'].drop([M_cols - 1], axis=1)
y_train = pair['train'][M_cols-1]
X_test = pair['test'].drop([M_cols - 1], axis=1)
y_test = pair['test'][M_cols - 1]
# Drop the features we found to have near 0 coefficients
X_train.drop(list(features_to_drop), axis=1, inplace=True)
X_test.drop(list(features_to_drop), axis=1, inplace=True)
weights = fit(X_train, y_train, lambda_reg=best_lambda)
MSEs_final.append(mean_square_error(X_test, y_test, weights))
all_weights_final['fold' + str(fold)] = weights
fold += 1
print('Number of features to be dropped:', len(features_to_drop))
print('Best lambda:', best_lambda)
print('MSE for best lambda:', lowest_mse)
print('MSE for best lambda after dropping least contributing features:', np.average(MSEs_final))
|
0dba48939a7bfa51e829aafb5d4a3ea53cc1bdca | mnihatyavas/Python-uygulamalar | /Brian Heinold (243) ile Python/p10204.py | 153 | 3.71875 | 4 | # coding:iso-8859-9 Trke
for i in range(10): print ('*' * 10)
for i in range(10): print ('*' * (i+1))
for i in range(10): print ('*' * (10-i))
|
08a6bd2a0ae1a0528a7ab26135c2738196dae764 | nghidinh/python-learning | /FundamentalProgramming/lecture8/StudentScoreMaintenance.py | 4,372 | 3.734375 | 4 | # a = [5, 9, 'Three', 2, 'Six']
# print a[3:]
# print a[:4]
# print a[2:5]
# print a[4]
# print a[-1]
#
# score = [65, 78, 90, 85, 50]
# k = int(raw_input('Student number '))
# if k < 150001 or k > 150005:
# print 'No such student number'
# else:
# print 'score = ', score[k - 150001]
#
# score = [-2, -2, -2, -2, -2]
# while True:
# stID = int(raw_input('Student ID'))
# if 150001 <= stID <= 150005:
# score[stID - 150001] = int(raw_input('seiseki '))
# else: break
# print score
# score = [-2,]*5
# while True:
# stID = int(raw_input('Student ID'))
# if 150001 <= stID <= 150005:
# score[stID - 150001] = int(raw_input('seiseki '))
# else: break
# print score
# while True:
# studentID = int(raw_input('StID'))
# if 150001 <= studentID <= 150005:
# print score[studentID - 150001]
# else: break
# stID1 = int(raw_input('First Student ID')) #the first student
# stID2 = int(raw_input('First Student ID')) #the first student
# score = [-2,]*(stID2 - stID1 + 1)
# while True:
# stID = int(raw_input('Student ID'))
# if 150001 <= stID <= 150005:
# score[stID - 150001] = int(raw_input('seiseki '))
# else: break
# print score
# while True:
# studentID = int(raw_input('StID'))
# if 150001 <= studentID <= 150005:
# print score[studentID - 150001]
# else: break
#
#Detecting which students's scores are missing
# stID1 = int(raw_input('First Student ID')) #the first student
# stID2 = int(raw_input('First Student ID')) #the first student
# score = [-2,]*(stID2 - stID1 + 1)
# while True:
# stID = int(raw_input('Student ID'))
# if 150001 <= stID <= 150005:
# score[stID - 150001] = int(raw_input('seiseki '))
# else: break
# #If all the scores are input and some scores remain -2, then ouput them.
# for stID in range(stID1, stID2 + 1):
# if score[stID - stID1] == -2:
# print 'score for', stID, 'is missing'
#Detecting duplicate registrations of scores
# stID1 = int(raw_input('First Student ID '))
# stID2 = int(raw_input('Last Student ID '))
# score = [-2] * (stID2 - stID1 + 1)
# while True:
# stID = int(raw_input('Student ID'))
# if stID1 <= stID <= stID2:
# if score[stID - stID1] != -2:
# print stID, 'Score is already registered '
# continue
# score[stID - stID1] = int(raw_input('seiseki '))
# else: break
# for stID in range(stID1, stID2+1):
# if score[stID - stID1] == -2:
# print 'score for', stID, 'is missing'
#
# IDs = [0, 0]; IDe = [0, 0]
# IDs[0] = int(raw_input('From 14xxxx: '))
# IDe[0] = int(raw_input('To 14xxxx: '))
# IDs[1] = int(raw_input('From 15xxxx: '))
# IDe[1] = int(raw_input('To 15xxxx: '))
# score14 = [-2,] * (IDe[0] - IDs[0] + 1)
# score15 = [-2,] * (IDe[1] - IDs[1] + 1)
#
# while True:
# stID = int(raw_input('Student ID: '))
# if IDs[0] <= stID <= IDe[0]:
# if score14[stID - IDs[0]] != -2:
# print stID, 'Score is already registered'
# else:
# score14[stID - IDs[0]] = int(raw_input('seiseki'))
# elif IDs[1] <= stID <= IDe[1]:
# if score15[stID - IDs[1]] != -2:
# print stID, 'Score is already registered'
# else:
# score15[stID - IDs[1]] = int(raw_input('seiseki'))
# else: break
#
# for stID in range(IDs[0], IDe[0] + 1):
# if score14[stID - IDs[0]] == -2:
# print 'score for', stID, 'is missing'
# for stID in range(IDs[1], IDe[1] + 1):
# if score15[stID - IDs[1]] == -2:
# print 'score for', stID, 'is missing'
#
n = int(raw_input('How many? '))
IDs = [0, ]* n; IDe = [0, ]*n
for i in range(0, n):
IDs[i] = int(raw_input('From '))
IDe[i] = int(raw_input('To '))
for i in range(0, n):
score[i] = [-2,] * (IDe[i] - IDs[i] + 1)
while True:
stID = int(raw_input('Student ID'))
for i in range(0, n):
if IDs[i] <= stID <= IDe[i]:
if score[i][stID - IDs[i]] != -2:
print stID, 'Score is already registered '
else:
score[i][stID - IDs[i]] = int(raw_input('seiseki '))
else: break
for i in range(0, n):
for stID in range(IDs[i], IDe[i]+1):
if score[i][stID - IDs[i]] == -2:
print 'score for ', stID, 'is missing'
|
ba34128d174c722d46b0c6a213a0593d8f4937eb | mmutiso/svpino_challenge | /find_missing_number.py | 1,028 | 3.765625 | 4 | import random
def data_generator():
array = [i for i in range(1,101)]
random_number = random.randint(1,100)
array.remove(random_number)
random.shuffle(array)
return (array, random_number)
def solution(arr):
'''
create a visited array initialized with all False.
The size of the visited array is the length of 100 + 1
Iterate first time on arr to set visitation
Iterate second time on visited to check unvisited
'''
N = len(arr)
visited_array = [False] * (100+1)
for i in range(N):
element = arr[i]
visited_array[element] = True
for i in range(1, len(visited_array)):
if visited_array[i] == False:
return i
#For the scenario in question we will never get here
if __name__ == "__main__":
(arr, missing_element) = data_generator()
result = solution(arr)
assert result == missing_element
(arr, missing_element) = data_generator()
result = solution(arr)
assert result == missing_element
|
235093da6c5dd075d79da9d3007ae69c44f11528 | NicolasBaak/primeros_programas_python | /Funciones/clase.py | 628 | 3.9375 | 4 | #Nos piden diseñar un procedimiento que recibe como datos las dos listas y una cadena con
#el nombre de un estudiante. Si el estudiante pertenece a la clase, el procedimiento imprimirá
#su nombre y nota en pantalla. Si no es un alumno incluido en la lista, se imprimirá un mensaje
#que lo advierta.
def muestra_nota_de_alumno(alumnos, notas, alumno_buscado):
encontrado = False
for i in range(len(alumnos)):
if alumnos[i]==alumno_buscado:
print(alumno_buscado,notas[i])
return
if not encontrado:
print('El alumno {0} no pertenece al grupo.'.format(alumno_buscado)) |
277dcda3a4abcf5244545b7390576e044f9770dc | MihailoJoksimovic/cs6006-implementations | /depth_first.py | 1,582 | 3.859375 | 4 | # Implement depth first graph search. Try implementing edge classification and topological sort as well
# How to represent graphs? 1. Adjacency lists, 2. Objects
graph = {
'a': ['b', 'd'],
'b': ['e'],
'c': ['e', 'f'],
'd': ['b'],
'e': ['d', 'g'],
'f': [],
'g': ['d']
}
visiting_order = []
def depth_first_search(start_node, adjacency_list, parents, visiting):
neighbors = adjacency_list[start_node]
print("Visiting {}".format(start_node))
visiting[start_node] = True
for neighbor in neighbors:
if neighbor in visiting:
print("Found a back-edge from {} to {}".format(start_node, neighbor))
if neighbor not in parents:
parents[neighbor] = start_node
depth_first_search(neighbor, adjacency_list, parents, visiting)
del visiting[start_node]
visiting_order.append(start_node)
# depth_first_search('a', graph)
# Now lets make sure to visit ALL vertices
parents = {}
for vertex in graph.keys():
if vertex in parents:
continue
parents[vertex] = None
depth_first_search(vertex, graph, parents, visiting = {})
visiting_order.reverse()
print(visiting_order)
print("New graph!!!")
graph = {
5: [11],
7: [8, 11],
3: [8, 10],
11: [2, 9, 10],
8: [9],
2: [],
9: [],
10: []
}
visiting_order = []
parents = {}
for vertex in graph.keys():
if vertex in parents:
continue
parents[vertex] = None
depth_first_search(vertex, graph, parents, visiting = {})
visiting_order.reverse()
print(visiting_order) |
5d1ae44cfc5234ccbfcfcf12782be925619d646b | r-hague/Python_work | /Loan_time_payment.py | 2,057 | 4.21875 | 4 | import math
myFunc = input("Press 1 to calculate payment amount for a given duration and principal. \n Press 2 to calculate duration for a given payment amount and principal. \n Press 3 to calculate principal for a given duration and payment amount: ")
interestRate = input("Interest rate (%): ")
r = interestRate / 1200
if myFunc == 1:
loanValue = input("Principal ($): ")
duration = input("Loan duration (months): ")
payment1 = (r*loanValue)/(1-((1+r)**(-1*duration)))
payment = int(math.ceil(payment1))
print "Monthly payment is $", payment
totalPaid = payment*duration
totalInterest = totalPaid-loanValue
print "Total paid is $", totalPaid, " and the interest paid is $", totalInterest
print "month interest balance"
elif myFunc == 2:
loanValue = input("Principal ($): ")
payment = input("Loan payment ($): ")
duration1 = (-1*math.log(1-((r*loanValue)/payment)))/(math.log(1+r))
duration2 = int(math.ceil(duration1))
dur_yr = float(duration2)/12
print "Loan duration is ", duration2, " months or ", dur_yr, " years "
totalPaid = payment*duration2
totalInterest = totalPaid-loanValue
print "Total paid is $", totalPaid, " and the interest paid is $", totalInterest
print "month interest balance"
elif myFunc == 3:
payment1 = input("Loan payment ($): ")
duration = input("Loan duration (months): ")
loanValue1 = payment1*((1-(1+r)**(-1*duration))/r)
loanValue = int(math.ceil(loanValue1))
print "Loan principal is $", loanValue
payment = int(math.ceil(payment1))
totalPaid = payment * duration
totalInterest = totalPaid - loanValue
print "Total paid is $", totalPaid, " and the interest paid is $", totalInterest
print "month interest balance"
else:
print "error"
loanBalance = loanValue
i = 1
while loanBalance > 0.01:
interest = (interestRate/1200)*loanBalance
loanBalance = (interest + loanBalance) - payment
print i, interest, loanBalance
i += 1
|
c59f9438bcff90694fd5938c20285707498adc18 | matyama/zal-tutorials | /tutorial04.py | 2,239 | 4.5 | 4 | #!/usr/bin/env python3
import math
from combinatorics import factorial
def range_sum_loop(a, b):
pass
def range_sum_func(a, b):
pass
def range_sum_expr(a, b):
pass
def euler_naive(num_iters):
pass
def euler(num_iters):
pass
def sqrt(x):
pass
def prime(n):
pass
if __name__ == '__main__':
# function range(n) creates a generator/iterator of numbers from interval [0,n), the default step is 1
r = range(10)
print(r, type(r))
# in order to display the sequence, we can use list() constructor
print(list(r))
# one can also define the initial element - in this case the sequence starts with 1
r2 = range(1, 5)
print(list(r2))
# typical usage is in a for loop - the body is in this case evaluated for i = 2, 4, 6, 8
for i in range(2, 10, 2):
print(i)
print('continue, break:')
# with any loop comes in hand pair of statements: continue and break
for i in range(5):
if i == 1:
# when continue is called, the rest of the block is not evaluated and the loop continues with next iter.
continue
if i == 3:
# when break is called, the loop execution breaks at this point and we continue after the loop body
break
print(i)
print('while:')
# next loop type is while which iterates while it's loop condition is satisfied
x = 2
while x ** 2 < 100:
print(x ** 2)
x += 2
# advanced usage of for is "list comprehension"
squares = [x ** 2 for x in range(2, 10, 2)]
print(type(squares), squares)
# one can even use if filter in list comprehensions
odd = [x for x in range(1, 10) if x % 2 == 1]
print(odd)
# how to create your own generator? - simply use () in comprehension
even = (2 * k for k in range(10))
print(type(even), even, list(even))
print('range_sum:')
print(range_sum_loop(2, 10))
print(range_sum_func(2, 10))
print(range_sum_expr(2, 10))
print("euler's number:")
print(euler_naive(100))
print(euler(100))
print(math.e)
print('sqrt:')
print(sqrt(5.))
print(math.sqrt(5.))
print('primality test')
print(prime(13))
print(prime(256))
|
ecc5c3563103ce17063704276583c3bd529a4110 | YosraAouini/pandas-numpy | /world_statistics_data.py | 3,085 | 3.96875 | 4 | # world_data.py
#
# A terminal-based application for computing and printing statistics based on given input.
# Detailed specifications are provided via the Assignment 5 git repository.
# You must include the main listed below. You may add your own additional classes, functions, variables, etc.
# You may import any modules from the standard Python library, including numpy and pandas.
# Remember to include docstrings and comments.
## Import librairies
import pandas as pd
import warnings
warnings.filterwarnings("ignore")
def main():
# Stage 1: Import data
print("ENSF 592 World Data")
## Import data
data=pd.read_csv('Assign5Data.csv',header=0, delimiter=";")
## Set index
index = pd.MultiIndex.from_frame(data[['UN Region', 'UN Sub-Region','Country']])
data.set_index(index,inplace=True)
##
#Define function region_valid to raise error when the sub-region doesn't exist
def region_valide(sub_region):
if sub_region not in data['UN Sub-Region'].unique():
raise ValueError("You must enter a valid UN sub-region name")
#Using the while functionality, the user can enter many time the sub-region name until he enter a valid name
sub_region = None
while sub_region is None:
input_value = str(input("Please enter a sub-region name: "))
try:
# try and convert the string input to a number
region_valide(input_value)
sub_region=input_value
except ValueError:
# tell the user off
print("You must enter a valid UN sub-region name".format(input=input_value))
## Select data concerning the sub region
data_r=data[data['UN Sub-Region']==sub_region ]
## Define the find_null()` to determine whether any area data is missing for the chosen sub-region.
def find_null(sub_region_name):
data_km=data_r['Sq Km']
if len(data_km[data_km.isnull()])!=0:
return data_km[data_km.isnull()]
else:
print("There are no missing sq km values for this sub-region.")
print("Sq Km measurements are missing for:")
print(find_null(sub_region ))
print("Calculating change in population and latest density")
## Calculate change in population
data_r['change_pop']=data_r['2020 Pop'] - data_r['2000 Pop']
## Calculate population density
data_r["population_density"]=data_r['2020 Pop']/data_r['Sq Km']
print(data_r.iloc[:,3:])
print("Number of threatened species in each country of the sub-region:")
species =data_r[['Plants (T)','Fish (T)','Birds (T)','Mammals (T)']]
data_r["species_number"] = species.sum(axis=1)
print(data_r[['Plants (T)','Fish (T)','Birds (T)','Mammals (T)','species_number']])
print("The calculated sq km area per umber of threatened species in each country is:")
data_r['species_density']=data_r['Sq Km']/data_r['species_number']
print(data_r['species_density'])
if __name__ == '__main__':
main()
|
990f06031119e8d514d26f48a1d2896426edb5f7 | 531621028/python | /函数式编程/filter.py | 964 | 3.921875 | 4 | #和map()类似,filter()也接收一个函数和一个序列。和map()不同的是,filter()把传入的函数依次作用于每个元素,然后根据返回值是True还是False决定保留还是丢弃该元素
def is_odd(x):
return x % 2 == 1
print(list(filter(is_odd,[1,2,3,4,5,6,7,8,9])))
#注意到filter()函数返回的是一个Iterator,也就是一个惰性序列,所以要强迫filter()完成计算结果,需要用list()函数获得所有结果并返回list
def _odd_iter():
n = 1
while True:
n = n + 2
yield n
def _not_divisible(n):
return lambda x : x % n > 0
def primes():
yield 2
it = _odd_iter()
while True:
n = next(it)
yield n
it = filter(_not_divisible(n),it)
for n in primes():
if n < 1000:
pass
else:
break
def is_palindrome(n):
y = n
sum = 0
while y != 0:
x = y % 10
y = int(y / 10)
sum = sum * 10 + x
return sum == n
output = filter(is_palindrome, range(1, 1000))
print(list(output)) |
9f24f047b3966e31dc38ce21ca8f3a261f692bd1 | Shubham-cod/Data-Reporting | /data_report_server.py | 1,207 | 3.765625 | 4 |
#################################### creating socket TCP server to recieve the data #########################################
import socket
import pickle
HOST = '127.0.0.1' # hostname or IP address
PORT = 65432 # Port to listen
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s.bind((HOST, PORT)) #assigning socket as a server socket
s.listen(5) #listens to incoming client signal
conn, addr = s.accept() #accepts the signal from client and connection is established
from_client = b"" #variable to concatenate and store recieved data
with conn:
print('Connected by', addr)
while True:
data = conn.recv(3000024)
if not data:
break
else:
from_client += data #concatenating recieving data
data_rec = pickle.loads(data) #unpickling/extracting recieved data
print(data_rec) #printing recieved data
s.close()
############################################################### END ###########################################################
|
e7f8e237f7c0cc8b3645a4d3efa4dd7d586fabf4 | awesomediff/cs207-FinalProject | /awesomediff/core.py | 12,946 | 4.09375 | 4 | import math
import numpy as np
class variable:
def __init__(self,val,der=1):
"""
Initialize a variable object
with a specified value and derivative.
Expect scalar for val. Expect scalar
or a numpy array for der.
If no derivative is specified,
a seed of 1 is assumed.
"""
self._val = val
assert isinstance(der, (np.ndarray, float, int)), "der must be a scalar or a numpy array"
self._der = der
@property
def val(self):
return self._val
@property
def der(self):
return self._der
def __repr__(self):
"""
Define representation of variable object:
"""
return "awesomediff.variable(val={},der={})".format(self.val,self.der)
def __neg__(self):
"""
Overload negation.
Returns a variable object with:
val : negated value.
der : negated derivative.
"""
return variable(val=-self.val,der=-self.der)
def __add__(self,other):
"""
Overload addition.
Returns a variable object with:
val : sum of values.
der : sum of derivatives.
"""
self_val = self.val
self_der = self.der
try:
# Assume other object is a variable:
other_val = other.val
other_der = other.der
except:
# If not, use this value and derivative 0.
try:
float(other)
except:
raise ValueError("{} is not a number.".format(other))
other_val = other
other_der = 0 # Derivative of a constant is zero.
# Calculate new values (simple summation):
new_val = self_val + other_val
new_der = self_der + other_der
# Return variable with new value and derivative:
return variable(val=new_val,der=new_der)
def __radd__(self,other):
"""
Overload reverse addition by calling __add__().
"""
return self.__add__(other)
def __mul__(self,other):
"""
Overload multiplication.
Returns a variable object with:
val : product of values.
der : result of product rule
"""
self_val = self.val
self_der = self.der
try:
# Assume other object is a variable:
other_val = other.val
other_der = other.der
except:
# If not, uses this value and derivative 0.
try:
float(other)
except:
raise ValueError("{} is not a number.".format(other))
other_val = other
other_der = 0 # Derivative of a constant is zero.
# Calculate new values (applying product rule):
new_val = self_val * other_val
new_der = (self_der * other_val) + (self_val * other_der)
# Return variable with new value and derivative:
return variable(val=new_val,der=new_der)
def __rmul__(self,other):
"""
Overload reverse multiplication
Calls __mul__.
"""
return self.__mul__(other)
def __sub__(self,other):
"""
Overload subtraction.
Implemented using negation and addition.
"""
return self.__add__(-other)
def __rsub__(self,other):
"""
Overload reverse subtraction.
Implemented using negation and addition.
"""
return self.__neg__().__add__(other)
def __truediv__(self, other):
try:
# assume other is an instance variable
new_val = self.val / other.val
new_der = (self.der * other.val - self.val * other.der) / other.val ** 2
except:
# assume in the form of variable/scaler
try:
float(other)
except:
raise ValueError("{} is not a number or instance variable.".format(other))
if float(other) == 0:
raise ZeroDivisionError('Cannot perform division by zero')
new_val = self.val / float(other)
new_der = self.der / float(other)
return variable(val=new_val, der=new_der)
def __rtruediv__(self, other):
new_val = other / self.val
new_der = -other * self.val ** (-2) # other*self.pow(-1)
return variable(val=new_val, der=new_der)
def __eq__(self, other):
"""
Overload equal
Check if the thing compared to is a variable and has the same vale
"""
return isinstance(other, variable) and self.val == other.val
def __ne__(self, other):
"""
Overload not equal
Check if the thing compared to is a variable and does not have the same vale
"""
return not isinstance(other, variable) or not (self.val == other.val)
def __lt__(self, other):
"""
Overload less than
"""
try:
return self.val<other.val
except:
raise AttributeError("Can only compare varibles.")
def __gt__(self, other):
"""
Overload greater than
"""
try:
return self.val>other.val
except:
raise AttributeError("Can only compare varibles.")
def __le__(self, other):
"""
Overload less than or equal to
"""
try:
return self.val<=other.val
except:
raise AttributeError("Can only compare varibles.")
def __ge__(self,other):
"""
Overload greater than or equal to
"""
try:
return self.val>=other.val
except:
raise AttributeError("Can only compare varibles.")
def __pow__(self, other):
try:
# check whether other is a number
new_val = self.val ** other
except:
raise ValueError("{} must be a number.".format(other))
new_der = other * self.val ** (other - 1) * self.der
return variable(val=new_val, der=new_der)
def __rpow__(self, other):
try:
new_val = other** self.val
except:
raise ValueError("{} must be a number.".format(other))
new_der = other**self.val * np.log(other)
return variable(val=new_val, der=new_der)
def _build_jacobian(outputs):
"""
INPUT:
outputs: a list of awesomediff.variable objects
OUTPUT:
returns n x m jacobian matrix where n is the number of functions
and m is the total number of variables
EXAMPLE:
outputs = [awesomediff.variable(val=5, der=[4]), awesomediff.variable
(val=0.5, der=[0.5])]
## _build_jacobian(outputs)
[[4]
[0.25]]
"""
n = len(outputs) # get number of functions
m = len(outputs[0].der) # get number of variables
jacobian = np.zeros((n,m))
for i, output in enumerate(outputs):
jacobian[i,:] = output.der
return jacobian
def evaluate(func,vals,seed=None):
"""
A wapper function that evaluates a user-defined function
using awesomediff.variable objects.
INPUTS:
func: A user-defined function of n variables and m functions
that will be evaluated to find the value and derivative
at a specified point.
The user-defined function may take one or more variables
as arguments and may return one or more function outputs (as a list).
Functions may include basic operations (+,*,etc),
as well as any special functions supported by awesomediff.
vals: A scalar (for univariate function) or a list of scalars
(for multivariate function) at which to evaluate the function
and its derivative.
seed: A scalar (for univariate function) or a list of lists (for multivariate
function) containing seed values for each variable. The lengths of the
outer list and inner list must equal the number of arguments taken by `func`
(i.e. the number of variables). Defaults to a seed of 1 for each
variable if no seed value is provided.
EXAMPLE:
To set seed of variables x, y, z at 1, 2, and 3, respectively, user
passes the following list of lists as seed:
[[1,0,0],[0,2,0],[0,0,3]]
The length of outer list and the lengths of each of the inner lists
must be equal to the total number of variables (in this example, 3)
...
RETURNS:
output_value: value of function at a specified point. A scalar for
a function, a vector of scalars for a vector function
jacobian: the jacobian of function. A vector of scalar or scalars
for univariate and multivariate functions, respectively. A matrix of
scalars for univariate and multivariate vector functions
...
EXAMPLE:
## def parametric_ellipse(a,b,t):
x = a * ad.cos(t)
y = b * ad.sin(t)
return [x, y]
## output_value, jacobian = ad.evaluate(func=parametric_ellipse,vals=[4,2,0])
## output_value
np.array([4, 0]) # [a*cos(t), b*sin(t)]
## jacobian
np.array([[1,0,0],[0,0,4]]) #[[cos(t), 0, -a*sin(t)],[0 , sin(t), a*cos(t)]]
"""
## check user input for vals and convert it to numpy array
# user input for vals will be a scalar for univariate function and
# a list of scalars for multivariate function
try:
float(vals) # if vals is a scalar
vals = np.array([vals])
except:
if isinstance(vals, list): # if vals is a list
vals = np.array(vals)
## get number of values that were passed as inputs
num_vars = len(vals)
## check user input for seed
# user input for seed will be a scalar for univariate function and
# a list of scalars for multivariate function
# if user doesn't pass in value for seed argument, create seed with value of 1
if seed == None:
if num_vars == 1: #if univariate function
seed = np.array([1])
else: #if multivariate function
seed_matrix = np.identity(num_vars)
#if user passes in value for seed argument
else:
try:
float(seed) # if seed is a scalar
seed = np.array([seed])
except:
if isinstance(seed, list): # if seed is a list
# check length of outer list
assert len(seed) == num_vars, "length of outer list must equal number of variables"
# check length of inner list
for s in seed:
try:
len(s)
except: # seed for univariate function given as a list
raise ValueError("seed for univariate function should be given as a scalar")
assert len(s) == num_vars, "length of inner list must equal number of variables"
seed_matrix = np.array(seed)
else: # if seed is not provided as a scalar or a list
raise ValueError("seed must be provided as a scalar or a list")
## evaluate the user-defined function passed in
# instantiate awesomediff.variable objects
if num_vars == 1: # if univariate function
var = variable(val=vals[0], der=seed)
inputs = [var]
else: # if multivariate function
inputs = []
for i,v in enumerate(vals):
var = variable(val=v,der=seed_matrix[i,:])
inputs.append(var)
# pass awesomediff.variable objects into user-defined function
# outputs will be an awesomediff.variable object or a list of
# awesomediff.variable objects storing values and derivatives of functions
try:
outputs = func(*inputs)
except Exception as e:
raise RuntimeError("function evaluation failed with the following error: {}".format(e))
# create output_value and jacobian
try: # if a vector-function
len(outputs)
output_value = np.zeros(len(outputs))
for i,output in enumerate(outputs):
output_value[i] = output.val
jacobian = _build_jacobian(outputs)
except: # if not a vector function
output_value = outputs.val
jacobian = outputs.der
return output_value, jacobian
|
aaeee0275cbd100624c088e4966234edb4aa4226 | crystal616/8480Group | /code/recom.py | 7,250 | 3.546875 | 4 | '''
recom.py
Author: Ying Cai
Date: 11/10/12
Description:
Compute movie similarity.
Analyze user's watching list, select similar movies and recommend.
Compute the recall and precision of the recommendation list.
'''
import pandas as pd
import numpy as np
import scipy as sp
import math
import json
#cleaned full movie_genre dataset
movie_genre = pd.read_csv("movie_left.csv")
movieId2title = {}
index2movieId={}
movieId2index={}
for i in range(0,len(movie_genre)):
movieId=movie_genre.at[i, 'movieId']
title=movie_genre.at[i,'title']
movieId2title[movieId]=title
index2movieId[i]=movieId
movieId2index[movieId]=i
movie_genre.drop(columns="title")
row = movie_genre.shape[0]
print(row)
genre_matrix = np.zeros((row, 20 + 1), dtype = int)
#movie genres
names = ["Action","Adventure","Animation","Children","Comedy","Crime","Documentary","Drama","Fantasy","Film-Noir","Horror","Musical","Mystery","Romance","Sci-Fi","Thriller","War","Western","IMAX","(no genres listed)"]
print(len(names))
genres = movie_genre["genres"]
print(genres.shape)
for i in range (0, row):
id = int(movie_genre.iloc[[i]]["movieId"])
genre_matrix[i][0] = id
strs = movie_genre.at[i, "genres"].split("|")
for g in strs:
loc = names.index(g)+1
genre_matrix[i][loc] = 1
genre_matrix = genre_matrix[:,1:21]
genre_matrix_T = genre_matrix.transpose()
#compute cosine similarity
similarity_matrix = np.dot(genre_matrix, genre_matrix_T)
cosine_sim = similarity_matrix
cosine_sim = cosine_sim.astype(float)
sqrt=[]
for i in range(0,len(cosine_sim[0])):
sqrt.append(math.sqrt(cosine_sim[i][i]))
for r in range (0, row):
for l in range (r, row):
if (cosine_sim[r,l] != 0):
cosine_sim[r,l] = cosine_sim[r,l] / (sqrt[r]*sqrt[l])
cosine_sim[l,r] = cosine_sim[r,l]
#compute recall and precision of recommendation
def recall_precision (pred_list, real_dict):
count = 0
real_count = len(real_dict)# or len(real_list)
pred_count = len(pred_list)
if real_count == 0:
return 0.0,0.0
for user in pred_list:
user = str(user)
if real_dict.get(user,0) != 0:
count = count + 1
recall = count / real_count
precision = count / pred_count
return recall, precision
#generate similar movie list, total # of chosen movies >= nn
def select_movie_basedon_similarity (similarity_matrix, movieIndex,nn,step):
IDs = []
similarity_list = similarity_matrix[movieIndex,:]
size = similarity_list.shape[0]
limit = 0.99+step
#choose movies whose similarity > 0.99. If we don't have >=nn movies selected,
#decrease the threshold of similarity by one "step", start a new iteration
while len(IDs) < nn:
limit = limit - step
for i in range (0, size):
if similarity_list[i] >= limit and i != movieIndex:
m_ID = index2movieId[i]
IDs.append(m_ID)
return IDs
def pred_list (movieId_list, movie_user_dict): ##Here must user movieId not index
user_list = []
for movieId in movieId_list:
user_list.extend(list(movie_user_dict[str(movieId)].keys()))
user_list = list(set(user_list))
return user_list
def real_list (movie_user_dict, movieId):
m_dict = movie_user_dict.get(str(movieId))
return m_dict
def rec_movie_list(userId, user_movie_train_dict, movie_user_train_dict, similarity_matrix,cutOff, listLength, nn, step):
select_movie = []
watched_list = user_movie_train_dict.get(str(userId))
#compute the mean of all ratings
mean = sum(watched_list.values()) / float(len(watched_list))
if cutOff != 0:
maxRating=max(watched_list.values())
mean = mean + (maxRating-mean)/2
#examine if an user "like" or "dislike" a particular movie
for key in watched_list:
if watched_list.get(key) >= mean:
index=movieId2index[int(key)]
select_movie.extend(select_movie_basedon_similarity(similarity_matrix, index, nn, step))
select_movie = list(set(select_movie))
if len(select_movie) > listLength: #recommend 50, 100 or 150 movies
temp_list = []
for movie in select_movie:
temp_list.append((movie, len(movie_user_train_dict.get(str(movie)))))
temp_list.sort(key=sortSecond, reverse=True)
list_50 = temp_list[:listLength]
select_movie = []
for i in range (0, listLength):
select_movie.append(list_50[i][0])
return select_movie
def sortSecond(val):
return val[1]
def movie_realwatch_list (user_movie_test_dict, userId):
userId = str(userId)
return user_movie_test_dict.get(userId,{})
with open("user_movie_train_dict.json") as f:
user_movie_train_dict = json.load(f)
f.close
with open("movie_user_train_dict.json") as f:
movie_user_train_dict = json.load(f)
f.close
with open("user_movie_test_dict.json") as f:
user_movie_test_dict = json.load(f)
f.close
rating=pd.read_csv('rating_left.csv')
userlist = np.random.choice(rating.userId.unique(), 1000)
recall = []
precision = []
# threshold for choosing neighbor
steps = [0.02,0.1]
# number of nearest neighbor
nn = [1,3,5,10]
# use mean for threshold of preference
cutOffs = [0,1]
# length of recommendation list
listLengths = [50, 100, 150]
# generate list and compute recall and precision
for step in steps:
for k in nn:
for cutOff in cutOffs:
for listLength in listLengths:
for userId in userlist:
select_movies=rec_movie_list(userId, user_movie_train_dict, movie_user_train_dict,cosine_sim,cutOff,listLength, k, step)
real_watch=movie_realwatch_list(user_movie_test_dict, userId)
a, b = recall_precision (select_movies, real_watch)
recall.append(a)
precision.append(b)
print('recall: ',a, ' precision: ', b)
with open('recall-movie2user-cutOff'+str(cutOff)+'-L'+str(listLength)+'-k'+str(k)+'-step'+str(step)+'.json', 'w') as outfile:
json.dump(recall, outfile)
with open('precision-movie2user-cutOff'+str(cutOff)+'-L'+str(listLength)+'-k'+str(k)+'-step'+str(step)+'.json', 'w') as outfile:
json.dump(precision,outfile)
with open("movie_user_dict.json") as f:
movie_user_dict = json.load(f)
f.close()
recall=[]
precision=[]
# compute recall and precision to find an optional "step" value
for step in steps:
for k in nn:
for i in range(row):
recom_movies=select_movie_basedon_similarity(cosine_sim,i, k, step)
pred=pred_list(recom_movies,movie_user_dict)
real=real_list(movie_user_dict, index2movieId[i])
a, b = recall_precision (pred, real)
recall.append(a)
precision.append(b)
print('recall: ',a, ' precision: ', b)
with open('recall-user2movie-step'+str(step)+'-k'+str(k)+'.json', 'w') as outfile:
json.dump(recall, outfile)
with open('precision-user2movie-step'+str(step)+'-k'+str(k)+'.json', 'w') as outfile:
json.dump(precision,outfile)
|
8b6181752ad87fc8c37b98bdb9f3cbbd159746eb | pinkrespect/HappyHappyAlgorithm | /test_score.py | 212 | 3.53125 | 4 | import stdin from sys as read
score = int(read.readline().rstrip())
if score > 89:
print("A")
elif score > 79:
print("B")
elif score > 69:
print("C")
elif score > 59:
print("D")
else: print("F")
|
78f3ae2d87f3a3d494feff8186737798caeb6379 | syurskyi/Python_Topics | /125_algorithms/_examples/_algorithms_challenges/pybites/beginner/1/summing.py | 621 | 3.75 | 4 | def sum_numbers(numbers=None):
total = 0
if numbers == None:
for i in range(1,101):
total = total + i
elif len(numbers) == 0:
total = 0
elif isinstance(numbers, list) or isinstance(numbers, tuple):
for i in numbers:
total = total + i
elif not isinstance(numbers, list) or not isinstance(numbers, tuple):
count = len(numbers)
for i in range(0,count):
total = total + numbers[i]
return total
# The isinstance() function checks if the object (first argument) is an instance or subclass of classinfo class (second argument). |
ea1b63f1c1810daff85f30ef678b9ed47eb5a6d8 | KARTHICKMUTHUSAMY/beginer | /detective saikat.py | 168 | 3.765625 | 4 | def stair():
x=0
y=[]
z=int(input())
for i in range(z):
y.append(int(input()))
for i in y:
x+=(z-i)
print(x)
try:
stair()
except:
print('invalid')
p
|
6a681d0495baf3f0ce68b022ebccdbff043341a4 | binarioGH/codewars | /simpletrans.py | 204 | 3.703125 | 4 | #-*-coding: utf-8-*-
def encode(text):
plain_text = ["", ""]
index = 0
for symbol in text:
plain_text[index] += symbol
if index == 0:
index += 1
else:
index -= 1
return "".join(plain_text) |
93fa93c1ab92ebed9582be1a5699b6eb63d8072a | YaroslavGavrilychev/Python_1594 | /HW3.py | 885 | 3.640625 | 4 | name_percent_main_part = 'процент'
while True:
try:
percent_from_input = int(input('Введите пожалуйста число от 1 до 20: '))
except:
print('Пожалуйста введите целое число')
else:
if percent_from_input < 1 or percent_from_input > 20:
print('Ваше число не входит в диапазон от 1 до 20')
else:
break
def get_percent_full_name(percent):
suffix = get_percent_suffix(percent)
return f'{percent} {name_percent_main_part}{suffix}'
def get_percent_suffix(percent):
if percent > 4:
return 'ов'
if percent > 1:
return 'а'
return ''
print(get_percent_full_name(percent_from_input))
print('Все склонения от 1 до 20:')
for i in range(1, 21):
print(get_percent_full_name(i)) |
37c9a4b0920c424e1c5b4bd34b3b7a9098a9083b | Adam-Of-Earth/holbertonschool-higher_level_programming | /0x06-python-classes/1-square.py | 323 | 3.875 | 4 | #!/usr/bin/python3
"""a class Square
Description of a square class
"""
class Square:
"""square shape
infomation about the square and how to use it
"""
def __init__(self, size):
"""Create a square size large
size(int): how large the size wil be
"""
self.__size = size
|
b6d4d895080d924b49da87976f8e9604a8e80fbf | green-fox-academy/balazsbarni | /week04/day01/09-teachers-and-students.py | 561 | 3.671875 | 4 | #### Teacher Student
#- Create `Student` and `Teacher` classes
#- `Student`
# - learn()
# - question(teacher) -> calls the teachers answer method
#- `Teacher`
# - teach(student) -> calls the students learn method
# - answer()
class Student(object):
def question(self, teacher):
teacher.answer()
def learn(self):
print("IDK")
class Teacher(object):
def teach(self, student):
student.learn()
def answer(self):
print("Ans")
stud = Student()
teach = Teacher()
stud.question(teach)
teach.teach(stud) |
b11c5aaca7509dea3a7f0c9ed54defabc3a01811 | twtrubiks/python-notes | /__len__tutorial.py | 710 | 3.734375 | 4 | class Product(object):
def __init__(self):
self.items = [
{
'id': 1,
'value': 10
},
{
'id': 2,
'value': 20
},
{
'id': 3,
'value': 30
},
{
'id': 4,
'value': 40
}
]
def __len__(self):
return sum(item['value'] for item in self.items)
if __name__ == "__main__":
data = 'test'
print('data.__str__(): {}'.format(data.__len__()))
print('len(data): {}'.format(len(data)))
product = Product()
print('len(product): {}'.format(len(product)))
|
f70f0c5b5a05003fb026b312a535cdf8fece228c | npankaj365/survivor-bias | /luck.py | 2,344 | 3.546875 | 4 | import random
import colorama
import persons
import argparse
def show_top(persons, number):
count = 0
for person in persons[:number]:
if person.talent_rank < number:
count += 1
print(colorama.Fore.GREEN, end='')
elif person.talent_rank < number * 2:
print(colorama.Fore.YELLOW, end='')
print(person, end='')
print(colorama.Fore.RESET)
return count
arg_parser = argparse.ArgumentParser(
description="Simulation of importance of Luck in Success.")
arg_parser.add_argument('--batch', dest='batch', type=int, default=10,
help="how many batch of simulation to run. (10)")
arg_parser.add_argument('--size', dest='size', type=int, default=1000,
help="how many persons to put in each batch. (1000)")
arg_parser.add_argument('--choose', dest='choose', type=int, default=10,
help="how many people to choose at the top. (10)")
arg_parser.add_argument('--luck_factor', dest='lf', type=float, default=0.1,
help="how important is the luck. (0.1)")
arg_parser.add_argument('--seed', dest='seed', default=None,
help="seed value for random.")
arg_parser.add_argument('--verbose', dest='verbose', action='store_true',
help="verbose output.")
args = arg_parser.parse_args()
if args.seed:
random.seed(args.seed)
persons.Person.LUCK_FACTOR = args.lf
data = []
for i in range(args.batch):
ps = persons.get_persons(args.size)
if args.verbose:
print(f'Experiment: {i+1}')
both = show_top(ps, args.choose)
color = colorama.Fore.BLACK
if both > 4:
color += colorama.Back.GREEN
elif both > 2:
color += colorama.Back.YELLOW
else:
color += colorama.Back.RED
print('Would have Accepted Anyway: ', end='')
print(color + f'{both}' + colorama.Back.RESET + colorama.Fore.RESET)
else:
both = sum(map(lambda p: p.luck_rank < args.choose, ps[:args.choose]))
data.append(both)
freq_table = [0 for i in range(args.choose+1)]
for d in data:
freq_table[d] += 1
most_freq = max(freq_table)
for i, entry in enumerate(freq_table):
print(f'{i:2d} ', end='')
print('█' * (entry * 50 // most_freq) + f' {entry}')
|
d3dff9d3eb34385cca871f0fe8f2fb16d747ff98 | kgashok/pygorithm | /pygorithm/sorting/tim_sort.py | 3,625 | 4.5 | 4 | def inplace_insertion_sort(arr, start_ind, end_ind):
"""
Performs an in-place insertion sort over a continuous slice of an
array. A natural way to avoid this would be to use numpy arrays,
where slicing does not copy.
This is in-place and has no result.
:param arr: the array to sort
:param start_ind: the index to begin sorting at
:param end_ind: the index to end sorting at. This index is excluded
from the sort (i.e., len(arr) is ok)
"""
for i in range(start_ind + 1, end_ind):
current_number = arr[i]
for j in range(i - 1, start_ind - 1, -1):
if arr[j] > current_number:
arr[j], arr[j + 1] = arr[j + 1], arr[j]
else:
arr[j + 1] = current_number
break
# iterative Timsort function to sort the
# array[0...n-1] (similar to merge sort)
def tim_sort(arr, run=32):
"""
Tim sort algorithm. See https://en.wikipedia.org/wiki/Timsort.
This is performed in-place.
:param arr: list of values to sort
:param run: the largest array that is sorted with an insertion sort.
:return: the sorted array
"""
# Sort individual subarrays of size run
for i in range(0, len(arr), run):
inplace_insertion_sort(arr, i, min(i + run, len(arr)))
# start merging from size RUN (or 32). It will merge
# to form size 64, then 128, 256 and so on ....
size = run
while size < len(arr):
# pick starting point of left sub array. We
# are going to merge arr[left..left+size-1]
# and arr[left+size, left+2*size-1]
# After every merge, we increase left by 2*size
for left in range(0, len(arr), 2 * size):
# find ending point of left sub array
# mid+1 is starting point of right sub array
mid = left + size
right = min(left + (2 * size), len(arr))
# merge sub array arr[left.....mid] &
# arr[mid+1....right]
merge(arr, left, mid, right)
size = 2 * size
return arr
def merge(arr, left, mid, right):
"""
Merge of two sections of array, both of which are individually
sorted. The result is that the entire chunk is sorted. Note that right
edges are exclusive (like slicing).
This modifies the passed array, but requires a complete copy of the array.
.. code:: python
merge([0, -1, 1, 3, 2, 4], 2, 4, 6) # [0, -1, 1, 2, 3, 4]
:param arr: the array which should have a portion sorted in-place
:param left: the left-most index which is included in the merge
:param mid: the first index that belongs to the second section
:param right: the right-edge in the merge, which is not included in the sort.
"""
# original array is broken in two parts
# left and right array
left_arr = arr[left:mid]
right_arr = arr[mid:right]
left_pos = 0
right_pos = 0
arr_ind = left
# after comparing, we merge those two array
# in larger sub array
while left_pos < len(left_arr) and right_pos < len(right_arr):
if left_arr[left_pos] <= right_arr[right_pos]:
arr[arr_ind] = left_arr[left_pos]
left_pos += 1
else:
arr[arr_ind] = right_arr[right_pos]
right_pos += 1
arr_ind += 1
# copy remaining elements of left, if any
for i in range(left_pos, len(left_arr)):
arr[arr_ind] = left_arr[i]
arr_ind += 1
# copy remaining element of right, if any
for i in range(right_pos, len(right_arr)):
arr[arr_ind] = right_arr[i]
arr_ind += 1
|
4cb5626a12a93cd280931061a84fdc6b660e6b73 | EmmanuelJeanBriand/hello-world | /cleancode/calculadora/calculadora.py | 1,982 | 3.96875 | 4 | def ask_option(): return int(input("Seleccione opción"))
def ask_int(s): return int(input(s))
header = r"""********
Calculadora
********"""
menu = r"""Menu
1) Suma
2) Resta
3) Multiplicación
4) División
5) Salir"""
pairs = {1: ('La suma es: {res}', lambda a, b: a + b),
2: ('La resta es: {res}', lambda a, b: a - b),
3: ('La multiplicación es: {res}', lambda a, b: a * b),
4: ('La división es: {res}', lambda a, b: a / b)}
bye = 5
def calcula(a, b, op_number):
r"""Realiza ``a`` @ ``b`` con @ la operación número ``op_number`` e imprime
el resultado.
``op_number`` es clave del diccionario global ``pairs``
EJEMPLOS::
>>> calcula(3, 2, 1)
La suma es: 5
>>> calcula(3, 2, 2)
La resta es: 1
>>> calcula(3, 2, 3)
La multiplicación es: 6
>>> calcula(3, 2, 4)
La división es: 1.5
>>> calcula(3, 0, 4)
No se permite la división entre 0
>>> calcula(3, 2, 0)
Traceback (most recent call last):
...
ValueError: Opción no prevista
"""
if op_number in pairs.keys():
(s, operation) = pairs[op_number]
try:
res = operation(a, b)
except ZeroDivisionError:
print("No se permite la división entre 0")
else:
print(s.format(res=res))
else:
raise ValueError('Opción no prevista')
def calculadora():
r"""Pide datos y operación, y realiza la operación
Interactivo.
"""
print(header)
print(menu)
option = ask_option()
while option in pairs.keys():
a = ask_int("Ingrese número:") # errors not considered here
b = ask_int("Ingrese otro número:") # same
calcula(a, b, option)
option = ask_option()
else:
if option == bye:
print("Bye")
else:
print("opción no prevista. Bye.")
|
36044d929d19fe21dbad7636b6506a13d09704ef | Eduardo271087/python-udemy-activities | /section-10/inheritance.py | 1,021 | 3.828125 | 4 | class Fabrica:
def __init__(self, marca, nombre, precio, descripcion, ruedas = None, distribuidor = None):
self.marca = marca
self.nombre = nombre
self.precio = precio
self.descripcion = descripcion
self.ruedas = ruedas
self.distribuidor = distribuidor
def __str__(self):
return """\
MARCA\t\t{}
NOMBRE\t\t{}
PRECIO\t\t{}
DESCRIPCION\t{}""".format(self.marca, self.nombre, self.precio, self.descripcion)
auto = Fabrica('Ford', 'Ranger', 10, 'Camioneta 4x4')
print(auto.nombre)
class Auto(Fabrica):
pass
z = Auto('Ford', 'Ranger', 100.000, 'Camioneta')
print(z)
class Deportivo(Fabrica):
ruedas = ""
distribuidor = ""
def __str__(self):
return """\
MARCA\t\t{}
NOMBRE\t\t{}
PRECIO\t\t{}
DESCRIPCION\t{}
RUEDAS\t\t{}
DISTRIBUIDOR\t{}""".format(self.marca, self.nombre, self.precio, self.descripcion, self.ruedas, self.distribuidor)
deportivo = Deportivo('Volkswagen', 'Vento', 54000, 'El mejor')
deportivo.ruedas = 3
deportivo.distribuidor = 'Tu autito'
print(deportivo) |
81a6e59840b3d3656a142c4823f4aa1899a1e133 | lgl90pro/colloquium2 | /56.py | 643 | 3.765625 | 4 | '''56. Якщо в одновимірному масиві є три поспіль однакових елемента, то
змінній r привласнити значення істина.
Виконав: Лещенко В. О.'''
import numpy as np
A = np.random.randint(0, 9, 15)
print(f'Вихідний масив: {A}.\n')
for i in range(len(A) - 2):
if (A[i] == A[i+1] == A[i+2]): # якщо зустрічається 3 однакових елементи підряд, r = істинна, і припиняємо цикл
r = True
break
else: # інакше, r = хиба
r = False
print(r) |
942247a1a2d2f2ff344161521ed462e57403b78b | dothuan96/machine-learning-coursera | /ML Basic - Python/linear reg_one var.py | 1,885 | 3.796875 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat May 2 13:08:14 2020
@author: thuando
"""
"""
Linear regression for 1 variable
"""
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
#reading dataset
data = pd.read_csv('ex1data1.txt', header = None)
#read 1st column
X = data.iloc[:,0]
#read 2nd column
y = data.iloc[:,1]
#number of training examples
m = len(y)
#view first few rows of the data
data.head()
plt.scatter(X,y)
plt.xlabel('Population of city (10,000s)')
plt.ylabel('Profit in (10,000s)')
plt.show()
#convert rank-1 array to rank-2 array
X = X[:, np.newaxis]
y = y[:, np.newaxis]
#initialize the initial parameter theta_0 and theta_1 = 0
theta = np.zeros([2,1])
iterations = 2000
#learning rate
alpha = 0.01
#create intercept x0 = 1
ones = np.ones((m,1))
#adding intercept
X = np.hstack((ones, X))
#computing the cost
def computeCost(X, y, theta):
#multiply matrix X and vector theta = h_theta(x)
error = np.dot(X, theta) - y
return np.sum(np.power(error, 2)) / (2*m)
J = computeCost(X, y, theta)
print("Cost of random theta:", round(J, 2))
#finding optimal parameters using Gradient Descent
def gradientDescent(X, y, theta, alpha, iterations):
#update 'interations' times
for _ in range(iterations):
#find hypothesis - y
error = np.dot(X, theta) - y
#X.T mean transpose X
#error * x_(i)
gradient = np.dot(X.T, error)
theta = theta - (alpha/m) * gradient
return theta
thetaOptimal = gradientDescent(X, y, theta, alpha, iterations)
print("Theta optimal:", np.round(thetaOptimal, 2))
print("Cost of theta optimal:", round(computeCost(X, y, thetaOptimal), 2))
#plot showing the best fit line
hyps = np.dot(X, thetaOptimal)
plt.scatter(X[:,1], y)
plt.xlabel('Population of city (10,000s)')
plt.ylabel('Profit in (10,000s)')
plt.plot(X[:,1], hyps)
plt.show()
|
16d8f90c8b1a78afcb1adfd78d348c690e62174f | nareshkr22/gtu_python | /pract17.py | 178 | 3.765625 | 4 | from module import *
num1 = input("Enter Number 1 : ")
num2 = input("Enter Number 2 : ")
oper = input("Enter the operation : ")
print(perform(int(num1),int(num2),oper)) |
936dc0b530010a91aa1ee114b7ca41ba4dda91cf | felipe-basina/python | /modulos/modulo_leitura_arquivo.py | 939 | 3.828125 | 4 | '''
Script utilizado para leitura de arquivo
from modulo_leitura_arquivo import ler_arquivo
arquivo = 'e:/instalados/python/dev/exercicios/modulos/arquivo_leitura.txt'
ler_arquivo(arquivo)
'''
def ler_arquivo(nome_arquivo):
if not nome_arquivo:
print('Um nome de arquivo deve ser definido!')
else:
# Utilizar 'with' para nao precisar utilizar bloco try-finally
conteudo = ''
with open(nome_arquivo, encoding='utf-8') as f:
conteudo = f.read()
f.closed
print('\nConteudo do arquivo\n')
print(conteudo)
print('\n')
# Realizando leitura linha por linha = mais eficiente!
def ler_arquivo_por_linha(nome_arquivo):
if not nome_arquivo:
print('Um nome de arquivo deve ser definido!')
else:
with open(nome_arquivo, encoding='utf-8') as f:
print('\n')
for line in f:
print(line, end='') |
d93ea266d20bb08f219c36bf69d8ed1635c335b2 | aswinishiyana/shiyana | /positive.py | 126 | 4.15625 | 4 | num=float(input("Enter a number"))
if num>0
print("positive number")
elif num==0
print("zero")
else:
print("Negative number")
|
3b3b623b172c9b69c1c40b1032b0bb264bde0087 | allatambov/allatambov.github.io | /PyProgPerm/practice/practice01/problem01.py | 563 | 3.703125 | 4 | line = ["Третьяковская", "Марксистская", "Площадь Ильича", "Авиамоторная",
"Шоссе Энтузиастов", "Перово", "Новогиреево", "Новокосино"]
station = input("Enter current station: ")
i = line.index(station)
print("Следующая станция: " + line[i + 1] + ".")
# alternatives (uncomment):
# print(f"Следующая станция: {line[i + 1]}.")
# print("Следующая станция: ", line[i + 1], ".", sep = "")
# print("Следующая станция: ", line[i + 1], ".", sep = "")
|
43d87f386f4145ff5977b12174f04f8db9216be8 | rossmfadams/AlgorithmsP2 | /arrayGenerator.py | 712 | 3.78125 | 4 | # This program returns the N amount of elements in an array
import random
# create four lists of random numbers
def generate_random_list_number(number):
first_list = []
second_list = []
third_list = []
fourth_list = []
for i in range(number):
value = random.randint(0, number)
first_list.append(value)
second_list.append(value)
third_list.append(value)
fourth_list.append(value)
return first_list, second_list, third_list, fourth_list
# Take in sorted lists and randomly pick an index to swap with index 100
# return the lists
def randomizer(arr):
value = random.randint(0, 99)
arr[99], arr[value] = arr[value], arr[99]
return arr |
4b0cc072f13613fc04c15b90bd9f769a94cd92ff | ShallowAlex/leetcode-py | /101-200/146.py | 2,036 | 3.515625 | 4 | class Node:
def __init__(self, key=None, value=None):
self.key = key
self.value = value
self.pre = None
self.next = None
class LRUCache:
def __init__(self, capacity: int):
self.capacity = capacity
self.head = Node()
self.tail = Node()
self.head.next = self.tail
self.tail.pre = self.head
self.dic = dict()
def get(self, key: int) -> int:
if key in self.dic:
self.move_to_end(key)
return self.dic[key].value
else:
return -1
def put(self, key: int, value: int) -> None:
if key in self.dic:
self.move_to_end(key)
self.dic[key].value = value
else:
new_node = Node(key, value)
self.dic[key] = new_node
new_node.pre = self.tail.pre
new_node.next = self.tail
self.tail.pre.next = new_node
self.tail.pre = new_node
if len(self.dic) > self.capacity:
self.dic.pop(self.head.next.key)
self.head.next = self.head.next.next
self.head.next.pre = self.head
def move_to_end(self, key: int):
#
old_node = self.dic[key]
old_node.pre.next = old_node.next
old_node.next.pre = old_node.pre
old_node.next = self.tail
old_node.pre = self.tail.pre
self.tail.pre.next = old_node
self.tail.pre = old_node
# from collections import OrderedDict
# class LRUCache(OrderedDict):
# def __init__(self, capacity: int):
# self.capacity = capacity
# def get(self, key: int) -> int:
# if key not in self:
# return -1
# else:
# self.move_to_end(key)
# return self[key]
# def put(self, key: int, value: int) -> None:
# if key in self:
# self.move_to_end(key)
# self[key] = value
# if len(self) > self.capacity:
# self.popitem(last = False) |
a4e46386f722808a8e904e8118d0f266d69cf611 | kylechenoO/812pytest | /pynative/q14.py | 204 | 4.0625 | 4 | #!/opt/anaconda/bin/python
## Question 14: Print downward Half-Pyramid Pattern with Star (asterisk)
def getHalfPyramid(size):
for i in range(size):
print('*' * (size - i))
getHalfPyramid(5)
|
252cfe8cba3c5a85b2def4aeb4ea7aada76247d1 | goalong/lc | /v1/61.rotate-list.133330774.ac.py | 1,225 | 3.703125 | 4 | #
# [61] Rotate List
#
# https://leetcode.com/problems/rotate-list/description/
#
# algorithms
# Medium (24.43%)
# Total Accepted: 131.8K
# Total Submissions: 539.7K
# Testcase Example: '[1,2,3,4,5]\n2'
#
# Given a list, rotate the list to the right by k places, where k is
# non-negative.
#
#
#
# Example:
#
# Given 1->2->3->4->5->NULL and k = 2,
#
# return 4->5->1->2->3->NULL.
#
#
#
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def rotateRight(self, head, k):
"""
:type head: ListNode
:type k: int
:rtype: ListNode
"""
# 4 star.
if not head:
return None
cur = head
n = 0
last = None
while cur:
n += 1
if cur.next is None:
last = cur
cur = cur.next
k = k % n
if k == 0:
return head
step = n - k - 1
node = head
while step > 0:
node = node.next
step -= 1
new_head = node.next
node.next = None
last.next = head
return new_head
|
f78a688ec2f6a58de128d60278efffc9c4f69754 | wlommusic/machine-learning-repo | /#2 regression/1 linear reg/linear-reg.py | 1,351 | 3.828125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Mon Feb 8 11:56:19 2021
@author: wlom
"""
#importing the libraries
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
#importing the dataset
data = pd.read_csv('Salary_Data.csv')
x= data.iloc[:,:-1].values #rows,col
y= data.iloc[:,-1].values
#splitting the data
from sklearn.model_selection import train_test_split
x_train,x_test,y_train,y_test=train_test_split(x,y,test_size=0.2,random_state=1)
#training the linear model on training set
from sklearn.linear_model import LinearRegression
reg = LinearRegression()
reg.fit(x_train,y_train)
#predicting the test results
y_pred=reg.predict(x_test)
# print(y_pred)
#visuallizing the training set results
plt.scatter(x_train,y_train ,color='blue')
plt.plot(x_train,reg.predict(x_train),color='red')
plt.title('Salary vs Exp (test set)')
plt.xlabel('Years of Exp')
plt.ylabel('Salary')
plt.show()
#visualizing the test set results
plt.scatter(x_test,y_test ,color='blue')
plt.plot(x_train,reg.predict(x_train),color='red')
plt.title('Salary vs Exp (test set)')
plt.xlabel('Years of Exp')
plt.ylabel('salary')
plt.show()
#to predict salary in any given no of years
y_pred = reg.predict([[12]])#double [[]] coz it expects 2d array
print(f"predicted salary: {y_pred}")
y_pred = reg.predict([[105]])
print(f"predicted salary: {y_pred}")
|
a79955480941c6a3516aaa750fafdc1fe3dc4dbc | satojkovic/algorithms | /problems/bulb_switch.py | 392 | 3.625 | 4 | def bulb_switch(n):
bulbs = [1 for _ in range(n)]
for i in range(1, n + 1):
if i == 1:
continue
elif i == n:
bulbs[-1] = 0 if bulbs[-1] == 1 else 1
else:
for j in range(i - 1, n, i):
bulbs[j] = 0 if bulbs[j] == 1 else 1
return sum(bulbs)
def bulb_switch2(n):
import math
return int(math.sqrt(n)) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.