blob_id stringlengths 40 40 | repo_name stringlengths 5 119 | path stringlengths 2 424 | length_bytes int64 36 888k | score float64 3.5 5.22 | int_score int64 4 5 | text stringlengths 27 888k |
|---|---|---|---|---|---|---|
f35e1f1edf32734fe1195efe513f59608b16637d | SOFIAshyn/BaseProgramming_course_Basic_Python | /lab_12/Petryshyn_Sofiia_table_print.py | 1,320 | 3.796875 | 4 | def rec_count(lst, i, j):
"""
(list, int, int) -> list
Return list of counted numbers
>>> rec_count([[0] * 4 for i in range(5)], 4, 0)
[[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [1, 1, 1, 1]]
"""
if j < len(lst[0]):
if i == 0 or j == 0:
lst[i][j] = 1
else:
lst[i][j] = lst[i - 1][j] + lst[i][j - 1]
return rec_count(lst, i, j + 1)
else:
return lst
def rec_print(lst, i, j):
"""
(list, int, int) -> list
Return list of counted numbers
>>> rec_print([[0] * 4 for i in range(5)], 0, 0)
0 0 0 0 [[0, 0, 0, 0], [0, 0, 0, 0], \
[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]]
"""
if j < len(lst[0]):
print("{:<5}".format(lst[i][j]), end="")
return rec_print(lst, i, j + 1)
else:
return lst
if __name__ == "__main__":
import doctest
doctest.testmod()
n, m = list(map(int, (input \
("Print two numbers for table(lenght, width): " \
).split())))
table = [[0] * m for i in range(n)]
# Investigation of recoursy
for i in range(len(table)):
table = rec_count(table, i, 0)
for i in range(len(table)):
table = rec_print(table, i, 0)
print('\n')
|
4411a0841a02c86c258ea784b78148b8eadca243 | lapps/lapps.github.io | /manuals/service-manager/install-service-manager/scripts/utils.py | 925 | 3.59375 | 4 |
def create_mappings(filename):
"""Reads the settings file and creates a dictionary f variables and their values."""
mappings = {}
for line in open(filename):
idx = line.find('#')
if idx > -1:
line = line[:idx]
line = line.strip()
if not line:
continue
result = line.split("\t",1)
var = result[0].strip()
if len(result) == 1:
val = ''
else:
val = result[1].strip()
mappings[var] = val
return mappings
def print_mappings(mappings):
for (var, val) in mappings.items():
print "%s=%s" % (var, val)
def replace_vars(lines, mappings):
"""Replace variable names like ${NODE_URL} with the value."""
new_lines = []
for line in lines:
for (var, val) in mappings.items():
line = line.replace(var, val)
new_lines.append(line)
return new_lines
|
fde051181779052834c92a50746f7cd7d670143b | premdhanawade/Marvellous | /Assignment 4/Assignment4_2.py | 381 | 4.125 | 4 | #Write a program which contains one lambda function which accepts two parameters and return
#its multiplication.
#Input : 4 3 Output : 12
#Input : 6 3 Output : 18
fp = lambda no1,no2 : no1*no2
def main():
value1=int(input("enter 1 no"))
value2 = int(input("enter 2nd no"))
ret = fp(value1,value2)
print(ret)
if __name__=='__main__':
main(); |
7f19b25673f7fe3bcadad649e3f4c22c3029fb23 | ldavis0866/Sprint-Challenge--Hash-Theory | /hash-tables/ex1/ex1.py | 1,037 | 3.578125 | 4 | def get_indices_of_item_weights(weights, limit):
return ();
if __name__ == '__main__':
# You can write code here to test your implementation using the Python repl
pass
def get_indices_of_item_weights(arr, limit):
list1 = list(range(len(arr)))
#print(list1)
#print(arr)
dictionary = dict(zip(arr,list1))
#print(dictionary)
dict_keys = dictionary.keys()
if len(arr) <= 1 :
return ()
else:
for key in dict_keys:
weight = limit - key
if weight in (dict_keys):
#print(dictionary[weight],dictionary[key])
return (dictionary[weight],dictionary[key])
#arr = [4]
#arr = [4, 6, 10, 15, 16]
#limit = 21
# arr = [4,4]
# limit = 8
# get_indices_of_item_weights(arr, limit)
# dict = {}
# for(let i=0; i< arr.length; i++):
# if(dict[arr[i]] !== undefined):
# return tuple([i, dict[arr[i]]])
# }else{
# dict[limit - arr[i]] = i
# }
# }
# return ()
# arr = [4,4];
# limit = 8;
# let x = getIndicesOfItemWeights(arr, limit);
# console.log(x) |
cb06a4d87632031ee6c004911aeed458e48aaddb | Shisan-xd/testPy | /python_work/day6-12列表的遍历之while.py | 435 | 4.15625 | 4 | # 依次打印列表中的各个数据
name_list = ['TOM', 'LILY', 'JACK', 'ROSE']
"""
1、准备表示下标数据
2、循环while
条件 n < 3 --循环遍历不适合写死,可以用len()表示
遍历:依次按顺序访问到序列的每个数据
n += 1
"""
n = 0
while n < len(name_list):
print(name_list[n]) # 遍历时不能固定写死,填写随着程序循环推进变化的一个数据
n += 1
|
78c7a81ad8c3c56225c430c16d69664d8e1d2688 | kart/projecteuler | /65.py | 667 | 4 | 4 | # Uses recurrence relation for computing the ith continued fraction. See wiki - http://en.wikipedia.org/wiki/Continued_fraction
#
import math
def sumofd(n):
s = 0
while n != 0:
s += n % 10
n = n / 10
return s
h_prev = 1
h_prev_prev = 0
k_prev = 0
k_prev_prev = 1
cycle = 1
for i in range(0, 101):
if i == 0:
a = 2
elif i % 3 == 1 or i % 3 == 0: a = 1
else:
a = 2 * cycle
cycle += 1
num = a * h_prev + h_prev_prev
den = a * k_prev + k_prev_prev
print "sum of numerator digits for the ", i + 1, "th term = ", sumofd(num)
h = a * h_prev + h_prev_prev
k = a * k_prev + k_prev_prev
h_prev_prev = h_prev
h_prev = h
k_prev_prev = k_prev
k_prev = k
|
83863fd424571f1446ec5dd791206245f2cd34ab | jyotiraditya125/txt-file | /TT1_1805125.py | 599 | 3.984375 | 4 | # Python program to segregate even and odd elements of array
def segregateEvenOdd(arr):
left,right = 0,len(arr)-1
while left < right:
while (arr[left]%2==0 and left < right):
left += 1
while (arr[right]%2 == 1 and left < right):
right -= 1
if (left < right):
arr[left],arr[right] = arr[right],arr[left]
left += 1
right = right-1
arr = [12, 34, 45, 9, 8, 90, 3]
segregateEvenOdd(arr)
print ("Array after segregation "),
for i in range(0,len(arr)):
print(arr[i])
|
c45d5a902ea23fbaf963c4db35c2c0945b9d7aa6 | Manmohanalla/interview_programs | /binary_sorted_index.py | 711 | 4 | 4 | # array = [1, 5, 9, 23, 30] # sorted array of integers
# binary_search(array, val) -> index of val in array or -1 if val not in array
# binary_search(array, 9)->2
# recursive
def binary_search(array, val, l=0,h=None):
if h == None:
h= len(array)
if len(array)!=0:
mid =(l+h)/2
value = array[mid]
if value < val:
l = mid+1
return binary_search(array,val,l,h)
elif value >val:
h =mid
return binary_search(array,val,l,h)
elif value==val:
return mid
else:
return -1
else:
return False
array = [1, 5, 9, 23, 30, 56, 78,79]
print binary_search(array,78)
|
b699bb44b7ce865aaa5b219d91f17da0fab5ae42 | marksutherland/python-playground | /example.py | 765 | 3.9375 | 4 | # A very simple class modelling coffee beans
class CoffeeBean:
def __init__(self, origin, country, tasting_notes):
self._origin = origin
self._country = country
self._tasting_notes = tasting_notes
def origin(self):
return self._origin
def country(self):
return self._country
def tasting_notes(self):
return self._tasting_notes
def __str__(self):
return "{origin} ({country}): \n* {tasting_notes}".format(
origin=self.origin(),
country=self.country(),
tasting_notes='\n* '.join(self.tasting_notes()))
bean = CoffeeBean("Chumeca La Trinidad",
"Costa Rica",
['caramel', 'chocolate', 'berry fruit'])
print(bean)
|
c03a5182b4ce93adb367dac2c935e108f265ac86 | whiteemperor13/ichw | /pyassign1/planets.py | 1,787 | 4.125 | 4 | #!/usr/bin/env python3
"""planets.py: Using the turtle module to build a model for the oribts of the planets in the solar system
__author__ = "Xiangtao Hu"
__pkuid__ = "1700011768"
__email__ = "white_emperor@pku.edu.cn"
"""
import math
import turtle
def initial():
"""setting the basic parameters, like color, shape, size, etc., for the planets
"""
for x in range(6):
wg=eval("wg"+str(x+1))
color=eval("color"+str(x+1))
c=eval("c"+str(x+1))
e=eval("e"+str(x+1))
wg.speed(0)
wg.shape("circle")
wg.turtlesize(0.5,0.5,0.5)
wg.pensize(1.5)
wg.color(color)
wg.penup()
wg.setx((1/e-1)*c)
wg.pendown()
def ovalmotion(i):
"""a function that allows 6 planets to move to a point on its oval orbit
"""
for x in range(6):
wg=eval("wg"+str(x+1))
c=eval("c"+str(x+1))
e=eval("e"+str(x+1))
n=50*(x+1)
a=c/e
b=math.sqrt(a**2-c**2)
wg.goto(b**2/c*math.cos((i+1)*2*math.pi/n)/(math.cos((i+1)*2*math.pi/n)+a/c),b**2/c*math.sin((i+1)*2*math.pi/n)/(math.cos((i+1)*2*math.pi/n)+a/c))
def solar_system():
"""A function that simulates the orbit of 6 planets in the solar system
"""
initial()
for i in range(100000000):
ovalmotion(i)
def main():
"""main module
"""
solar_system()
wg=turtle.Screen()
sun=turtle.Turtle()
sun.shape("circle")
sun.turtlesize(1,1,1)
sun.color("yellow")
wg1=turtle.Turtle()
color1="blue"
c1=5
e1=0.2
wg2=turtle.Turtle()
color2="yellow"
c2=20
e2=0.25
wg3=turtle.Turtle()
color3="darkblue"
c3=40
e3=0.3
wg4=turtle.Turtle()
color4="red"
c4=60
e4=0.35
wg5=turtle.Turtle()
color5="green"
c5=80
e5=0.4
wg6=turtle.Turtle()
color6="brown"
c6=100
e6=0.45
if __name__ == '__main__':
main() |
69dbf924e0c714107e575ee3df078ce1c580478f | joanaritacouto/fdpython | /2017-2018/AULA_5/aula05_ex8.py | 190 | 4.03125 | 4 | #encoding:utf8
def digitos(N):
c=0
for i in str(N):
c=c+1
return c
N=int(input("Insira um número que quer testar: "))
print("O número {} possui {} digitos.".format(N,digitos(N)))
|
e894ba04a8a49afdf079d771e1469784f6deb7d3 | brettspeaks/utils | /python/extract_csv.py | 2,078 | 3.71875 | 4 | #!/usr/bin/env python
import csv
import os
import sys
import argparse
def header_map(header, reqs, show_extra=False):
""" Return a mapped list of header names to column indices.
Only found headers will be part of the return map.
"""
import re
# Non alphanumeric class with space and some punctuation
pattern = re.compile('[^a-zA-Z0-9_\ \/#?-]+')
nml_header = [pattern.sub('', x.lower()).strip() for x in header]
# Map each required column to an index value in the header
# Return list
h = {}
for col in reqs:
if type(col) is list:
for col_name in col:
if col_name in nml_header:
# Map the index to the first column name given regardless of which column name is actually used
h[col[0]] = nml_header.index(col_name)
elif show_extra:
print col
else:
if col in nml_header:
h[col] = nml_header.index(col)
elif show_extra:
print col
return h
def main():
parser = argparse.ArgumentParser(description="Extract given fields from csv and output in the same order.")
parser.add_argument("in_file", type=str, help="file to extract from")
parser.add_argument("fields", metavar="field", type=str, nargs="+", help="list of fields to extract")
parser.add_argument("-d", "--delimiter", default=",", help="parser delimiter")
args = parser.parse_args()
file = args.in_file
fields = args.fields
delimiter = args.delimiter
# todo - find a cleaner solution for this.
if delimiter == "\\t":
delimiter = "\t"
with open(file, 'rb') as csv_file:
csv_reader = csv.reader(csv_file, delimiter=delimiter)
header = csv_reader.next()
h = header_map(header, fields)
print(h)
print(",".join(fields))
for row in csv_reader:
tmp_list = []
for f in fields:
tmp_list.append( row[h[f]] )
print(",".join(tmp_list))
if __name__ == "__main__":
main()
|
fdc911dbf7f6eee7f79288b2fa6255135e3f2e70 | cezanedeepak/Training_python | /Day 1/Mapping.py | 236 | 3.53125 | 4 | #Mapping,lambda and Filtering
li=[22,23,21,44,45]
def my(e1):
return e1*9/5+32
m=list(map(my,li))
print(m)
#lambda
m=list(map(lambda e1:e1*9/5+32,li))
print(m)
#Filtering
def my(e1):
return e1<30
m=list(filter(my,li))
print(m) |
cf8989bba87ca137b59d0dee910f87142e7a8f2d | chris-datascience/optimisation | /Simulated_Annealing_optimization.py | 1,617 | 3.5625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Fri Jul 20 22:06:02 2018
@author: erdbrca
"""
import numpy as np
import time
from random import choice
def costf(x):
q = np.array(x)
return np.sum((q - 1)**2)
def annealingoptimize(domain, costf, T=10000, cool=.97, step=1):
# random initialisation
vec = [float(np.random.randint(domain[i][0], domain[i][1])) for i in range(len(domain))]
unit_directions = [-1,1]
it = 0
while T>.1:
i = np.random.randint(0, len(domain)-1) # choose an index
dir = step*(-1)**choice(unit_directions) # choose a direction to change it
# Create a new list with one of the values changed
vecb = vec[:]
vecb[i] += dir
if vecb[i]<domain[i][0]:
vecb[i] = domain[i][0]
elif vecb[i]>domain[i][1]:
vecb[i] = domain[i][1]
# Calculate current cost and new cost
ea = costf(vec)
eb = costf(vecb)
# Is it better or does it make the probability cut-off?
if eb<ea:
vec = vecb # new solution is better
else:
prob = np.exp((-eb - ea) / T)
if np.random.rand()<prob:
vec = vecb # new solution is NOT better but nevertheless selected
# Decrease the temperature
T *= cool
it += 1
return vec, it
if __name__=='__main__':
domain = [(0,9)]*10
SA_solution, i = annealingoptimize(domain, costf, step=.5) # See cost function: solution is [0,1,2,..,9]
print(SA_solution)
|
d76f4f9096d2b2cdd20702b65991f686109f7526 | lezlyv/comparisonOperators | /practiceComparisonOperators.py | 409 | 3.5 | 4 | '''
Created on Nov 30, 2019
@author: ITAUser
'''
4 == 4
#True
var = 4 == 4
print(var)
a = 2 == 4
print(a)
b = 2 < 3
print(b)
c = 4 < 3
print(c)
d = 4 > 3
print(d)
e = 2 > 3
print (e)
a = 2 <= 3
print(a)
b = 2 >= 3
print(b)
print(e == b)
r = e == b
print(r)
string1 = "michael"
string2 = "Michael"
print(string1 == string2)
a = [1, 2, 3] == [1, 2, 3]
print(a)
#true
|
ce14d04317358ab835f87e397ca297829959b1f9 | danieelgohh/Unwinnable-TicTacToe | /TicTacToe/player.py | 3,528 | 3.8125 | 4 | import math
import random
class Player:
def __init__(self, letter):
#letter is x or o
self.letter = letter
# next move in a game
def get_move(self, game):
pass
class RandomComputerPlayer(Player):
def __init__(self, letter):
super().__init__(letter)
def get_move(self, game):
spot = random.choice(game.available_moves())
return spot
class HumanPlayer(Player):
def __init__(self, letter):
super().__init__(letter)
def get_move(self, game):
valid_spot = False
val = None
while not valid_spot:
spot = input(self.letter + '\'s turn. Select your next move (0-8): ')
# value checker to see if value is correct by trying to cast it to
# an integer, if not possible, notify that it is invalid and also check
# if spot is available.
try:
val = int(spot)
if val not in game.available_moves():
raise ValueError
valid_spot = True
except ValueError:
print('Invalid spot!')
return val
class UnbeatableComputerPlayer(Player):
def __init__(self, letter):
super().__init__(letter)
def get_move(self, game):
if len(game.available_moves()) == 9:
spot = random.choice(game.available_moves()) # random spot on grid
else:
# get the spot based on the minimax algorithm
spot = self.minimax(game, self.letter)['position']
return spot
def minimax(self, state, player):
max_player = self.letter # UnbeatableComputerPlayer
other_player = 'O' if player == 'X' else 'X' # the other player
# firstly check if previous move won
# base case
if state.current_winner == other_player:
# return position and score to keep track of the score
return {'position': None,
'score': 1 * (state.num_empty_spots() + 1) if other_player == max_player else
-1 * (state.num_empty_spots() + 1)
}
elif not state.empty_spots(): # no empty spots on grid
return {'position': None, 'score': 0}
if player == max_player:
best = {'position': None, 'score': -math.inf} # each score should maximize (be larger)
else:
best = {'position': None, 'score': math.inf} # each score should minimize
for possible_move in state.available_moves():
# step 1: make a move, try that spot
state.make_move(possible_move, player)
# step 2: recurse using minimax to simulate a game after making that move
simulate_score = self.minimax(state, other_player) # alternate players
# step 3: undo the move
state.board[possible_move] = ' '
state.current_winner = None
simulate_score['position'] = possible_move # otherwise this will be messed up from the recursion
# step 4: update the dictionaties if necessary
print(player)
print(simulate_score)
print(best)
if player == max_player:
if simulate_score['score'] > best['score']:
best = simulate_score # replace best
else:
if simulate_score['score'] < best['score']:
best = simulate_score # replace best
return best
|
f8e9a92f19e631d595be2fd6c250eb0d83a05534 | felix-perdana/online_judge | /io-example/io-1.py | 369 | 3.578125 | 4 | from sys import stdin
for line in stdin:
if line == '': # If empty string is read then stop the loop
break
a, b, c = map(str, line.split())
b = int(b)
c = int(c)
if a == "+":
print(b+c)
if a == "-":
print(b-c)
if a == "*":
print(b*c)
if a == "/":
print(b//c)
if a == "%":
print(b%c)
|
6a94e3e6b2d90c95ff7842bfb8bf40d9ac2e278b | tsungic/w18c-fizzBuzz | /app.py | 445 | 3.84375 | 4 | def fizzbuzz(test_number):
# every line that is indented belongs to fizzbuzz function (be consistent with indentation)
print(test_number)
if(test_number % 3 == 0 and test_number % 5 == 0):
print("FizzBuzz")
elif(test_number % 5 == 0):
print("Buzz")
elif(test_number % 3 == 0):
print("Fizz")
numbers =[3, 5, 15, 8, 10, 30, 1, 0, -10, 1000, 900, 150, 297, 16, 22]
for num in numbers:
fizzbuzz(num) |
ab6b60a93a5fbfb54bd614168ced30ac8ee05473 | guimmp92/python | /digit_stats.py | 1,211 | 3.8125 | 4 | #!/usr/bin/python
"""
https://www.codeeval.com/open_challenges/144/
Given the numbers "a" and "n" find out how many times each digit from zero to nine is
the last digit of the number in a sequence [ a, a2, a3, ... an-1, an ].
"""
from collections import defaultdict
import sys
def correct_but_inefficient(a, n):
counter = defaultdict(int)
for i in range(1, n+1):
num = pow(a, i)
counter[num % 10] += 1
return counter
def solution(a, n):
series = []
last_digit = None
for i in xrange(1, n+1):
last_digit = pow(a, i) % 10
if last_digit not in series:
series.append(last_digit)
else:
break
counter = defaultdict(int)
q, r = divmod(n, len(series))
for i in series:
counter[i] = q
for i in range(r):
counter[series[i]] += 1
return counter
if __name__ == "__main__":
with open(sys.argv[1], 'r') as infile:
for line in infile:
data = map(int, line.strip().split())
counter = solution(data[0], data[1])
res = []
for i in range(10):
res.append("{0}: {1}".format(i, counter[i]))
print ", ".join(res)
|
71b677e019fd6fd9997b7d0a69ef6633299d1b3b | Radik0/python-learn | /凯撒加密.py | 1,961 | 3.546875 | 4 | #!/usr/bin/python3
# -*- coding: utf-8 -*-
# @Time : 2021/6/12 20:59
# @Author : Huang
# @FileName: 凯撒加密.py
# @Software: PyCharm
# Caesar Cipher
MAX_KEY_SIZE = 26
def hgl30_getMode():
while True:
# print('请选择加密或解密模式,或者选择暴力破解:')
print('加密:encrypt(e):')
print('解密:decrypt(d):')
# print('暴力破解:brute(b)')
mode = input().lower() # 对输入的字符转换
if mode in 'encrypt e decrypt d brute b'.split():
return mode
else:
print('请输入"encrypt"或"e"或"decrypt"或"d"或"brute"或"b"!')
def hgl10_getMessage():
print('请输入你的信息:')
return input()
def hgl100_getKey():
key = 0
while True:
print('请输入密钥数字(1-%s)' % (MAX_KEY_SIZE)) # 定义凯撒加密的秘钥
key = int(input())
if (key >= 1 and key <= MAX_KEY_SIZE):
return key
def hgl102getTranslatedMessage(mode, message, key):
if mode[0] == 'd':
key = -key
translated = ''
for symbol in message:
if symbol.isalpha():
num = ord(symbol)
num += key
if symbol.isupper():
if num > ord('Z'):
num -= 26
elif num < ord('A'):
num += 26
elif symbol.islower():
if num > ord('z'):
num -= 26
elif num < ord('a'):
num += 26
translated += chr(num)
else:
translated += symbol
return translated
mode = hgl30_getMode()
message = hgl10_getMessage()
if mode[0] != 'b':
key = hgl100_getKey()
print('你要翻译的信息是:')
if mode[0] != 'b':
print(hgl102getTranslatedMessage(mode, message, key))
else:
for key in range(1, MAX_KEY_SIZE + 1):
print(key, hgl102getTranslatedMessage('decrypt', message, key))
|
600e9868f6c3e677854455e5ddfbe1a666cdac15 | jlhg/rosalind-solution | /fib/fib.py | 821 | 3.75 | 4 | #!/usr/bin/env python
#
# fib.py
#
# Copyright (C) 2013, Jian-Long Huang
# Licensed under The MIT License
# http://opensource.org/licenses/MIT
#
# Author: Jian-Long Huang (jlhgln@gmail.com)
# Version: 0.1
# Created: 2013.7.18
#
# http://rosalind.info/problems/fib/
#
# Usage: fib.py <input>
def fib(m, k):
"""Rabbits and recurrence relations
m: month
k: number of rabbit pairs produced
formula: Fn = Fn-1 + Fn-2 * k (with F1 = F2 = 1)
"""
assert m > 2
first = 1
second = 1
generation = 3
while generation <= m:
result = second + first * k
second, first = result, second
generation += 1
return result
if __name__ == '__main__':
import sys
with open(sys.argv[1], 'r') as fi:
month, k = fi.readline().strip().split(' ')
print(fib(int(month), int(k)))
|
50f10bea69e6127e078dc528d19b1bfc63740a9a | andrewhunter1612/precourse_recap_homework | /precourse_recap.py | 144 | 3.828125 | 4 | userInput
correctAnswer = "correct_answer"
if (correct_answer == userInput):
print("You are correct")
else:
print("You are wrong")
|
937e4c88e104d5b1f6ccc6ea4113b65bba271a19 | bhavya4official/data_structure | /search_max.py | 120 | 3.90625 | 4 | numbers = [12, 4, 6, 24, 10, 24, 1]
max = numbers[0]
for num in numbers:
if num > max:
max = num
print(max)
|
0e73f7725d180aa7afcd778b1ccdb73e5e21027a | HelloDepy/tic_tac_toe | /tictactoe.py | 2,756 | 3.78125 | 4 | cells = [' ' for _ in range(9)]
s = 0
def field(cells):
print("-" * 9)
print("|", cells[0], cells[1], cells[2], "|")
print("|", cells[3], cells[4], cells[5], "|")
print("|", cells[6], cells[7], cells[8], "|")
print("-" * 9)
x_o = 'X'
field(cells)
end1, end3 = False, True
while True:
if s % 2 == 0:
x_o = 'X'
else:
x_o = 'O'
while end1 != True:
end2 = False
a = input("Enter the coordinates: > ").split()
while end2 != True:
if len(a) != 2:
print("You should enter numbers!")
break
elif a[0].isdigit() is False or a[1].isdigit() is False:
print("You should enter numbers!")
break
else:
end3 = False
break
while end3 != True:
x, y = [int(i) for i in a]
if (x < 1 or x > 3) or (y < 1 or y > 3):
print("Coordinates should be from 1 to 3!")
break
else:
n = 8 - 3 * y + x
if cells[n] == 'X' or cells[n] == 'O':
print("This cell is occupied! Choose another one!")
break
else:
end1 = True
break
n = 8 - 3 * y + x
cells[n] = x_o
field(cells)
s += 1
end1, end3 = False, True
x_win = cells[0] == cells[1] == cells[2] == 'X' or cells[3] == cells[4] == cells[5] == 'X' or cells[6] == cells[
7] == cells[8] == 'X' # X win in lines
x_win = x_win or cells[0] == cells[3] == cells[6] == 'X' or cells[1] == cells[4] == cells[7] == 'X' or cells[2] == \
cells[5] == cells[8] == 'X' # X win in columns
x_win = x_win or cells[0] == cells[4] == cells[8] == 'X' or cells[2] == cells[4] == cells[
6] == 'X' # X win in diagonale
o_win = cells[0] == cells[1] == cells[2] == 'O' or cells[3] == cells[4] == cells[5] == 'O' or cells[6] == cells[
7] == cells[8] == 'O' # O win in lines
o_win = o_win or cells[0] == cells[3] == cells[6] == 'O' or cells[1] == cells[4] == cells[7] == 'O' or cells[2] == \
cells[5] == cells[8] == 'O' # O win in columns
o_win = o_win or cells[0] == cells[4] == cells[8] == 'O' or cells[2] == cells[4] == cells[
6] == 'O' # O win in diagonale
if x_win is True:
print('X wins')
elif o_win is True:
print('O wins')
elif o_win == x_win == False and (' ' not in cells and '_' not in cells):
print('Draw')
elif o_win == x_win == False and (' ' in cells or '_' in cells):
continue
break |
ccd20bb4ada7aba90ed52c3e1c301a982784cd04 | super-iterator/puzzles-and-datastructures | /DataStructures in JS/Andela_Interview.py | 348 | 3.609375 | 4 | def equivalent(string1,string2):
## String1: abc
## String2: bac
common = []
if len(string1) != len(string2):
return False
for i in string1:
if i in string2:
common.append(i)
print(common)
if len(common) == len(string1):
return True
else:
return False
print( equivalent("abc","bad") )
NlongN
{
a : 0,
b : 1,
c : 0
} |
1e8eb6e0e16925f04cf73462f509a6965fd0970d | singgihbekti/K-Means_Theory_Random_Data | /K-Means_Practically_Computer_Vision_Experiment.py | 5,977 | 4.09375 | 4 | #!/usr/bin/env python
# coding: utf-8
# # K-Means Clustering - Comparing with Theory in Computer Vision
# Source: Computer Vision Meeting - Chapter 3. Episode. 2 - 3
# # Step 1: Get Data:
# The first step is to prepare or generate the data. In this dataset, the observations only have two features, but K-Means can be used with any number of features. Since this is an unsupervised example, it is not necessary to have a "target" column.
#
# =================================
# here, I will use several libraries that we need to do some functions
# In[1]:
from sklearn.cluster import KMeans
import pandas as pd
import matplotlib.pyplot as plt
from matplotlib import style
style.use("ggplot")
get_ipython().run_line_magic('matplotlib', 'inline')
# Let's choose number from 0-100.
#
# From 7 student's we got [7, 10, 13, 29, 48, 94, 99] ==> define those in the coloum.
#
# Then assume that the second coloum has same value, let say it is "1.0"
# In[2]:
data = pd.DataFrame([[7.0, 1.0],
[10.0, 1.0],
[13.0, 1.0],
[29.0, 1.0],
[48.0, 1.0],
[94.0, 1.0],
[99.0, 1.0]], columns=['x','y'])
print( data )
# # Step 2: Build the Model:
# Much like the supervised models, you first create the model then call the .fit() method using your data source. The model is now populated with both your centroids and labels. These can be accessed via the .cluster_centers_ and labels_ properties respectively.
#
# You can view the complete documentation here: http://scikit-learn.org/stable/modules/generated/sklearn.cluster.KMeans.html
#
# K-Means also has a .predict() method which can be used to predict the label for an observation.
#
# ==================================
# Today, we wil create 3 clusters from the data we have collected from students
# Using K-Means we will get the centroids and we can see the members
# That data set is arranged in:
#
# i1, i2, i3, i4, i5, i6, i7
#
# ------------------------------------------------
#
# 100 is the highest number from 0-100
# So, we can get the range by :
# 100:3 = 33,33
#
# ------------------------------------------------
#
# From, that range we will get the median of the group
#
# i1 - i2 - i3 - i4 - i5 - i6 - i7
# 7 10 13 29 48 94 99
#
# |--- 16 ---||--- 50 ---||--- 80 ---|
# |--- µ1 ---||--- µ2 ---||--- µ3 ---|
#
# So, we obtain:
# µ1= 16
# µ2= 50
# µ3= 80
#
# ------------------------------------------------
# Then, we have to do operation by subtracting:
# |in - µ1|, |in - µ2|, |in - µ3|
#
# So, we will get the operation bellow:
#
# |i1 - µ1|, |i1 - µ2|, |i1 - µ3|
#
# |i2 - µ1|, |i2 - µ2|, |i2 - µ3|
#
# |i3 - µ1|, |i3 - µ2|, |i3 - µ3|
#
# |i4 - µ1|, |i4 - µ2|, |i4 - µ3|
#
# |i5 - µ1|, |i5 - µ2|, |i5 - µ3|
#
# |i6 - µ1|, |i6 - µ2|, |i6 - µ3|
#
# |i7 - µ1|, |i7 - µ2|, |i7 - µ3|
#
# Okay, how's the result?
#
# |i1 - µ1|, |i1 - µ2|, |i1 - µ3|
#
# |07 - 16|, |07 - 50|, |07 - 80|
#
# | 09,0 |, | 43,0 |, | 76,3 |
#
#
# |i2 - µ1|, |i2 - µ2|, |i2 - µ3|
#
# |10 - 16|, |10 - 50|, |10 - 80|
#
# | 06,0 |, | 40,0 |, | 73,5 |
#
#
# |i3 - µ1|, |i3 - µ2|, |i3 - µ3|
#
# |13 - 16|, |13 - 50|, |13 - 80|
#
# | 03,0 |, | 37,0 |, | 70,5 |
#
#
# |i4 - µ1|, |i4 - µ2|, |i4 - µ3|
#
# |29 - 16|, |29 - 50|, |29 - 80|
#
# | 13,0 |, | 21,0 |, | 54,5 |
#
#
# |i5 - µ1|, |i5 - µ2|, |i5 - µ3|
#
# |48 - 16|, |48 - 50|, |48 - 80|
#
# | 32,0 |, | 02,0 |, | 35,5 |
#
#
# |i6 - µ1|, |i6 - µ2|, |i6 - µ3|
#
# |94 - 16|, |94 - 50|, |94 - 80|
#
# | 78,0 |, | 44,0 |, | 10,5 |
#
#
# |i7 - µ1|, |i7 - µ2|, |i7 - µ3|
#
# |94 - 16|, |94 - 50|, |94 - 80|
#
# | 83,0 |, | 49,0 |, | 15,5 |
#
# ================================================
# In[3]:
kmeans = KMeans(n_clusters=3).fit(data)
centroids = kmeans.cluster_centers_
labels = kmeans.labels_
print(centroids)
print(labels)
# # Visualizing the Clusters
# The code below visualizes the clusters.
# In[4]:
#show the data sparately
data['labels'] = labels
#plt.plot(data, colors[data['labels'], markersize = 10)
group1 = data[data['labels']==1].plot( kind='scatter', x='x', y='y', color='DarkGreen', label="Group 1" )
group2 = data[data['labels']==0].plot( kind='scatter', x='x', y='y', color='Brown', label="Group 2" )
group2 = data[data['labels']==2].plot( kind='scatter', x='x', y='y', color='Blue', label="Group 3" )
group1.legend(loc='upper center', bbox_to_anchor=(0.5, 1.05),ncol=3, fancybox=True, shadow=True)
plt.show()
# Show the data generally in a frame
# In[5]:
data['labels'] = labels
group1 = data[data['labels']==1].plot( kind='scatter', x='x', y='y', color='DarkGreen', label="Group 1" )
group2 = data[data['labels']==0].plot( kind='scatter', x='x', y='y', color='Brown', ax=group1, label="Group 2" )
group3 = data[data['labels']==2].plot( kind='scatter', x='x', y='y', color='Blue', ax=group2, label="Group 3" )
group1.legend(loc='upper center', bbox_to_anchor=(0.5, 1.05),ncol=3, fancybox=True, shadow=True)
plt.show()
# Finally, let's see generally with centroids included
# In[6]:
data['labels'] = labels
#plt.plot(data, colors[data['labels'], markersize = 10)
group1 = data[data['labels']==1].plot( kind='scatter', x='x', y='y', color='DarkGreen', label="Group 1" )
group2 = data[data['labels']==0].plot( kind='scatter', x='x', y='y', color='Brown', ax=group1, label="Group 2" )
group3 = data[data['labels']==2].plot( kind='scatter', x='x', y='y', color='Blue', ax=group2, label="Group 3" )
group1.legend(loc='upper center', bbox_to_anchor=(0.5, 1.05),ncol=3, fancybox=True, shadow=True)
plt.scatter(centroids[:, 0],centroids[:, 1], marker = "x", s=150, linewidths = 5, zorder = 10)
plt.show()
# By using K-Means, we do not need to compute the number or data manually by hand beacuse it will need much time to do.
#
# So, we can obtain the cluster easily by using K-Means.
# In[ ]:
|
ac397ee3fbd7df5022985a468516c39c43f33f07 | jakehoare/leetcode | /python_1_to_1000/962_Maximum_Width_Ramp.py | 1,408 | 3.71875 | 4 | _author_ = 'jake'
_project_ = 'leetcode'
# https://leetcode.com/problems/maximum-width-ramp/
# Given an array A of integers, a ramp is a tuple (i, j) for which i < j and A[i] <= A[j].
# The width of such a ramp is j - i.
# Find the maximum width of a ramp in A. If one doesn't exist, return 0.
# If a later element of A is greater than or equal to an earlier element then the earlier element makes a wider ramp.
# Hence we find the indices of strictly decreasing elements of A, which are candidates for the left edges of ramps.
# Then iterate over A again from the last index to the first, considering each element as the right edge of a ramp.
# When an element is greater than the top of stack, update max_ramp and pop off top of stack since lower index
# elements of A cannot make wider ramps.
# Time - O(n)
# Space - O(n)
class Solution(object):
def maxWidthRamp(self, A):
"""
:type A: List[int]
:rtype: int
"""
max_ramp = 0
stack = [] # stack of indices in decreasing value order, left edges of ramps
for i, num in enumerate(A):
if not stack or num < A[stack[-1]]:
stack.append(i)
for i in range(len(A) - 1, -1, -1): # iterate backwards
while stack and A[i] >= A[stack[-1]]:
max_ramp = max(max_ramp, i - stack.pop())
return max_ramp |
cf496e297dc07b5f085af40c74aeda1f66098854 | RaindropSaber/leetcode | /27.py | 325 | 3.59375 | 4 | class Solution(object):
def removeElement(self,nums,val):
number=len(nums)
for i in range(number-1,-1,-1):
if (nums[i]==val):
number-=1
nums[i],nums[number]=nums[number],nums[i]
return number
A=Solution()
a=[3,2,5,3,6,5,3]
A.removeElement(a,5)
print(a)
|
424d813512399d5e44a4c27d31a1169838c9f92b | TinaCloud/Python | /lynda/10 Exceptions/exceptions -- raise.py | 628 | 3.6875 | 4 | #!/usr/bin/python3
# exceptions.py by Bill Weinman [http://bw.org/]
# This is an exercise file from Python 3 Essential Training on lynda.com
# Copyright 2010 The BearHeart Gorup, LLC
def main():
try:
for line in readFile( 'xlines.doc' ): print( line.strip() )
except IOError as err:
print( "Can't open the file:", err )
except ValueError as err:
print( "Bad filename:", err )
def readFile( filename ):
if filename.endswith( '.txt' ):
fh = open( filename )
return fh.readlines()
else: raise ValueError( 'Filename must ends with .txt' )
if __name__ == "__main__": main()
|
a8dc79ea04276a0bfdbda33b17cddc34aabc0788 | love-adela/python_book | /think_python/solutions/ch5.py | 1,620 | 4.0625 | 4 | import time
import math
# Exercise 5-1
print('---------Exercise 5-1-----------')
def get_time():
epoch = time.time()
seconds_in_a_day = 24 * 60 * 60
seconds_in_an_hour = 60 * 60
seconds_in_a_minute = 60
days = epoch // seconds_in_a_day
hours = (epoch % seconds_in_a_day) // seconds_in_an_hour + 8
minutes = (epoch % seconds_in_a_day) % seconds_in_an_hour // seconds_in_a_minute
seconds = (epoch % seconds_in_a_day) % seconds_in_an_hour % seconds_in_a_minute
print('Current time is %d: %d: %d' % (hours, minutes, seconds))
print('Number of days since the epoch is %d' % (days))
get_time()
# Test
# TODO : python time모듈을 써서 자동으로 계산되게 짜보자.
# Exercise 5-2
print('---------Exercise 5-2-----------')
def check_fermat(n):
if pow(a, n) + pow(b, n) == pow(c, n):
print('Holy smikes, Fermat was wrong!')
else:
print("No, that doesn't work")
def prompt():
print('2보다 큰 수를 입력하세요.')
n = int(input())
if n <= 2:
print('2보다 큰 수여야 합니다.')
prompt()
else:
check_fermat(n)
a = int(input('a를 입력하세요'))
b = int(input('b를 입력하세요'))
c = int(input('c를 입력하세요'))
prompt()
# Exercise 5-3
print('---------Exercise 5-3-----------')
def is_triangle(a, b, c):
if a + b > c and a + c > b and b + c > a:
print('Yes')
else:
print('No')
def prompt():
a = input('a를 입력하세요')
b = input('b를 입력하세요')
c = input('c를 입력하세요')
return is_triangle(a, b, c)
prompt()
|
3ff1737ab510f68947c1c499fe6711eb961ab02a | wintersalmon/black-and-white | /cli/board_drawer.py | 3,488 | 3.609375 | 4 | '''
BLACK-AND-WHITE
WinterSalmon
Class Description
'''
from game.board.direction import DIRECTION
from game.board.color import COLOR
class BoardDrawer():
'''
Class Description
'''
def __init__(self, board):
self.board = board
self.row_count = board.get_row_count()
self.col_count = board.get_col_count()
self.marker = [[None for col in range(self.col_count)] for row in range(self.row_count)]
self.b_marker = [[None for col in range(self.col_count)] for row in range(self.row_count)]
def draw_color(self):
'''
Method Description
'''
if self.board:
for row in range(self.board.get_row_count()):
for col in range(self.board.get_col_count()):
color = self.board.get_block_color(row, col)
if self.marker[row][col]:
if self.b_marker[row][col]:
overlap_color = self.marker[row][col].get_color()
mixed_color = COLOR.mix_color(color, overlap_color)
color_text = color.get_color_text(mixed_color)
color_text = '[' + color_text + ']'
else:
overlap_color = self.marker[row][col].get_color()
mixed_color = COLOR.mix_color(color, overlap_color)
color_text = color.get_color_text(mixed_color)
color_text = '<' + color_text + '>'
else:
color_text = color.get_color_text(color)
print(color_text, end='\t')
print('\n')
else:
print('board not initialized')
def draw_overlap_counter(self):
'''
Method Description
'''
if self.board:
for row in range(self.board.get_row_count()):
for col in range(self.board.get_col_count()):
counter = self.board.get_block_overlap_count(row, col)
print(counter, end='\t')
print('\n')
else:
print('board not initialized')
def reset_marker(self):
'''
Method Description
'''
for row in range(self.row_count):
for col in range(self.col_count):
self.marker[row][col] = None
self.b_marker[row][col] = False
def set_marker(self, tile, row, col, direction):
'''
Method Description
'''
self.reset_marker()
if self.board.can_place_tile(tile, row, col, direction):
self.marker[row][col] = tile.get_block(0)
self.b_marker[row][col] = True
ad_row, ad_col = DIRECTION.adjust_row_col_by_direction(row, col, direction)
self.marker[ad_row][ad_col] = tile.get_block(1)
self.b_marker[ad_row][ad_col] = True
else:
if row >= 0 and row < self.row_count and col >= 0 and col < self.col_count:
self.marker[row][col] = tile.get_block(0)
self.b_marker[row][col] = False
ad_row, ad_col = DIRECTION.adjust_row_col_by_direction(row, col, direction)
if ad_row >= 0 and ad_row < self.row_count and ad_col >= 0 and ad_col < self.col_count:
self.marker[ad_row][ad_col] = tile.get_block(1)
self.b_marker[ad_row][ad_col] = False
|
7878ed0aac771681a1dd57a6778981aeb54be86e | cparker/pythonclub | /Oct05/TurtleWithMethods.py | 824 | 3.921875 | 4 | import turtle
def drawCircleAt(size, x, y):
turtle.color('red')
turtle.penup()
turtle.goto(x, y)
turtle.pendown()
turtle.circle(size)
def drawSquareAt(x, y):
turtle.penup()
turtle.goto(x, y)
turtle.pendown()
turtle.forward(20)
turtle.right(90)
turtle.forward(20)
turtle.right(90)
turtle.forward(20)
turtle.right(90)
turtle.forward(20)
def drawTriangleAt(x,y):
turtle.penup()
turtle.goto(x,y)
turtle.pendown()
turtle.forward(50)
turtle.right(120)
turtle.forward(50)
turtle.right(120)
turtle.forward(50)
drawTriangleAt(-100,-100)
drawTriangleAt(-100,-200)
drawSquareAt(50, 100)
drawSquareAt(100, 50)
drawSquareAt(50, 50)
drawCircleAt(20, 100, 100)
drawCircleAt(20, 100, 200)
drawCircleAt(20, 200, 200)
turtle.exitonclick()
|
337dffe18669adc3d52bcc1ae057c536fa64beea | PalmiraPereira/curves | /geometry.py | 2,985 | 3.671875 | 4 | from math import sqrt, pi
def dot(u, v):
return u.x*v.x + u.y*v.y
def cross(u, v):
return u.x*v.y - u.y*v.x
class Vector2D(object):
def __init__(self, x=0, y=0):
self.x = x
self.y = y
def mag(self):
return sqrt(self.x**2 + self.y**2)
def unit(self):
return Vector2D(self.x, self.y)/self.mag()
def __add__(self, other):
return Vector2D(self.x + other.x, self.y + other.y)
def __sub__(self, other):
return Vector2D(self.x - other.x, self.y - other.y)
def __neg__(self):
return Vector2D(-self.x, -self.y)
def __rmul__(self, other):
return Vector2D(other*self.x, other*self.y)
def __div__(self, other):
return Vector2D(self.x/other, self.y/other)
def __str__(self):
return '({},{})'.format(self.x, self.y)
class Line2D(object):
def __init__(self, r0=Vector2D(), d=Vector2D()):
self.r0 = r0
self.d = d.unit()
def intersect(self, other):
dr0 = other.r0 - self.r0
t1, t2 = cross(dr0, -other.d)/cross(self.d, -other.d), cross(self.d, dr0)/cross(self.d, -other.d)
return self(t1)
def __call__(self, t):
return self.r0 + t*self.d
class LineSegment2D(object):
def __init__(self, pt_a=Vector2D(), pt_b=Vector2D()):
self.pt_a = pt_a
self.pt_b = pt_b
def projection_is_bounded(self, pt):
t = dot(pt - self.pt_a, (self.pt_b - self.pt_a).unit())
return t >= 0. and t <= (self.pt_b - self.pt_a).mag()
def intersection(self, other):
if isinstance(other, Line2D):
xc = other.intersect(Line2D(self.pt_a, self.pt_b - self.pt_a))
return xc if self.projection_is_bounded(xc) else None
elif isinstance(other, LineSegment2D):
xc = Line2D(self.pt_a, self.pt_b - self.pt_a).intersect(Line2D(other.pt_a, other.pt_b - other.pt_a))
return xc if self.projection_is_bounded(xc) and other.projection_is_bounded(xc) else None
class Triangle(object):
def __init__(self, verts):
self.verts = [vert for vert in verts]
def area(self):
return abs(cross(self.verts[1] - self.verts[0], self.verts[2] - self.verts[0]))/2.
def centroid(self):
return (self.verts[0] + self.verts[1] + self.verts[2])/3.
class Circle(object):
def __init__(self, center=Vector2D(0., 0.), radius=0.):
self.center = center
self.radius = radius
def area(self):
return pi*self.radius**2
if __name__ == '__main__':
verts = Vector2D(0, 0), Vector2D(0, 1), Vector2D(1, 1)
tri = Triangle(verts)
print tri.centroid(), tri.area()
l1 = Line2D(Vector2D(0, 0), Vector2D(0, 1))
l2 = Line2D(Vector2D(1, 0), Vector2D(-1, 1))
print l1.intersect(l2)
print l2.intersect(l1)
l1 = LineSegment2D(Vector2D(0, 0), Vector2D(0, 1))
l2 = LineSegment2D(Vector2D(1, 0), Vector2D(0.432, 0.89))
print l1.intersection(l2)
print l2.intersection(l1)
|
cd5166db7b3fb2927310440adbbdcbd554b6b316 | Adiiigo/UdacityML | /decision_tree/dt_author_id.py | 1,183 | 3.5 | 4 | #!/usr/bin/python
"""
This is the code to accompany the Lesson 3 (decision tree) mini-project.
Use a Decision Tree to identify emails from the Enron corpus by author:
Sara has label 0
Chris has label 1
"""
import sys
from time import time
sys.path.append("../tools/")
from email_preprocess import preprocess
#import - Aditi Goyal
from sklearn import tree
from sklearn.metrics import accuracy_score
### features_train and features_test are the features for the training
### and testing datasets, respectively
### labels_train and labels_test are the corresponding item labels
features_train, features_test, labels_train, labels_test = preprocess()
#########################################################
### your code goes here ###
#min_smaple_split = minimum number of samples(NOS) required to split the leaf node
#if the NOS is less than 40 then splitting will not happen
clf = tree.DecisionTreeClassifier(min_samples_split=40)
clf.fit(features_train , labels_train)
labels_pred = clf.predict(features_test)
acc = accuracy_score(labels_test,labels_pred)
print "Accuracy = " , acc
#########################################################
|
413a21091f83da3b799a619ecc6b80aeb0adc130 | Pearwa-likeLion/Coursera | /testwhile.py | 106 | 3.90625 | 4 | x = int(input('Enter number : '))
while x > 0 :
print(x)
x = x - 1
print('Finish all good job!!')
|
9c31eeac0cb7af0094e3081ddf67377de70e500f | plee-lmco/python-algorithm-and-data-structure | /leetcode/415_Add_Strings.py | 1,922 | 4.09375 | 4 | # 415. Add Strings Easy
#
# Given two non-negative integers num1 and num2 represented as string, return the sum of num1 and num2.
#
# Note:
#
# The length of both num1 and num2 is < 5100.
# Both num1 and num2 contains only digits 0-9.
# Both num1 and num2 does not contain any leading zero.
# You must not use any built-in BigInteger library or convert the inputs to integer directly.
def addStrings(self, num1: str, num2: str) -> str:
return self.init_code(num1, num2)
# return self.add_string_zip(num1, num2)
def init_code(self, num1: str, num2: str) -> str:
'''
Runtime: 72 ms, faster than 20.72% of Python3 online submissions for Add Strings.
Memory Usage: 13.3 MB, less than 38.61% of Python3 online submissions for Add Strings.
'''
sum_string = ''
carry = 0
i = len(num1)
j = len(num2)
while (i > 0 or j > 0):
digit1 = '0' if i <= 0 else num1[i - 1]
digit2 = '0' if j <= 0 else num2[j - 1]
int_1 = ord(digit1) - ord('0')
int_2 = ord(digit2) - ord('0')
curr_sum = int_1 + int_2 + carry
carry = curr_sum // 10
sum_string = str(curr_sum % 10) + sum_string
i -= 1
j -= 1
if carry:
sum_string = '1' + sum_string
return sum_string
def add_string_zip(self, num1: str, num2: str) -> str:
'''
Runtime: 52 ms, faster than 74.83% of Python3 online submissions for Add Strings.
Memory Usage: 13.4 MB, less than 19.13% of Python3 online submissions for Add Strings.
'''
from itertools import zip_longest
result = ''
carry = 0
for digit1, digit2 in zip_longest(reversed(num1), reversed(num2), fillvalue='0'):
int_1 = ord(digit1) - ord('0')
int_2 = ord(digit2) - ord('0')
curr_sum = int_1 + int_2 + carry
result = str(curr_sum % 10) + result
carry = curr_sum // 10
return '1' + result if carry == True else result
|
f920135a5acb9309140cf7ec99d688c224e6069e | UCSB-dataScience-ProjectGroup/nlpgroup | /examples/ex_nltk.py | 2,896 | 3.546875 | 4 | # basic nltk example
import nltk
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.feature_extraction.text import TfidfTransformer
from sklearn.feature_extraction.text import CountVectorizer
if __name__ == "__main__":
sometext = "a b c d e f g h a b c h i j k l m a b"
tokens = nltk.word_tokenize(sometext)
print()
print('tokens:', tokens)
print()
fd = nltk.FreqDist(tokens)
print('frequency distribution:', fd)
print()
print('How to use tf-idf: what is unique about each document?')
docs = [
'Hello you are my friend world.',
'This is a test called hello world.',
'why would i use this test?'
]
tok_docs = [nltk.word_tokenize(doc) for doc in docs]
print()
print('start with tokenized docs:', tok_docs)
print()
print('(pretend each sentence is a doc)')
print()
#tfidf = TfidfVectorizer(tokenizer=nltk.word_tokenize, stop_words='english')
#response = tfidf.transform(docs)
#feature_names = response.get_feature_names()
#print([feature_names[col] + response[0,col] in response.nonzero()[1]])
#print(feature_names)
from sklearn.feature_extraction.text import CountVectorizer
vectorizer = CountVectorizer(min_df=1)
print(vectorizer)
print()
X = vectorizer.fit_transform(docs)
print(X)
print(X.toarray())
print()
print(vectorizer.get_feature_names())
print()
print()
from sklearn.feature_extraction.text import TfidfTransformer
transformer = TfidfTransformer(smooth_idf=False)
print(transformer)
tfidf = transformer.fit_transform(X)
print(tfidf.toarray())
# make a list of dicts
wordlist = list(vectorizer.get_feature_names())
print(wordlist)
tfidf_lookup = tfidf.toarray()
scores = list()
dontuse = ['.','a','i','?']
for i in range(len(docs)):
docscores = dict()
from sklearn.feature_extraction.text import TfidfTransformer
transformer = TfidfTransformer(smooth_idf=False)
print(transformer)
tfidf = transformer.fit_transform(X)
print(tfidf.toarray())
# make a list of dicts
wordlist = list(vectorizer.get_feature_names())
print(wordlist)
tfidf_lookup = tfidf.toarray()
scores = list()
dontuse = ['.','a','i','?']
for i in range(len(docs)):
docscores = dict()
for word in nltk.word_tokenize(docs[i]):
if word not in dontuse:
wordind = wordlist.index(word.lower())
score = tfidf_lookup[i][wordind]
docscores[word] = score
scores.append(docscores)
for word in nltk.word_tokenize(docs[i]):
if word not in dontuse:
wordind = wordlist.index(word.lower())
score = tfidf_lookup[i][wordind]
docscores[word] = score
scores.append(docscores)
print()
print(scores)
print()
|
b039a56596a379bf2e899c0b50c3ea6ce84b72a8 | sarkisc/cs-61a-labs | /lab08/lab08/lab08.py | 3,693 | 4.125 | 4 | ## Linked Lists and Sets ##
# Linked Lists
class Link:
"""A linked list.
>>> s = Link(1, Link(2, Link(3, Link(4))))
>>> len(s)
4
>>> s[2]
3
>>> s
Link(1, Link(2, Link(3, Link(4))))
"""
empty = ()
def __init__(self, first, rest=empty):
assert rest is Link.empty or isinstance(rest, Link)
self.first = first
self.rest = rest
def __getitem__(self, i):
if i == 0:
return self.first
else:
return self.rest[i-1]
def __len__(self):
return 1 + len(self.rest)
def __repr__(self):
if self.rest is not Link.empty:
rest_str = ', ' + repr(self.rest)
else:
rest_str = ''
return 'Link({0}{1})'.format(repr(self.first), rest_str)
def list_to_link(lst):
"""Takes a Python list and returns a Link with the same elements.
>>> list_to_link([1, 2, 3])
Link(1, Link(2, Link(3)))
"""
"*** YOUR CODE HERE ***"
#if lst == []:
#return
#elif len(lst) == 1:
#return Link(lst[0])
if lst == []:
return Link.empty # This is great. Notice that you're calling list_to_link([])
# within the call list_to_link([last_elem])
else:
return Link(lst[0], list_to_link(lst[1:])) # remember: you don't have to specify the end index
# I want from index 1 until the end of the list
def link_to_list(link):
"""Takes a Link and returns a Python list with the same elements.
>>> link = Link(1, Link(2, Link(3, Link(4))))
>>> link_to_list(link)
[1, 2, 3, 4]
>>> link_to_list(Link.empty)
[]
"""
"*** YOUR CODE HERE ***"
if link is Link.empty:
return []
else:
return [link.first] + link_to_list(link.rest)
def slice_link(link, start, end):
"""Slices a Link from start to end (as with a normal Python list).
>>> link = Link(3, Link(1, Link(4, Link(1, Link(5, Link(9))))))
>>> slice_link(link, 1, 4)
Link(1, Link(4, Link(1)))
"""
"*** YOUR CODE HERE ***"
return list_to_link( link_to_list(link)[start:end] )
# Sets
def union(s1, s2):
"""Returns the union of two sets.
>>> r = {0, 6, 6}
>>> s = {1, 2, 3, 4}
>>> t = union(s, {1, 6})
>>> t
{1, 2, 3, 4, 6}
>>> union(r, t)
{0, 1, 2, 3, 4, 6}
"""
"*** YOUR CODE HERE ***"
s = set()
for member in s1:
s.add(member)
for member in s2:
s.add(member)
return s
def intersection(s1, s2):
"""Returns the intersection of two sets.
>>> r = {0, 1, 4, 0}
>>> s = {1, 2, 3, 4}
>>> t = intersection(s, {3, 4, 2})
>>> t
{2, 3, 4}
>>> intersection(r, t)
{4}
"""
"*** YOUR CODE HERE ***"
return s1.intersection(s2) # ...
def extra_elem(a,b):
"""B contains every element in A, and has one additional member, find
the additional member.
>>> extra_elem(['dog', 'cat', 'monkey'], ['dog', 'cat', 'monkey', 'giraffe'])
'giraffe'
>>> extra_elem([1, 2, 3, 4, 5], [1, 2, 3, 4, 5, 6])
6
"""
"*** YOUR CODE HERE ***"
return list( set(a).symmetric_difference(set(b)) )[0] # don't need to turn b into a set
# the function will accept a list as an arg.
def find_duplicates(lst):
"""Returns True if lst has any duplicates and False if it does not.
>>> find_duplicates([1, 2, 3, 4, 5])
False
>>> find_duplicates([1, 2, 3, 4, 2])
True
"""
"*** YOUR CODE HERE ***"
return len( set(lst) ) != len(lst)
|
2b808f852da4ccfd6b090bb6a94977bf2a2c9f84 | AricA05/Year_10_Design | /CCC_Practice_Q's/TournamentSelection.py | 407 | 3.53125 | 4 |
def runFunction():
v1 = input()
v2 = input()
v3 = input()
v4 = input()
v5 = input()
v6 = input()
wins = 0
if v1 == "W":
wins+=1
if v2 == "W":
wins+=1
if v3 == "W":
wins+=1
if v4 == "W":
wins+=1
if v5 == "W":
wins+=1
if v6 == "W":
wins+=1
if wins >=5:
return (1)
elif wins >= 3:
return (2)
elif wins >= 1:
return (3)
else:
return (-1)
print(runFunction()) |
a8a50ed27a3da41e8436c58436c7a07829fc928f | RyhanSunny/myPythonJourney | /Self-study__Book_Exercises/ex-4__page_64.py | 1,803 | 4.0625 | 4 | # 4-3. Counting to Twenty: Use a for loop to print the numbers from 1 to 20, inclusive.
#
list1 = []
for i in range(1, 21):
list1 += [i]
print(list1)
# 4-4. One Million: Make a list of the numbers from one to one million, and then use a for loop to print the numbers
# If the output is taking too long, stop it by pressing ctrl-C or by closing the output window)
#
oneMill = [i for i in range(1, 1000001)]
# for n in oneMill:
# print(n)
# 4-5. Summing a Million: Make a list of the numbers from one to one million, and then use min() and max() to make
# sure your list actually starts at one and ends at one million . Also, use the sum() function to see how quickly
# Python can add a million numbers
oneMill = [i for i in range(1, 1000001)]
print('min of 1 mill: ' + str(min(oneMill)))
print('max of 1 mill: ' + str(max(oneMill)))
print('sum: ' + str(sum(oneMill)))
# 4-6. Odd Numbers: Use the third argument of the range() function to make a list of the odd numbers from 1 to 20 .
# Use a for loop to print each number.
for i in range(1, 20, 2):
print(i)
# 4 -7. Threes: Make a list of the multiples of 3 from 3 to 30. Use a for loop to print the numbers in your list
for i in range(3, 30, 3):
print(i)
# 4-8. Cubes: Make a list of the first 10 cubes (that is, the cube of each integer from 1 through 10), and use a for
# loop to print out the value of each cube
value = []
for i in range(1, 10):
value.append(i**3)
print('\n')
print(value)
# 4-9. Cube Comprehension: Use a list comprehension to generate a list of the first 10 cubes
cubes = [value ** 3 for value in range(1, 10)]
print('\n')
for cube in cubes:
print(cube)
# RANDOM print formatting
name = 'don'
num = 8
print('name is %s, number is %i'%(name,num))
# or
print('name is {}, number is {}'.format(name, num)) |
8cda5b0fe2195d26579781e7a44b7410a8d04803 | codeprogredire/data-structures-and-algorithms | /Dynamic Programming/4.py | 669 | 3.609375 | 4 | '''
Link: https://leetcode.com/problems/minimum-path-sum/
'''
class Solution:
def minPathSum(self, grid: List[List[int]]) -> int:
m=len(grid)
n=len(grid[0])
a=[[0]*n]*m
for i in range(m):
for j in range(n):
if i==0:
if j==0:
a[i][j]=grid[i][j]
else:
a[i][j]=a[i][j-1]+grid[i][j]
elif j==0:
a[i][j]=a[i-1][j]+grid[i][j]
else:
a[i][j]=min(a[i-1][j],a[i][j-1])+grid[i][j]
return a[m-1][n-1]
|
f5662e9721fdcffdba9dffefec3ec2043ca3de10 | itsolutionscorp/AutoStyle-Clustering | /all_data/exercism_data/python/allergies/9acb6049e9164932bcf5d71b48854bfb.py | 570 | 3.75 | 4 |
class Allergies(object):
def __init__(self, rating):
self.list = []
self.allergins = ['eggs', 'peanuts', 'shellfish',
'strawberries', 'tomatoes', 'chocolate',
'pollen', 'cats']
self.sorting = {i: v for i, v in enumerate(self.allergins)}
if rating > 0:
for i in self.sorting:
if 2**i == (2**i & rating):
self.list.append(self.sorting[i])
def is_allergic_to(self, allergin):
return allergin in self.list
|
7802a821694f0e0ef6dc4da6b5b01ea4ae8b398c | PeturSteinn/GAGN3GS05DU-PSG | /Verkefni_1/A/main.py | 3,106 | 3.96875 | 4 | import json
jsonOutput = {}
def main():
while True:
path = "resources/The_Frozen_Dead_S01E01_ENGLISH.srt"
language = input("Language: ").lower()
while True:
result = input('Use default date/studio/translators? (y/n): ')
if result == '' or not result.lower() in ['y','n']:print('Please answer with y or n')
else: break
if result.lower() == 'y':
date = "01-01-2019"
studio = "Media Subtitle Studio"
translators = ["Oscar Johnson"]
else:
date = input("Date: ")
studio = input("Studio: ")
translators = input("Translators (split with ','): ").title().split(",")
print("Working...")
if buildTree(date, studio, translators, language): print("Building tree for language worked")
else:
print("Building tree for language failed")
break
if convertToDict(path, language): print("Converting srt to dictionary worked")
else:
print("Converting srt to dictionary failed")
break
print("Success!")
while True:
result = input('Add another language? (y/n): ')
if result == '' or not result.lower() in ['y','n']:print('Please answer with y or n')
else: break
if result.lower() == 'y':
print("Continuing...")
else:
print("Ok")
with open('GENERATED_The_Frozen_Dead_S01E01.json', 'w') as file: json.dump(jsonOutput, file)
break
# Options
# path = "The_Frozen_Dead_S01E01_ENGLISH.srt"
# language = "english"
# date = "01-01-2019"
# studio = "Media Subtitle Studio"
# translators = ["Oscar Johnson"]
# Foundation
def buildTree(date, studio, translators, language):
try:
jsonOutput[language] = {}
jsonOutput[language]['date'] = date
jsonOutput[language]['studio'] = studio
jsonOutput[language]['translators'] = translators
jsonOutput[language]['id'] = {}
return True
except:
return False
# Statuses
# 1: ID
# 2: Timestamps
# >2: Text
def convertToDict(path, language):
try:
with open(path, 'r', encoding='UTF-8-SIG') as file:
status = 0
currID = ""
for index, i in enumerate(file):
status += 1
i = i.strip()
if status == 1:
currID = i
jsonOutput[language]['id'][currID] = {}
elif status == 2:
jsonOutput[language]['id'][currID]['start'] = i.split(' --> ')[0]
jsonOutput[language]['id'][currID]['end'] = i.split(' --> ')[1]
elif status > 2:
if len(i):
if "text" in jsonOutput[language]['id'][currID]: jsonOutput[language]['id'][currID]['text'] += "\n" + i
else: jsonOutput[language]['id'][currID]['text'] = i
if len(i) == 0: status = 0
return True
except:
return False
if __name__ == "__main__": main()
|
c60ffef9a931836f9382f57df3fd0160a5a26f24 | TheStellaCreation/pycharm-practice | /Python Tutorial /student.py | 856 | 4 | 4 | class Student:
def __init__(self, name, major, gpa):
# all student object data gonna passed into init this function, when we create the student object we actually
# calling this function.
# (self, name, major, gpa, is_on_probation) this are just parameters we passed in
# belows self.name are actual value.
self.name = name # the name of the student object is equal to the name we passed in eg: student1.name
self.major = major # etc.
self.gpa = gpa
# this is defining what is student data type is
# we can use functions inside this class
# we can create a function inside this class and all student objects could access this class
def on_honor_roll(self):
if self.gpa >= 3.5: # referring to the actual student gpa
return True
else:
return False
|
3e9a0de72645bf8c70f369f68369e6b78969b126 | babiswas2020/Python | /distance.py | 799 | 3.96875 | 4 | class Node:
def __init__(self,value):
self.value=value
self.left=None
self.right=None
def distance(root,x):
dist=-1
dist1=0
dist2=0
if not root:
return -1
elif root==x:
return 0
else:
if node.left:
dist1=distance(node.left,x)
if node.right:
dist2=distance(node.right,x)
if dist1>0:
dist=dist1+1
elif dist2>0:
dist=dist2+1
return dist
if __name__=="__main__":
node=Node(12)
node.left=Node(21)
node.right=Node(13)
node.right.left=Node(17)
node.right.right=Node(19)
node.left.right=Node(25)
node.left.left=Node(31)
node.right.right.left=Node(40)
node.right.right.right=Node(34)
print(distance(node,node.right.right.left))
|
c33489a70c279a67d1fab6afd7916cb3130aa3cc | Ashwin-19/LeetCode | /June Challenge/Day12_insertdeletegetRandomO1.py | 1,192 | 4.09375 | 4 | class RandomizedSet:
def __init__(self):
"""
Initialize your data structure here.
"""
self.map = []
self.data = {}
def insert(self, val: int) -> bool:
"""
Inserts a value to the set. Returns true if the set did not already contain the specified element.
"""
if val in self.data:
return False
self.map.append(val)
self.data[val] = len(self.map)-1
return True
def remove(self, val: int) -> bool:
"""
Removes a value from the set. Returns true if the set contained the specified element.
"""
if val in self.data:
index = self.data[val]
l = len(self.map)
self.map[index],self.map[l-1] = self.map[l-1],self.map[index]
self.data[self.map[index]] = index
self.map.pop()
del self.data[val]
return True
return False
def getRandom(self) -> int:
"""
Get a random element from the set.
"""
index = random.randint(0,len(self.map)-1)
return self.map[index] |
c4e9da631193009891d665455ef396d0fe4b2754 | Lukasavicus/MachineLearning_Library | /UFSCar_ML_Class/Python/LinReg/ex02.py | 7,557 | 3.734375 | 4 | ## Universidade Federal de Sao Carlos - UFSCar, Sorocaba
#
# Disciplina: Aprendizado de Máquina
# Prof. Tiago A. Almeida
#
# Exercicio 2 - Regressao Linear
#
# Instrucoes
# ----------
#
# Este arquivo contem o codigo que auxiliara no desenvolvimento do
# exercicio. Voce precisara completar as seguintes funcoes:ns:
#
# plotarDados.m
# gradienteDescente.m
# computarCusto.m
#
# Voce nao podera criar nenhuma outra funcao. Apenas altere as rotinas
# fornecidas.
#
# Dados:
# x refere-se ao tamanho da populacao (x 10.000 pessoas)
# y refere-se a arrecadacao (x R$ 100.000,00)
#
## Inicializacao
#clear ; close all; clc
## ======================= Parte 1: Plotando dados =======================
import csv
import plotarDados as pd
import computarCusto as cc
import gradienteDescente as gd
import matplotlib.pyplot as plt
#fprint('Plotando dados ...\n')
print('Plotando dados ...\n')
#data = load('ex02Dados.txt')
file = open('ex02Dados.csv', 'r')
csv_reader = csv.reader(file)
list_reader = list(csv_reader)
#X = data(:, 1); y = data(:, 2)
X = [float(li[0]) for li in list_reader]
y = [float(li[1]) for li in list_reader]
#m = length(y); # numero de exemplos de treinamento
m = len(y); # numero de exemplos de treinamento
# Plotando os Dados
# VOCE PRECISA COMPLETAR O CODIGO PLOTARDADOS.M
pd.plotarDados(X, y);
#fprint('\nPrograma pausado. Pressione enter para continuar.\n\n');
#pause;
## =================== Parte 2: Gradiente descente ===================
#fprint('Calculando Gradiente Descente ...\n')
print('Calculando Gradiente Descente ...\n')
#X = [ones(m, 1), data(:,1)]; # Adicionar uma coluna de 1s em x
X = zip([1 for x in X], X) # Adicionar uma coluna de 1s em x
#theta = zeros(2, 1); # Inicializa parâmetros que serao ajustados
theta = [0, 0] # Inicializa parâmetros que serao ajustados
# Algumas configuracoes do gradiente descente
iteracoes = 1500;
alpha = 0.01;
# calcula e exibe o custo inicial
# VOCE PRECISA COMPLETAR O CODIGO COMPUTARCUSTO.M
J = cc.computarCusto(X, y, theta);
#fprint('Custo inicial: ');
print('Custo inicial: ')
#fprint('#f\n', J);
print('%f\n' % J)
# chama o metodo do gradiente descente
# VOCE PRECISA COMPLETAR O CODIGO GRADIENTEDESCENTE.M
(theta, J_historico) = gd.gradienteDescente(X, y, theta, alpha, iteracoes);
# imprime o valor de Theta
#fprint('Theta encontrado pelo gradiente descendente: ');
print('Theta encontrado pelo gradiente descendente: ')
#fprint('#f #f \n', theta(1), theta(2));
print('%f %f \n' % (theta[0] , theta[1]))
# Plota o regressor linear
#hold on; # mantem o plot anterior
#plot(X(:,2), X*theta, 'r-', 'LineWidth', 2);
#legend('Dados de treinamento', 'Regressor linear')
scatter_x_pts = [x[1] for x in X];
scatter_y_pts = X_times_T = [sum(map(lambda m1, m2: float(m1 * m2), theta, x)) for x in X];
fig = plt.figure()
sub_fig = fig.add_subplot(111)
sub_fig.scatter(scatter_x_pts, y, c='b', marker='x')
sub_fig.plot(scatter_x_pts, scatter_y_pts, c='r', marker='+', linewidth=2)
plt.show()
#hold off
#fprint('\nPrograma pausado. Pressione enter para continuar.\n\n');
#pause;
# Plota o grafico de convergencia do gradiente descente
# O valor sempre devera ser decrescente ou igual no decorrer das iteracoes
#figure;
#plot(1:numel(J_historico), J_historico, 'b-', 'LineWidth', 2);
#title('Convergencia do Gradiente Descendente');
#xlabel('# iteracoes');
#ylabel('Custo J');
fig = plt.figure()
sub_fig = fig.add_subplot(111)
sub_fig.plot(list(range(len(J_historico))), J_historico, c='b', marker='.', linewidth=2)
plt.show()
# Prediz resultados orcamentarios para cidades com populacao de 40.000 e
# 70.000 habitantes
#predict1 = [1, 4] * theta;
predict1 = sum(map(lambda m1, m2: m1 * m2 , [1, 4], theta));
#fprint('Para populacao = 40.000, resultado orcamentario previsto = #f\n',...
print('Para populacao = 40.000, resultado orcamentario previsto = %f\n' % \
predict1*100000)
#predict2 = [1, 8] * theta;
predict2 = sum(map(lambda m1, m2: m1 * m2 , [1, 8], theta));
#fprint('Para populacao = 80.000, resultado orcamentario previsto = #f\n',...
print('Para populacao = 80.000, resultado orcamentario previsto = %f\n' % \
predict2*100000);
#fprint('\nPrograma pausado. Pressione enter para continuar.\n\n');
#pause;
## ============= Parte 3: Visualizando J(theta_0, theta_1) =============
#fprint('Visualizando J(theta_0, theta_1) ...\n')
print('Visualizando J(theta_0, theta_1) ...\n')
def linrange(start, stop, n_elem):
x = float(start);
diff = abs(start - stop)+1;
step = float(float(diff) / float(n_elem));
r = [0.0 for z in range(n_elem)];
i = 0;
while(i < n_elem):
r[i] = x;
if(start < stop):
x += step;
else:
x -= step;
i += 1;
return r;
# Grade sobre a qual J sera calculado
#theta0_vals = linspace(-10, 10, 100);
theta0_vals = linrange(-10, 10, 100);
#theta1_vals = linspace(-1, 4, 100);
theta1_vals = linrange(-1, 4, 100);
# Initializa J_vals em uma matriz de 0's
#J_vals = zeros(length(theta0_vals), length(theta1_vals))
def bidim_zeros(n, m):
return [[0 for x in range(n)] for y in range(m)]
J_vals = bidim_zeros(len(theta0_vals), len(theta1_vals));
# Calcula todos os valores de J_vals
#for i = 1:length(theta0_vals)
# for j = 1:length(theta1_vals)
# t = [theta0_vals(i); theta1_vals(j)];
# J_vals(i,j) = computarCusto(X, y, t);
# end
#end
for i in range(len(theta0_vals)):
for j in range(len(theta1_vals)):
t = [theta0_vals[i], theta1_vals[j]];
J_vals[i][j] = cc.computarCusto(X, y, t);
# Devido a forma como meshgrid trabalha com o comando surf, eh preciso
# transpor J_vals antes de chamar surf, ou entao os eixos serao invertidos
#J_vals = J_vals'
#<<<<<<<<<<<<<<<<< HERE NEED TO BE PYTHONIZED:
# Plota a superficie
figure;
surf(theta0_vals, theta1_vals, J_vals)
xlabel('\theta_0'); ylabel('\theta_1'); zlabel('Custo J');
#fprint('\nPrograma pausado. Pressione enter para continuar.\n\n');
#print('\nPrograma pausado. Pressione enter para continuar.\n\n');
#pause;
#fprint('Visualizando o contorno de J(theta_0, theta_1) ...\n')
print('Visualizando o contorno de J(theta_0, theta_1) ...\n')
# Plota o contorno
figure;
# Plota J_vals como 15 linhas de contorno espacadas logaritimicamente entre
# 0.01 e 100
contour(theta0_vals, theta1_vals, J_vals, logspace(-2, 3, 20))
xlabel('\theta_0'); ylabel('\theta_1');
#hold on;
plot(theta[0], theta[1], 'rx', 'MarkerSize', 10, 'LineWidth', 2);
#fprint('\nPrograma pausado. Pressione enter para continuar.\n\n');
#pause;
## ============= Parte 4: Predizendo o valor de novos dados =============
#fprint('Predizendo o valor de novos dados...\n\n')
#popSize = input('Informe o tamanho da populacao (x 10.000) ou -1 para SAIR: ');
#while (popSize ~= -1)
# predict = [1, popSize] *theta; # Faz a predicao usando theta encontrado
#fprint('Para populacao = #d, resultado orcamentario previsto = #f\n\n',...
# popSize = input('Informe o tamanho da populacao (x 10.000) ou -1 para SAIR: ');
#end
print('Predizendo o valor de novos dados...\n\n')
popSize = input('Informe o tamanho da populacao (x 10.000) ou -1 para SAIR: ');
while (popSize != -1):
predict = sum(map(lambda m1, m2: m1 * m2 , [1, popSize], theta));
#fprint('Para populacao = #d, resultado orcamentario previsto = #f\n\n',...
print('Para populacao = #d, resultado orcamentario previsto = %f\n\n' % \
popSize*10000, predict*100000);
popSize = input('Informe o tamanho da populacao (x 10.000) ou -1 para SAIR: ');
## Finalizacao
#close all; clear all; |
e9fc3644812cd1e306b2d8a27c6c7dec3780cb2a | MrHamdulay/csc3-capstone | /examples/data/Assignment_7/fkrray001/push.py | 3,557 | 3.625 | 4 | # Author : Rayaan Fakier FKRRAY001
# Date : 30 - 04 - 2014
# push.py
import util
def push_left(grid):
for row in range(4):
# Creates a temporary list of row values
row_vals = []
for value in range(4):
row_vals.append(grid[row][value])
# Moves numbers to end
for nums in range(4):
if row_vals[nums] == 0:
row_vals.remove(0)
row_vals.append(0)
# Adds adjacent nums that are equal
for num in range(3):
if row_vals[num] == row_vals[num+1]:
val_add = row_vals[num+1]
row_vals.remove(row_vals[num+1])
row_vals.append(0)
row_vals[num] += val_add
# Replaces grid values with new (added) values
for replacement in range(4):
grid[row][replacement] = row_vals[replacement]
return grid
def push_right(grid):
for row in range(4):
# Creates a temporary list of row values
row_vals = []
for value in range(3,-1,-1):
row_vals.append(grid[row][value])
# Moves numbers to end
for nums in range(4):
if row_vals[nums] == 0:
row_vals.remove(0)
row_vals.append(0)
# Adds adjacent nums that are equal
for num in range(3):
if row_vals[num] == row_vals[num+1]:
val_add = row_vals[num+1]
row_vals.remove(row_vals[num+1])
row_vals.append(0)
row_vals[num] += val_add
# Replaces grid values with new (added) values
rep_place = 0
for replacement in range(3,-1,-1):
grid[row][rep_place] = row_vals[replacement]
rep_place += 1
return grid
def push_up(grid):
# Creates a temporary list of column values
for column in range(4):
column_vals = []
for val in range(4):
column_vals.append(grid[val][column])
# Moves numbers to end
for nums in range(4):
if column_vals[nums] == 0:
column_vals.remove(0)
column_vals.append(0)
# Adds nums below that are equal
for num in range(3):
if column_vals[num] == column_vals[num+1]:
val_add = column_vals.pop(num+1)
column_vals[num] += val_add
column_vals.append(0)
# Replaces grid values with new (added) values
for k in range (4):
grid[k][column] = column_vals[k]
return grid
def push_down(grid):
# Creates a temporary list of column values
for column in range(4):
column_vals = []
for val in range(3,-1,-1):
column_vals.append(grid[val][column])
# Moves numbers to end
for nums in range(4):
if column_vals[nums] == 0:
column_vals.remove(0)
column_vals.append(0)
# Adds nums above that are equal
for num in range(3):
if column_vals[num] == column_vals[num+1]:
val_add = column_vals.pop(num+1)
column_vals[num] += val_add
column_vals.append(0)
# Replaces grid values with new (added) values
rep_place = 0
for k in range (3,-1,-1):
grid[rep_place][column] = column_vals[k]
rep_place += 1
return grid |
bb65845598626a43e2cda1384e2756dd57777a71 | CihatAcar/Python-Learning-Projects | /arithmeticOperations.py | 341 | 4.46875 | 4 | print(10 / 3) # --> float
print(10 // 3) # --> Integer
print(10 % 3) # Remainder of division!
print(10 ** 3) # Power
x = 10
x = x + 3
x -= 3
print(x)
x = 10 + 3 * 2 ** 2 # Operation Precedents
print(x)
# _1parantheses then exponentiation = 2 ** 3
# _2multiplication = 2 * 3 or division = 2 / 3
# _3addition = 2 + 3 or substraction = 2 - 3 |
77f5e4e1736dcf394ad896f850963ae5f8d2f348 | knakajima3027/Atcoder | /python/ABC/ABC169/169_D.py | 715 | 3.609375 | 4 | N = int(input())
#nを素因数分解したリストを返す
def prime_factor(n):
i = 2
table = []
while i * i <= n:
while n % i == 0:
n //= i
table.append(i)
i += 1
if n > 1:
table.append(n)
return table
primes = prime_factor(N)
prime_dic = {}
for i in range(len(primes)):
if primes[i] in prime_dic:
prime_dic[primes[i]] += 1
else:
prime_dic[primes[i]] = 1
sum_list = [0 for _ in range(30)]
sum_list[0] = 1
for i in range(29):
sum_list[i+1] += sum_list[i] + (i + 2)
ans = 0
for key in prime_dic:
for i in range(30):
if sum_list[i] > prime_dic[key]:
ans += i
break
print(ans) |
6ee7ed7a04cfcb5325f58bf60d4ad2fd367f6860 | Naganandhinisri/python-beginner | /hacker_rank/palindrome.py | 233 | 4.28125 | 4 | word = "12345"
new_word = "54321"
sorted_word = sorted(word)
new_sorted_word = sorted(new_word)
if sorted_word == new_sorted_word:
print('the given string is palindrome')
else:
print('The given string is not palindrome')
|
ee1b09994e9f85446dd93877f655c5206de74ad4 | yordan-marinov/fundamentals_python | /mid_exams/array_manipulator.py | 1,517 | 3.78125 | 4 | from itertools import zip_longest
def adding(lst, indx, el):
lst.insert(indx, el)
return lst
def adding_many(lst, indx, lst_1):
lst[indx:indx] = lst_1
return lst
def contains_element(lst, el):
if el in lst:
print(lst.index(el))
else:
print(-1)
def remove_element(lst, indx):
lst.pop(indx)
return lst
def shifting(lst):
return lst.append(lst.pop(0))
def sum_pairs(lst):
l_1 = [lst[i] for i in range(len(lst)) if i % 2 != 0]
l_2 = [lst[i] for i in range(len(lst)) if i % 2 == 0]
return [i + j for i, j in zip_longest(l_1, l_2, fillvalue=0)]
numbers = [int(i) for i in input().split()]
while True:
data = input().split()
command = data.pop(0)
if command == "add":
index, element = int(data[0]), int(data[1])
numbers = adding(numbers, index, element)
elif command == "addMany":
index = int(data[0])
elements = [int(i) for i in data[1:]]
numbers = adding_many(numbers, index, elements)
del elements
elif command == "contains":
element = int(*data)
contains_element(numbers, element)
elif command == "remove":
index = int(*data)
numbers = remove_element(numbers, index)
elif command == "shift":
positions_count = int(*data)
[shifting(numbers) for _ in range(positions_count)]
elif command == "sumPairs":
numbers = sum_pairs(numbers)
elif command == "print":
print(numbers)
break
|
0f3cb430b367a0470d909589a3c7cad340791876 | WalaaAlkady/Bioinformatics | /InFrameStopCodon.py | 940 | 3.953125 | 4 | def IsDNAorRNAhasStopCodon(seq , DNAorRNA):
"This function checks if given sequence has in frame stop codon"
DNAStopCodons = ['TGA' , 'TAG' , 'TAA']
RNAStopCodons = ['UGA' , 'UAG' , 'UAA']
hasStopCodon = False
if DNAorRNA == '1':
for i in range(0, len(seq), 3):
codon = seq[i:i+3].upper()
if codon in DNAStopCodons:
hasStopCodon = True
break
else:
for i in range(0, len(seq), 3):
codon = seq[i:i+3].upper()
if codon in RNAStopCodons:
hasStopCodon = True
break
return hasStopCodon
# Main:
Sequence = input("Please Enter the Sequence:")
DNAorRNA = input("Enter 1 for DNA and 2 for RNA ")
if IsDNAorRNAhasStopCodon(Sequence , DNAorRNA):
print('Input Sequence has an in frame stop codon')
else:
print('Input Sequence has no an in frame stop codon') |
256dc213bed92b406bf09e6fde8ef8205832b318 | powerwaffe/Python-Programs | /ISY150/Section8/8-3.py | 1,383 | 4.0625 | 4 | def main():
keep_asking = 'y'
while keep_asking == 'y':
# ask for date input
user_input = input('Enter date in the form of mm/dd/yyyy')
# split string
date = user_input.split('/')
# print formatted date with name
if date[0] == '01':
print('January', date[1], ',', date[2])
elif date[0] == '02':
print('February', date[1], ',', date[2])
elif date[0] == '03':
print('March', date[1], ',', date[2])
elif date[0] == '04':
print('April', date[1], ',', date[2])
elif date[0] == '05':
print('May', date[1], ',', date[2])
elif date[0] == '06':
print('June', date[1], ',', date[2])
elif date[0] == '07':
print('July', date[1], ',', date[2])
elif date[0] == '08':
print('August', date[1], ',', date[2])
elif date[0] == '09':
print('September', date[1], ',', date[2])
elif date[0] == '10':
print('October', date[1], ',', date[2])
elif date[0] == '11':
print('November', date[1], ',', date[2])
elif date[0] == '12':
print('December', date[1], ',', date[2])
else:
print('INCORRECT FORMAT!!')
keep_asking = input('Would you like to enter another date? y or n').lower()
main() |
14feeee040b1f521058ef6371cb8f472ef717be5 | nojongmun/python_basics | /step07_object/object/objectEx5_1.py | 1,180 | 4.0625 | 4 | '''''
클래스명 : Sales
- item : str
- qty : int
- cost : int
+property, *.setter
+ *.__str__() ==> 출력문
+ getPrice() ==> qty*cost(수량 * 단가)를 리턴
--출력
apple 1200원짜리 5개 구입하려면 6000원이 필요함
'''''
class Sales:
__item : object
# __item = '' # __item = None
__qty : object
__cost : object
@property
def item(self):
return self.__item
@property
def qty(self):
return self.__qty
@property
def cost(self):
return self.__cost
@item.setter
def item(self, value):
self.__item=value
@qty.setter
def qty(self, value):
self.__qty=value
@cost.setter
def cost(self, value):
self.__cost=value
def getPrice(self):
return self.qty * self.cost
def __str__(self):
return self.__item + ' ' + str(self.__cost) + \
'원짜리 ' + str(self.__qty) + '개 구입하려면 ' + \
str(self.getPrice()) + '원이 필요함 '
if __name__ == '__main__':
ss = Sales()
ss.item = 'apple'
ss.qty = 5
ss.cost = 1200
print(ss.__str__())
|
f65950e010174b002e752799df2ee1af481ed706 | previsualconsent/projecteuler | /p020.py | 157 | 3.734375 | 4 |
def factorial(n):
if(n == 1 or n == 0):
return 1
else:
return factorial(n - 1) * n
print sum( [ int(s) for s in str(factorial(100))])
|
53fc80c1928c0e66fa98504a0a6dffa3fed9dff8 | SIRAbae/-BIT-Class-Sangbae-Growth-Diary | /2.Advanced_Class/코드(Code)/python/연습코드/1118파이썬기본2.py | 1,086 | 3.6875 | 4 | """
len("_____")길이를 구한다.
변수.replace('바꿀이름','바꿀말')
변수.upper() ----소문자를 대문자로 치환
변수.lower() ----대문자를 소문자로 치환
"""
"""
a=10
b ='10'
print(type(a))
print(type(b))
print(a+int(b))
print(str(a)+b)
"""
"""
dic={'경상도':{'부산','대구','울산','공통'},
'전라도':{'광주','전주','공통'}}
for name,contents in dic.items():
if '광주' in contents:
print(name)
#광주가 있는 key값을 출력
for name,contents in dic.items():
if '대구' in contents:
print(name)
for name,contents in dic.items():
if '공통' in contents:
print(name)
"""
dic={'경상도':{'부산','대구','울산','공통'},
'전라도':{'광주','전주','공통'}}
for name,contents in dic.items():
if '공통' in contents and not('대구' in contents):
print(name)
#'공통'이들어가고 '대구'가 안들어가는 key 값
age=int(input('나이?'))
if age<8:
print('유아')
elif age>=8 and age<20:
print('학생')
else:
print('성인')
|
27fdb2641a19003c851a9a8989c9de0e19166346 | adiojha629/Ojha_ML_implementations | /Kmeans_ojha_implementation.py | 3,381 | 4.25 | 4 | # -*- coding: utf-8 -*-
"""
Created on Tue Jul 21 10:58:19 2020
Implementation of KMeans clustering with 3 clusters
@author: Aditya Ojha
"""
###Necessary Libraries
import matplotlib.pyplot as plt #for data presentation
from scipy.spatial import distance
import numpy as np
###Necessary Functions
#distance.euclidean gets us the distance between two points
#to make the function name shorter we'll use lambda
dist = lambda p1,p2: distance.euclidean(p1,p2)
#function points_average
#inputs: 'points' a list of tuples, each tuple a x,y coordinate
#output: returns a tuple x,y where x = avg(all x points); y = avg(all y points)
###
def points_average(points):
#we assume that this is a list of tuples
x_points = [point[0] for point in points]
y_points = [point[1] for point in points]
x = sum(x_points)/len(x_points)
y = sum(y_points)/len(y_points)
return (x,y)
#function: get distances
#inputs: data is a list of tuples, each tuple=data points. Cluster is tuple
#outputs: list of the distances between each point in data and cluster.
def get_distances(data,cluster) -> list:
distance_list = []
for point in data:
distance_list.append(dist(point,cluster))
return distance_list
#function get closest point
#inputs: data a list of tuples representing points, cluster is a tuple
#output: the point in data closest in distance to cluster
def get_closest_point(data,cluster) -> tuple:
return data[np.argmin(get_distances(data, cluster))]
#function get furthest point
#inputs: data a list of tuples representing points, cluster is a tuple
#output: the point(tuple) in data furthest in distance to cluster
def get_furthest_point(data,cluster) -> tuple:
return data[np.argmax(get_distances(data, cluster))]
###Start of Implementation:
#Define the data to be entered
dataset = [(0,0),(1,1),(2,2),(6,6),(7,7),(15,15),(16,16),(17,17),(18,18)]
clusters = [None]*3 #list of the three clusters
clusters[0] = dataset[0] #first cluster is the first point
clusters[1] = get_furthest_point(dataset[0:],clusters[0]) #2nd cluster is point furthest from 1st cluster
clusters[2] = get_furthest_point(dataset[1:], clusters[1])#etc(^)
old_groups = []#values set so that they purposely don't equal each other
new_groups = [1]
while(old_groups != new_groups):
old_groups = new_groups.copy() #use a copy because we don't want both vars to reference same data
classifi_dict = dict()
for cluster in clusters:
classifi_dict[cluster] = []
#now assign point to a cluster
for point in dataset:
cluster_for_this_point = get_closest_point(list(classifi_dict.keys()),point) #get the cluster that is closest to this point
classifi_dict[cluster_for_this_point].append(point)#append the point to that cluster's values in the dict
#keep track of which cluster got which points
new_groups = list(classifi_dict.values())
#points_groups is a list of lists; assume indexs x,y
#x = classification (0,1,2,etc)
#y = list of points in the classification specified by x
###Redefine the clusters based on the points in each group
for index,points_in_group in enumerate(new_groups):
clusters[index] = points_average(points_in_group)
print(clusters)
for value in new_groups:
x_points = [point[0] for point in value]
y_points = [point[1] for point in value]
plt.scatter(x_points,y_points) |
d62d7d36813e1cad3ea215dc12c568c4dabe5b3e | yennanliu/CS_basics | /leetcode_python/Hash_table/k-diff-pairs-in-an-array.py | 6,108 | 3.8125 | 4 | """
532. K-diff Pairs in an Array
Medium
Given an array of integers nums and an integer k, return the number of unique k-diff pairs in the array.
A k-diff pair is an integer pair (nums[i], nums[j]), where the following are true:
0 <= i < j < nums.length
|nums[i] - nums[j]| == k
Notice that |val| denotes the absolute value of val.
Example 1:
Input: nums = [3,1,4,1,5], k = 2
Output: 2
Explanation: There are two 2-diff pairs in the array, (1, 3) and (3, 5).
Although we have two 1s in the input, we should only return the number of unique pairs.
Example 2:
Input: nums = [1,2,3,4,5], k = 1
Output: 4
Explanation: There are four 1-diff pairs in the array, (1, 2), (2, 3), (3, 4) and (4, 5).
Example 3:
Input: nums = [1,3,1,5,4], k = 0
Output: 1
Explanation: There is one 0-diff pair in the array, (1, 1).
Example 4:
Input: nums = [1,2,4,4,3,3,0,9,2,3], k = 3
Output: 2
Example 5:
Input: nums = [-1,-2,-3], k = 1
Output: 2
Constraints:
1 <= nums.length <= 104
-107 <= nums[i] <= 107
0 <= k <= 107
"""
# V0
# IDEA : HASH TABLE
import collections
class Solution(object):
def findPairs(self, nums, k):
answer = 0
cnt = collections.Counter(nums)
# NOTE THIS : !!! we use set(nums) for reduced time complexity, and deal with k == 0 case separately
for num in set(nums):
"""
# [b - a] = k
# -> b - a = +k or -k
# -> b = k + a or b = -k + a
# -> however, 0 <= k <= 10^7, so ONLY b = k + a is possible
2 cases
-> case 1) k > 0 and num + k in cnt
-> case 2) k == 0 and cnt[num] > 1
"""
# case 1) k > 0 and num + k in cnt
if k > 0 and num + k in cnt: # | a - b | = k -> a - b = +k or -k, but here don't have to deal with "a - b = -k" case, since this sutuation will be covered when go through whole nums
answer += 1
# case 2) k == 0 and cnt[num] > 1
if k == 0 and cnt[num] > 1: # for cases k = 0 -> pair like (1,1) will work. (i.e. 1 + (-1))
answer += 1
return answer
# V0'
# IDEA : SORT + BRUTE FORCE + BREAK
class Solution(object):
def findPairs(self, nums, k):
# edge case
if not nums and k:
return 0
nums.sort()
res = 0
tmp = []
for i in range(len(nums)):
for j in range(i+1, len(nums)):
if abs(nums[j] - nums[i]) == k:
cur = [nums[i], nums[j]]
cur.sort()
if cur not in tmp:
res += 1
tmp.append(cur)
elif abs(nums[j] - nums[i]) > k:
break
return res
# V0''
# IDEA : SORT + BRUTE FORCE + BREAK
class Solution(object):
def findPairs(self, nums, k):
d = {}
res = []
# NOTE : we sort here
nums.sort()
for i in range(len(nums)-1):
for j in range(i+1, len(nums)):
if abs(nums[i] - nums[j]) == k:
tmp = [nums[i],nums[j]]
tmp.sort()
if tmp not in res:
res.append(tmp)
if abs(nums[j] - nums[i]) > k:
break
return len(res)
# V1
# https://blog.csdn.net/fuxuemingzhu/article/details/79255633
# IDEA : collections.Counter
# IDEA : FIND # OF PAIR THAT SUM-PAIR = K (i.e. for pair(a,b), -> a + b = k)
# -> a+ b = k
# -> a = k - b
import collections
class Solution(object):
def findPairs(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: int
"""
answer = 0
counter = collections.Counter(nums)
for num in set(nums):
if k > 0 and num + k in counter: # | a - b | = k -> a - b = +k or -k, but here don't have to deal with "a - b = -k" case, since this sutuation will be covered when go through whole nums
answer += 1
if k == 0 and counter[num] > 1: # for cases k = 0 -> pair like (1,1) will work. (i.e. 1 + (-1))
answer += 1
return answer
# V1'
# https://blog.csdn.net/fuxuemingzhu/article/details/79255633
# IDEA : collections.Counter
class Solution(object):
def findPairs(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: int
"""
res = 0
if k < 0: return 0
elif k == 0:
count = collections.Counter(nums)
for n, v in count.items():
if v >= 2:
res += 1
return res
else:
nums = set(nums)
for num in nums:
if num + k in nums:
res += 1
return res
# V1''
# https://www.jiuzhang.com/solution/k-diff-pairs-in-an-array/#tag-highlight-lang-python
class Solution:
"""
@param nums: an array of integers
@param k: an integer
@return: the number of unique k-diff pairs
"""
def findPairs(self, nums, k):
# Write your code here
nums.sort()
n, j, ans = len(nums), 0, 0
for i in range(n):
if i == j:
j += 1
while i + 1 < n and nums[i] == nums[i + 1]:
i += 1
while j + 1 < n and nums[j] == nums[j + 1]:
j += 1
while j < n and abs(nums[i] - nums[j]) < k:
j += 1
if j >= n:
break
if abs(nums[i] - nums[j]) == k:
ans, j = ans + 1, j + 1
return ans
# V2
# Time: O(n)
# Space: O(n)
class Solution(object):
def findPairs(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: int
"""
if k < 0: return 0
result, lookup = set(), set()
for num in nums:
if num-k in lookup:
result.add(num-k)
if num+k in lookup:
result.add(num)
lookup.add(num)
return len(result) |
aaad1467f6088d384bbd9182b03c6a24fbf6a575 | ShreyaaPawar/PasswordGenerator | /PasswordGenerator.py | 415 | 3.5625 | 4 | import string
import random
s1 = string.ascii_lowercase
s2 = string.ascii_uppercase
s3 = string.digits
s4 = string.punctuation
s = []
s.extend(s1)
s.extend(s2)
s.extend(s3)
s.extend(s4)
user_leninput = input("Enter the length of the password you want to generate: ")
if user_leninput.isdigit():
random.shuffle(s)
print("".join(s[:int(user_leninput)]))
else:
print("Wrong Input!!!!Try Again....")
|
efb4135c58ed900038ab13e9b46f8d7a019f912d | asavpatel92/random | /detour_distance.py | 2,420 | 4.03125 | 4 | from collections import namedtuple
from math import radians, cos, sin, asin, sqrt
def haversine_distance((lat1, lon1, lat2, lon2)):
"""
Calculate the great circle distance between two points
on the earth (specified in decimal degrees)
referenced from: http://stackoverflow.com/questions/4913349/haversine-formula-in-python-bearing-and-distance-between-two-gps-points
"""
# convert decimal degrees to radians
lon1, lat1, lon2, lat2 = map(radians, [lon1, lat1, lon2, lat2])
# haversine formula
dlon = lon2 - lon1
dlat = lat2 - lat1
a = sin(dlat/2)**2 + cos(lat1) * cos(lat2) * sin(dlon/2)**2
c = 2 * asin(sqrt(a))
# 3958.75 miles is the radius of the Earth
distance = 3958.75 * c
return distance
def consecutive_points(points):
"""
returns consecutive elements of a list as tuple
for example, if list has elements [A, B, C, D] it returns (A, B), (B, C), (C, D)
"""
i = 0
j = i + 1
while j < len(points):
yield points[i].lat, points[i].lon, points[j].lat, points[j].lon
i += 1
j += 1
def total_distance(points):
return reduce(lambda x, y: x + y, map(haversine_distance, [x for x in consecutive_points(points)]))
def shorter_detour(tourA, tourB):
# there are 2 possible cases
# (i) Driver A pickes up Driver B
d1 = total_distance((tourA.start, tourB.start, tourB.end, tourA.end ))
# (ii) Driver B picks up Driver A
d2 = total_distance((tourB.start, tourA.start, tourA.end, tourB.end ))
if d1 < d2:
print "Shorter Detour if Driver A picks up Driver B, total distance : %f compared to : %f and path is: %s%s%s%s" % (d1, d2, tourA.start.point, tourB.start.point, tourB.end.point, tourA.end.point)
else:
print "Shorter Detour if Driver B picks up Driver A, total distance : %f compared to : %f and path is: %s%s%s%s" % (d2, d1, tourB.start.point, tourA.start.point, tourA.end.point, tourB.end.point)
def main():
Point = namedtuple('Point', 'point lat lon')
pointA = Point("A", 37.776685, -122.394259) # caltrain station
pointB = Point("B", 37.760568, -122.412705) # Lyft office
pointC = Point("C", 37.766387, -122.398820) # 16th and Berry
pointD = Point("D", 37.757430, -122.412381) # 21st and Harrison
Tour = namedtuple('Tour', 'start end')
tourA = Tour(pointA, pointB)
tourB = Tour(pointC, pointD)
shorter_detour(tourA, tourB)
if __name__ == "__main__":
main()
|
31dd68535f8316107f2ec38249082af8c80a8a4a | allester/cis40 | /words_count.py | 898 | 3.78125 | 4 | """
Lab 7 - word_count.py - De Anza CIS D040 - Allester Ramayrat
"""
def wordCount(docWords):
dict = {}
for line in docWords:
line = line.strip()
for currChar in line:
if currChar not in dict:
dict[currChar] = 1
else:
dict[currChar] += 1
maxLength = 0
countList = []
for currChar in dict: #turns the dict values into list
countList.append(dict[currChar])
currLength = len(str(dict[currChar]))
if currLength > maxLength: #find maxLength
maxLength = currLength
countList.sort()
for count in countList: #prints the function w/ indent
for currChar in dict:
indent = maxLength - len(str(count))
if count == dict[currChar]:
print(currChar + " : " + " " * indent + str(count))
docWords = open('words.txt')
wordCount(docWords)
|
d08fbee03903a0e6de8ca887212afe2397abea84 | ntuong196/AI-for-Puzzle-Solving | /Week4-Pancake-puzzle/pancake_puzzle.py | 3,723 | 4.625 | 5 | """
Complete the function marked with "INSERT YOUR CODE HERE"
If you don't know where to start, have a good look at the
implementation of the sliding puzzle (file sliding_puzzle.py)
- Define an heuristic for this problem (see hint in lecture slide).
- Compare the performance A* and BFS on this problem.
Last modified 2019-03-16
by f.maire@qut.edu.au
"""
from W04_search import Problem, breadth_first_graph_search, astar_graph_search
import random, time
class PancakePuzzle(Problem):
'''
Pancake puzzle,
Stack of n pancakes is represented by a permutation P of range(n).
P[0] is the size of the pancake at the bottom
P[n-1] is the size of the pancake at the top
'''
default_size = 4
def __init__(self, initial=None, goal=None):
"INSERT YOUR CODE HERE"
def actions(self, state):
"""Return the actions that can be executed in the given
state.
"""
"INSERT YOUR CODE HERE"
def result(self, state, action):
"""Return the state that results from executing the given
action in the given state. The action must be one of
self.actions(state).
applying action a to state s results in a sequence
s[:a]+s[-1:a-1:-1]
"""
"INSERT YOUR CODE HERE"
def print_solution(self, goal_node):
"""
Shows solution represented by a specific goal node.
For example, goal node could be obtained by calling
goal_node = breadth_first_tree_search(problem)
"""
# path is list of nodes from initial state (root of the tree)
# to the goal_node
path = goal_node.path()
# print the solution
print ("Solution takes {0} steps from the initial state".format(len(path)-1))
print (path[0].state)
print ("to the goal state")
print (path[-1].state)
print ("\nBelow is the sequence of moves\n")
for node in path:
if node.action is not None:
print ("flip at {0}".format(node.action))
print (node.state)
def goal_test(self, state):
"""Return True if the state is a goal. The default method compares the
state to self.goal, as specified in the constructor. Override this
method if checking against a single self.goal is not enough."""
return state == self.goal
def path_cost(self, c, state1, action, state2):
"""Return the cost of a solution path that arrives at state2 from
state1 via action, assuming cost c to get up to state1. If the problem
is such that the path doesn't matter, this function will only look at
state2. If the path does matter, it will consider c and maybe state1
and action. The default method costs 1 for every step in the path."""
return c + 1
#______________________________________________________________________________
#
if __name__ == "__main__":
## pp = PancakePuzzle(initial=(0, 4, 1, 2, 6, 5, 3), goal=range(6,-1,-1))
## print "Initial state : ", pp.initial
## print "Goal state : ", pp.goal
pp = PancakePuzzle(initial=(3, 1, 4, 6, 0, 2, 5), goal=range(6,-1,-1))
t0 = time.time()
## sol_ts = breadth_first_tree_search(pp) # tree search version
sol_ts = breadth_first_graph_search(pp) # graph search version
t1 = time.time()
print ('BFS Solver took {:.6f} seconds'.format(t1-t0))
pp.print_solution(sol_ts)
print('- '*40)
pp = PancakePuzzle(initial=(3, 1, 4, 6, 0, 2, 5), goal=range(6,-1,-1))
t0 = time.time()
sol_ts = astar_graph_search(pp) # graph search version
t1 = time.time()
print ('A* Solver took {:.6f} seconds'.format(t1-t0))
pp.print_solution(sol_ts)
|
7eb417fdd1fe667fa3f452361b2ca1e71b8729cd | DhananjayAshok/Lending-Club-EDA-and-Interest-Rate-Prediction | /kaggle _notebook.py | 16,652 | 3.53125 | 4 | """
"""
# Should do earlier itself
def investigate(data)->None:
print(data.shape)
print(data.info())
print(data.describe())
def drop_nan_columns(data, ratio=1.0)->pd.DataFrame:
"""
From an initial look at the data it seems like some columns are entirely nan columns (e.g. id, there are 24 such columns)
The ratio parameter (0.0<=ratio<1.0) lets you drop columns which has 'ratio'% of nans. (i.e if ratio is 0.8 then all columns with 80% or more entries being nan get dropped)
Returns a new dataframe
"""
col_list = []
na_df = data.isna()
total_size = na_df.shape[0]
for col in na_df:
a = na_df[col].value_counts()
if False not in a.keys():
col_list.append(col)
elif True not in a.keys():
pass
else:
if a[True]/total_size >= ratio:
col_list.append(col)
print(f"{len(col_list)} columns dropped- {col_list}")
return data.drop(col_list, axis=1)
data = drop_nan_columns(data, ratio=0.5)
# Now we've taken out the really useless columns, let's check the other ones so that we get a sense of how many NaN entries the rest of our data has
def investigate_nan_columns(data)->None:
"""
Prints an analysis of the nans in the dataframe
Tells us that employment title and length have very few nans, title has barely any nans
Upon further looking at the data it seems for employment nans are all unemployed (there is no unemployed category otherwise), length nans is also unemployed
"""
col_dict = {}
na_df = data.isna()
total_size = na_df.shape[0]
for col in na_df:
a = na_df[col].value_counts()
if False not in a.keys():
col_dict[col] = 1.0
elif True not in a.keys():
pass
else:
col_dict[col] = a[True]/total_size
print(f"{col_dict}")
return
investigate_nan_columns(data)
# Tells us that employment title and length have very few nans, title has barely any nans
# Upon further looking at the data it seems for employment nans are likely all unemployed (there is no unemployed category otherwise), length nans we will use mode filling
def handle_nans(data)->None:
"""
Handle the nans induvidually per column
emp_title: make Nan -> Unemployed
emp_length: make Nan - > 10+ years this is both mode filling and value filing
title: make Nan -> Other
"""
data['emp_title'] = data['emp_title'].fillna("Unemployed")
data['title'] = data['title'].fillna('Other')
mode_cols = ['emp_length', 'annual_inc', 'mort_acc']
for col in mode_cols:
data[col] = data[col].fillna(data[col].mode()[0])
return
handle_nans(data)
# Now we're done with handling the NaN values we can check that the dataframe truly has no Nan values
any(data.isna().any())
# Now we can look at the data again and actually understand it
investigate(data)
# Looking at the datatypes it's easy to tell there are a lot of categorical columns (e.g. grade) but right now these are only being read as object or strings. We convert them
# We can also safely convert employment length to numbers so that the model can use it as a numerical column
# We also need to convert date to a datetime datatype to best use it
def handle_types(data, numericals, strings, categoricals):
def helper_emp_length(x):
if x == "10+ years": return 10
elif x == "2 years": return 2
elif x == "< 1 year": return 0
elif x == "3 years": return 3
elif x == "1 year": return 1
elif x == "4 years": return 4
elif x == "5 years": return 5
elif x == "6 years": return 6
elif x == "7 years": return 7
elif x == "8 years": return 8
elif x == "9 years": return 9
else:
return 10
data['emp_length'] = data['emp_length'].apply(helper_emp_length)
for category in categoricals:
try:
data[category] = data[category].astype('category')
except:
pass
data['issue_d'] = data['issue_d'].astype('datetime64')
handle_types(data, numericals, strings, categoricals)
# And that's it. We have finished an extremely basic cleaning of the dataset. We can now start Exploratory Data Analysis to find deeper patterns in the data.
# Now just copy paste each graph function and run it immediately
"""
Correlation Heatmap
Correlation Heatmaps are a great way to spot linear relations between numerical columns in your dataset.
The basic theory is that you use an inbuilt pandas function corr to calculate each variables correlation to every other variable
Plotting this resulting correlation matrix in a heatmap gives you a sense of which features are correlated to the target variables, hinting at the features you should select or are more important in the model you will make.
"""
"""
From this plot we can clearly see that there is a huge correlation (nearly one to one) with the loan_amnt (Which is the amount requested by the borrower), and the funded amounts (amount funded by investors). This suggests that we probably want to merge these columns as they add dimensionality but do not provide that much extra information
From looking at the variables related to interest rates the first observation is that some variables like mortgage account balance and (surprisingly) annual income seem to have nearly no correlation
In general the most correlated variable seems to be employment length, we could plot these two variables against each other to get a clearer sense of their relationship
Unfortunately overall it seems the numerical variables are not the most correlated, either there is a non-linear relationship in the data or our categorical features are where the bulk of our useful features will be
"""
"""
Distribution Plot
Distribution Plots are very similar to histograms and essentially show how data is distributed across its different values.
They are extremely useful in finding skews in the data. Most models perform best when the data they deal with is normally distributed (especially linear models). So if we find a skew we may want to apply a skew solution function the variable in order to make it resemble a normal distribution
"""
"""
The extended tail forward gives a clear sign of a positive skew in our interest rate. This means that there are much more lower values than there are high values.
Possible solutions we could apply include the square root and log functions
"""
"""
Boxplots
Boxplots are an extremely useful way to plot outliers, while also seeing how numerical data varies across different categories.
{Read up and insert what boxplots represent}
"""
"""
The insights we can take from each plot
(0,0) - This graph tells us nothing about the relation to interest rates, but gives us interesting insights on the economy from which the data was extracted, namely it is likely not a savings based economy. You can tell this by looking at how people who own their houses are not that much wealthier than those who have it on a mortgage. This implies that even when induviudals have enough income to perhaps save an eventually buy a house or a buy a lower grade house they could afford they are opting to take a loan and commit to this expenditure.
(0,1) - This graph tells us the intutive idea that cash loans on average are of a smaller sum than DirectPay loans, presumably for security reasons. The suprising observation is the lack of any outliers, implying that this lending institution is a relatively safe one which caps the loans it gives, meaning there isn't a single loan so high that it would count as an outlier.
(1,0) - This graph suggests that verification status does seem to have a relationship with interest rate. The average steadily increases the more verfified the borrower is.
(1,1) - This graph is interesting as it seems like the grade of the borrower is low if they either worked in a particular job for very little (less than 1 year or 1 year) or if they have worked the same job for very long (9, 10 years). This suggest some sort of aversion to inexperience, but also stagnation in one job, considering both to be factors that make a loan more risky.
"""
"""
LinePlots
Good for seeing trends in data between induvidual variables
"""
"""
It seems interest rate vs employment length mirrors the relationship between grade and enployment length witnessed in the boxplot above, presumably for the same reasons.
The interest rate for people who have worked less than a year seems low though, possibly this is because these are small buisness or enterprise loans that are valued at a lower interest rate so that the buisness itself has a greater chance of success and thus repaying the loan.
"""
"""
Scatter Plot
The most basic type of plot, but we will scatter averages because otherwise the graph will be too dense for us to actually learn anything
"""
"""
Clearly there is a massive relationship between subgrade and interest rate. This makes it the best feature we have seen so far, and understandably so because the interest rate is in most cases a function of the risk of a loan.
"""
"""
Etc.
The rest of the plots are various different plots which show relationships in the data
3D scatter
Violin Plot
Bubble plot
"""
# Exploratory Data Analysis done. Now we will prepare our data for the model
# First let us define a function to split data and return it to us. This is useful because we want to be very sure of what manipulations we are doing to test data, in order to ensure we aren't cheating
def load_split_data(number_of_rows=None, purpose=None, column='int_rate', test_size=0.2):
from sklearn.model_selection import train_test_split
data = load_data(number_of_rows=number_of_rows, purpose=purpose)
target = data[column]
data.drop(column, axis=1, inplace=True)
return train_test_split(data, target, test_size=test_size)
X_train, X_test, y_train, y_test = load_split_data(size, purpose="time_of_issue")
X_train = drop_nan_columns(X_train, ratio=0.5)
X_test = drop_nan_columns(X_test, ratio=0.5)
handle_nans(X_train)
handle_nans(X_test)
handle_types(X_train, numericals, strings, categoricals)
handle_types(X_test, numericals, strings, categoricals)
# For this notebook we will ignore the string variables, however there are ways to use them using other prepreocessing techniques if desired
X_train = X_train.drop(strings, axis=1)
X_test = X_test.drop(strings, axis=1)
timing.timer("Cleaned Data")
# First, let us fix the skew that we saw in the distribution plot using the square root transformation
def manage_skews(train_target, test_target):
"""
Applying Square Root in order
"""
return np.sqrt(train_target), np.sqrt(test_target)
y_train, y_test = manage_skews(y_train, y_test)
# Next, we should normalize all of our data, this once again simply makes most models more effective and speeds up convergence
def scale_numerical_data(X_train, X_test, numericals):
from sklearn.preprocessing import StandardScaler
sc = StandardScaler()
X_train[numericals] = sc.fit_transform(X_train[numericals])
X_test[numericals] = sc.transform(X_test[numericals])
return
scale_numerical_data(X_train, X_test, numericals)
timing.timer("Scaled Data")
"""
Finally we will encode all of our categorical variables so that models can process them, but before we do that, we need to realize something about the size of our dataset
i.e if you look at the columns such as employment title you can already see a whole bunch of different occupations
"""
data['emp_title'].value_counts()
"""
There are other columns, like purpose, that have this same issue. When there are so many different categories the model is likely to get extremely confused or is just unlikely to generalize well.
Additionally there is also a harm that once we fit an encoder onto our categorical columns, then there will be a completely new profession in the test set that the encoder hasn't seen before, this would throw an exception
To solve this problem we keep only the instances that make up the top 15 categories of that variable, and cast the rest to a standard value like "Other"
"""
def shrink_categoricals(X_train, X_test, categoricals, top=25):
"""
Mutatues categoricals to only keep the entries which are the top 25 of the daframe otherwise they become other
"""
for category in categoricals:
if category not in X_train.columns:
continue
tops = X_train[category].value_counts().index[:top]
def helper(x):
if x in tops:
return x
else:
return "Other"
X_train[category] = X_train[category].apply(helper)
X_test[category] = X_test[category].apply(helper)
shrink_categoricals(X_train, X_test, categoricals)
timing.timer("Shrunk Categories")
data['emp_title'].value_counts()
# Now we can encode and transform our categorical data safely
def encode_categorical_data(X_train, X_test, categoricals):
from sklearn.preprocessing import LabelEncoder
for category in categoricals:
if category not in X_train.columns:
continue
le = LabelEncoder()
X_train[category] = le.fit_transform(X_train[category])
X_test[category] = le.transform(X_test[category])
#X_test[category] = le.transform(X_test[category])
return
encode_categorical_data(X_train, X_test, categoricals)
timing.timer("Encoded Data")
"""
We are nearly done with our data processing. The final step is to run a dimensionality reduction algorithm.
Having many dimensions to data can make training models significantly slower and also sometimes less accurate as well.
We will use PCA, an algorithm which tries to project data into lower dimensions while preserving as much entropy as possible. Instead of stating how many dimensions the PCA algorithm should project down to, we will simply state what percentage of entropy we would like preserved, 95% is a good standard bar.
The reason we are doing the step last is because after the PCA it is virtually impossible to figure out what each column represents in terms of the original data. s
"""
def dimensionality_reduction(X_train, X_test):
from sklearn.decomposition import PCA
pca = PCA(n_components=0.95)
X_train = pca.fit_transform(X_train)
X_test = pca.transform(X_test)
return X_train, X_test
X_train, X_test = dimensionality_reduction(X_train, X_test)
X_train.shape()
"""
From over 20 columns to only 4! While it may seem like we ought to have lost a lot of data the 95% of entropy being saved ensures we have preserved most core patterns.
You could do the notebook without the above step to see how much slower the training of the models is without this step
"""
# We are finally onto the modelling stage. We will create 4 different models - Random Forest, Support Vector Machine, Linear Regression, KNearestNeighbors and fine-tune them using scikit-learn
Literally copy paste all of the models
# Now we find the best hyperparameters for each model
"""
From these models, while all of them have a decent mse loss the SVM clearly performs best, let us use an averaging ensemble technique to combine the models and see if it improves the loss
Unfortunately the ensemble doesn't perform any better than the SVM in this case.
Finally we will try to use a Boosting technique -Gradient Boosting,
Gradient Boosting has a simple theory a prelimnary model is trained on a dataset, and its residual errors are recorded. Another model is then trained to model these residual errors, the sum of the induvidual predictions is considered the prediction of the overall system.
Scikit-Learn has an inbuilt GradientBoostingRegressor, but this uses Decision trees as its fundamental unit. We would rather use the SVM that is performing so well induvidually, so we will have to manually define the class
Now we can train and test all of these models to compare them.
Unfortunately even Gradient Boosting could not reduce the error beyond the SVM.
Let us visualize our models accuracy now to get a sense of how close we are to the true interest rate.
Thank you for viewing this Kernel. The notebook is a work in progress and will be updated as per feedback and future ideas.
"""
Check
All docstrings
All plot legends |
f552ee2a3fb7cafd655dccbd585790793a3bd3be | 14021612946/python_all-hedengyong | /pythonProject2day3/day3.6.py | 566 | 3.875 | 4 | a = int(input("请输入长度:"))
b = int(input("请输入长度:"))
c = int(input("请输入长度:"))
if a > 0 and b > 0 and c > 0 and a + b > c and b + c > a and a + c > b :
if ( a * a + b * b == c * c ) or ( a * a + c * c == b * b ) or ( c * c + b * b == a * a ):
print("直角三角形")
elif ( a * a + b * b < c * c ) or (a * a + c * c < b * b) or ( c * c + b * b < a * a ) :
print("普通三角形")
elif ( a * a == b * b == c * c ) :
print("等边三角形")
else:
print("输入错误")
|
6dbcfbebaa5c46e0a7767ea7d1f8eab24cf9870c | Mazza-a/Git-Repo-LPHW | /ex10.py | 582 | 3.875 | 4 | # defines a variable that tabs a string using \t
tabby_cat = "\tI'm tabbed in."
# Defines a variable that splits a string to the next line after \n
persian_cat = "I'm split\non a line"
# Defines a variable that separates each word with \ using double backslashes \\
backslash_cat = "I'm \\ a \\ cat"
#defines a variable that makes a list using triple quotes and the \t that tabs the each new line
fat_cat = """
I'll do a list:
\t* Cat Food
\t* Fishies
\t* Catnip\n\t* Grass
"""
#prints the value of each variable
print tabby_cat
print persian_cat
print backslash_cat
print fat_cat
|
2ce09db01ff7767534ffbdf1883661ab704faf1e | kailu3/105-book | /_build/jupyter_execute/2-python-types/intro-types.py | 1,697 | 4.03125 | 4 | # Python Types
Every value in Python has a type. In this section I will introduce the most common, basic types that are built into Python. To check the type of a value, we can use the Python built-in `type()` function.
## Numbers
The first category of types I will go through in detail is Numbers. Integers, floating point numbers, and complex numbers fall under Python's number category. They are defined as `int`,
`float`, and `complex`. I personally have not used `complex` yet but have used `int` and `float` almost every day.
type(9642)
type(9642.0)
type(1+2j)
## Strings
Next we have strings. As you've seen in the previous section, a sequence of one or more characters enclosed within single quotes ‘, double quotes ", or even triple quotes ''' is considered as a String in Python. Any letter, number or symbol could be a part of the sting.
type('I like cats')
type("meow")
type('''meoooooow''')
type('9642')
## Booleans
Last but not least, we introduce booleans. A boolean is a data type that almost every programming language has. A Boolean in Python can have two values: `True` or `False`. These values are constants and can be used to assign or compare boolean values.
type(True)
type(False)
> Note that there are many other Python data types that you will encounter in our Pythonic journey! Don't be intimidated as there are many data types that even I haven't heard of. Besides `Numbers`, `Strings`, and `Booleans`, I will also going over container data types like `Lists`, `Tuples`, and `Dictionaries` that can contain `Booleans`, `Numbers`, and `Strings` soon.
```{toctree}
:hidden:
:titlesonly:
numbers
strings
booleans
type-casting
tuples-lists-dicts
```
|
b8edb210f7d18abf7f8cdbf975a7ac56435a0c37 | PapelRasgado/Uri-1 | /Uri/1014.py | 80 | 3.8125 | 4 | A = int(input())
B = float(input())
Total = A/B
print ("%.3f" %Total, "km/l")
|
a27c637c6796b52ee6e21894576a81bd325b5f5d | kellymakoc/cs50 | /lecture6/dna.py | 2,357 | 4.15625 | 4 | from csv import reader, DictReader
from sys import argv
if len(argv) < 3: # if arugement command line is less than 3
print("Usage: python dna.py data.csv sequence.txt \n") # print
exit() # exit program
with open(argv[2]) as dnafile: # open dna file
dnareader = reader(dnafile) # read the sequences from the dna file
for row in dnareader: # read every row in the sequences
dnalist = row; # make a list of the rows
dna = dnalist [0] # dna is assigned to index 0 in the array
sequences = {} # sequence is assigned to index 0 in the array
with open(argv[1]) as peoplefile: # open the sequences file from database in to a list
people = reader(peoplefile) # read the file
for row in people:
dnaSequences = row # dna sequence is the row in the file
dnaSequences.pop(0)
break
# for the sequence in the dictionary
for item in dnaSequences:
sequences[item] = 1
for key in sequences: # iterate the dna sequence to find repeated sequences
k = len(key)
mtemp = 0
temp = 0
for i in range (len(dna)): # after counted sequence it skip to the end to avoid multiply counting
while temp > 0:
temp -= 1
continue
if dna[i: i + k] == key: # assume a certain sequence is the key
while dna[i - k: i] == dna[i: i + k]: # if another sequence is the same as the "key" sequence
temp += 1 # add 1
i += k # add to k
if temp > mtemp: # if temp is greater than the max
mtemp = temp # max will be the value of temp
sequences[key] += mtemp # find the index value in the array as the max value
with open(argv[1], newline = '') as peoplefile: # open database of the people
people = DictReader(peoplefile) # people are the names in the dictionary
for person in people: # go thru all the people
match = 0
for dna in sequences: # and compare the sequences of the key and theirs
if sequences[dna] == int(person[dna]): # if the sequences match
match += 1 # add 1 to match
if match == len(sequences): # if the value of match is equal to the index order of sequences
print(person['name']) # print the name of the person
exit() # exit program
print("No match") # else print no match |
d61d5aa835e9a84b1ba4e430ed6d3329dcbeaf7e | SparshGautam/Primitive-Datatypes | /Integers/Floats/.py | 165 | 3.65625 | 4 | i = 89 #Integers are usually numbers here i is an integer
print(i)
#floats
f = 0.89 #Floats are numbers but decimal eg = 0.89,0.97....etc
print(f)
|
8620d7602ac01c3cc98cabf23948fdaea19727e4 | OurGitAccount846/pythontraining | /exampleprograms/check.py | 339 | 4.125 | 4 | #check a given key is in dictionary or not
def is_key_present(num):
d={1:10,2:20,3:30,4:40}
if num in d:
return 'key is present'
else:
return 'key is not present'
def main():
num=int(input("enter number"))
check=is_key_present(num)
print("checking {} is {}".format(num,check))
main()
|
0fc7d10eadf915768b2cfec987af736292036f77 | Tolyander/WebDev2021Spring | /pythonproblems/while/d.py | 170 | 3.65625 | 4 | n = int(input())
cnt = 1
if(n == cnt):
print ("YES")
exit()
while cnt * 2 <= n:
cnt *= 2
if(n == cnt):
print ("YES")
exit()
print ("NO") |
26b2468954116882140c7efa2c96f7e4a5c541e5 | Incuriosus/GeekBrains | /Dobrokhvalov_Sergei_dz_10/Ex.2.py | 1,588 | 3.71875 | 4 | class Clothes:
def __init__(self, name):
self.name = name
def consumption(self):
return NotImplementedError
class Coat(Clothes):
def __init__(self, name, size):
super().__init__(name)
self.v = float(size)
self._consumption = None
@property
def consumption(self):
self._consumption = self.v / 6.5 + 0.5
return self._consumption
class Costume(Clothes):
def __init__(self, name, height):
super().__init__(name)
self.h = float(height)
self._consumption = None
@property
def consumption(self):
self._consumption = self.h * 2 + 0.3
return self._consumption
class AllProducts:
def __init__(self):
self._products = []
def __iter__(self):
return (el for el in self._products)
def add(self, product):
self._products.append(product)
def remove(self, product):
if product in self._products:
self._products.remove(product)
else:
print('Данный продукт не добавлен')
@property
def consumption(self):
result = 0
for i in self._products:
result += i.consumption
return result
if __name__ == '__main__':
costume_1 = Costume('Tailcoat', 6.1)
print(costume_1.h, costume_1.name)
coat_1 = Coat('Cape Coat', 54)
print(coat_1.v, coat_1.name)
all_products = AllProducts()
all_products.add(costume_1)
all_products.add(coat_1)
print(all_products.consumption)
print(coat_1 in all_products)
|
22390bff12eb6ab22d6d617347030d10dedd173e | kielejocain/cryptopals-python | /cryptopals/cryptolib/utils.py | 933 | 4.03125 | 4 | def list_blocks(itr, n):
"""A generator that breaks an iterable into a list of blocks.
Keyword arguements:
itr -- the incoming iterable to be chopped
n -- the size of each block (except possibly the last)
"""
if n < 1:
raise ValueError("Blocks must be of size at least 1")
def blocks(itr, n):
for i in range(0, len(itr), n):
yield itr[i:i+n]
return blocks(itr, n)
def pkcs7_padding(bstr, n):
"""Adds padding per PKCS#7 to the bytestring.
Keyword arguments:
bstr -- the byte string to be padded
n -- the assumed block size
"""
if n < 2:
raise ValueError("Blocks must be of size at least 2")
blocks = list(list_blocks(bstr, n))
if len(blocks) > 0:
short = n - len(blocks[-1])
else:
short = n
if short == 0:
short = n
for _ in range(short):
bstr += bytes([short])
return bstr
|
b186f8de7974e7d414c34e33edee331c7bb7f6a7 | alvas-education-foundation/ISE_3rd_Year_Coding_challenge | /4AL17IS012_Danush_Kumar/PradeepSir_codingchallenge/PradeepSir_codingchallenge1/prg2.py | 294 | 4.15625 | 4 | '''Write a python program to find the duplicate values of an array of integer values
'''
import numpy as y
def unique(lst):
x=y.array(lst)
print(y.unique(x))
lst=[]
n=int(input("Number of elements"))
for i in range(0,n):
ele=int(input())
lst.append(ele)
unique(lst) |
942d450ad42ff349dc61b105f9488c11b0495af3 | zacmcdonnell/pokemontextgame | /main/pokemon.py | 2,255 | 3.65625 | 4 | """Defines the enemies in the game"""
import random, attacks
class WildPokemon:
"""A base class for all enemies"""
def __init__(self, name, hp, attack, speed, possibleAttacks=None):
"""Creates a new enemy
:param name: the name of the enemy
:param hp: the hit points of the enemy
"""
self.name = name
self.hp = hp
self.attack = attack
self.speed = speed # THIS DETERMINES WHO ATTACKS FIRST
self.possibleAttacks = possibleAttacks
def is_alive(self):
return self.hp > 0
def getHighestAttack(self):
for i in self.possibleAttacks:
attack = 0
if i.damage > attack:
attack = i
return attack
class Pikachu(WildPokemon):
def __init__(self):
super().__init__(
name="Pikachu",
hp=35,
attack=55,
speed=90,
possibleAttacks=[attacks.Growl(), attacks.ThunderShock()],
)
class Pidgey(WildPokemon):
def __init__(self):
super().__init__(
name="Pikachu",
hp=35,
attack=55,
speed=90,
possibleAttacks=[attacks.Growl(), attacks.ThunderShock()],
)
class Rattata(WildPokemon):
def __init__(self):
super().__init__(
name="Pikachu",
hp=35,
attack=55,
speed=90,
possibleAttacks=[attacks.Growl(), attacks.ThunderShock()],
)
class Spearow(WildPokemon):
def __init__(self):
super().__init__(
name="Pikachu",
hp=35,
attack=55,
speed=90,
possibleAttacks=[attacks.Growl(), attacks.ThunderShock()],
)
class Evee(WildPokemon):
def __init__(self):
super().__init__(
name="Eevee",
hp=55,
attack=55,
speed=55,
possibleAttacks=[attacks.Growl(), attacks.ThunderShock()],
)
class Metapod(WildPokemon):
def __init__(self):
super().__init__(
name="Metapod",
hp=50,
attack=20,
speed=30,
possibleAttacks=[attacks.Growl(), attacks.ThunderShock()],
)
|
8f3c45595c0d40db076664e29a2e405f0b7f6f12 | Yangfan2016/learn-python | /src/d005/index.py | 2,044 | 4.0625 | 4 | '''
水仙花数
水仙花数是指一个 3 位数,它的每个位上的数字的 3次幂之和等于它本身(例如:1^3 + 5^3+ 3^3 = 153)
'''
import math
def is_armstrong_num(num):
g = num % 10
s = (num-g) // 10 % 10
b = num // 100
return math.pow(g, 3)+math.pow(s, 3)+math.pow(b, 3) == num
# res = is_armstrong_num(153)
# print(res)
'''
完全数
它所有的真因子(即除了自身以外的约数)的和(即因子函数),恰好等于它本身
例如:第一个完全数是6,它有约数1、2、3、6,除去它本身6外,其余3个数相加,1+2+3=6。第二个完全数是28,它有约数1、2、4、7、14、28
'''
def is_perfect_num(num):
s = 0
for i in range(1, num):
if num % i == 0:
s += i
return s == num
# res=is_perfect_num(6)
# print(res)
# 斐波那契数列
cache = {}
def make_fibonacci(n):
if n < 3:
return 1
if cache.__contains__(n):
return cache[n]
cache[n-1] = make_fibonacci(n-1)
cache[n-2] = make_fibonacci(n-2)
return cache[n-1] + cache[n-2]
# res = make_fibonacci(6)
# print(res)
'''
百鸡百钱
我国古代数学家张丘建在《算经》一书中提出的数学问题:鸡翁一值钱五,鸡母一值钱三,鸡雏三值钱一。百钱买百鸡,问鸡翁、鸡母、鸡雏各几何?
'''
def hundred_chicken():
arr = []
# 5 * x + 3 * y + (100-x-y) / 3== 100
# 7 * x + 4 * y == 100
for i in range(0, 26):
z = (100 - 4 * i)
if z % 7 == 0:
x = int(z/7)
arr.append([x, i, 100-x-i])
return arr
res = hundred_chicken()
print(res)
'''
Craps赌博游戏
玩家摇两颗色子 如果第一次摇出7点或11点 玩家胜
如果摇出2点 3点 12点 庄家胜 其他情况游戏继续
玩家再次要色子 如果摇出7点 庄家胜
如果摇出第一次摇的点数 玩家胜
否则游戏继续 玩家继续摇色子
玩家进入游戏时有1000元的赌注 全部输光游戏结束
'''
# todo
|
ca5fd9b510b502371420f57edcc350f346a4550d | harmonytrevena/python_dictionaries | /dictionary.py | 716 | 3.953125 | 4 | meal = {
"Drink": "Wine",
"Appetizer": "Meat and Cheese Board",
"Entree": "Steak",
"Dessert": "Chocolate",
}
print(meal)
# if "Dessert" in meal:
# print("Harmony enjoyed dessert! She ate %s" % (meal["Dessert"]))
# else:
# print("Harmony, unfortunately, missed out on dessert!")
# if "Dessert" in meal:
# del meal["Dessert"]
# print(meal)
# 1. Phonebook Dictionary
phonebook_dict = {
"Alice": "703-493-1834",
"Bob": "857-384-1234",
"Elizabeth": "484-584-2923"
}
# print(phonebook_dict["Alice"])
phonebook_dict["Kareem"] = "938-489-1234"
print(phonebook_dict)
del phonebook_dict["Alice"]
print(phonebook_dict)
phonebook_dict["Bob"] = "938-489-1234"
print(phonebook_dict)
|
4fb862a1adda1daa3d3997e1d62a6088a81d2351 | p0leary/cs1301x | /5-2.py | 4,171 | 4.375 | 4 | #Write a function called string_search() that takes two
#parameters, a list of strings, and a string. This function
#should return a list of all the indices at which the
#string is found within the list.
# #
# #You may assume that you do not need to search inside the
# #items in the list; for examples:
# #
# # string_search(["bob", "burgers", "tina", "bob"], "bob")
# # -> [0,3]
# # string_search(["bob", "burgers", "tina", "bob"], "bae")
# # -> []
# # string_search(["bob", "bobby", "bob"])
# # -> [0, 2]
# #
# #Use a linear search algorithm to achieve this. Do not
# #use the list method index.
# #
# #Recall also that one benefit of Python's general leniency
# #with types is that algorithms written for integers easily
# #work for strings. In writing string_search(), make sure
# #it will work on integers as well -- we'll test it on
# #both.
# #Write your code here!
# def string_search(strList, str):
# locations = []
# for i in range(len(strList)):
# if strList[i] == str:
# locations.append(i)
# return locations
# #Feel free to add code below to test your function. You
# #can, for example, copy and print the test cases from
# #the instructions.
# print(string_search(['nope', 'nope', 'yeah', 'nope', 'yeah'], 'yeah'))
#Recall in Worked Example 5.2.5 that we showed you the code
#for two versions of binary_search: one using recursion, one
#using loops.
#
#In this problem, we want to implement a new version of
#binary_search, called binary_year_search. binary_year_search
#will take in two parameters: a list of instances of Date,
#and a year as an integer. It will return True if any date
#in the list occurred within that year, False if not.
#
#For example, imagine if listOfDates had three instances of
#date: one for January 1st 2016, one for January 1st 2017,
#and one for January 1st 2018. Then:
#
# binary_year_search(listOfDates, 2016) -> True
# binary_year_search(listOfDates, 2015) -> False
#
#You should not assume that the list is pre-sorted, but you
#should know that the sort() method works on lists of dates.
#
#Instances of the Date class have three attributes: year,
#month, and day. You can access them directly, you don't
#have to use getters (e.g. myDate.month will access the
#month of myDate).
#
#You may copy the code from Worked Example 5.2.5 and modify
#it instead of starting from scratch.
#
#Don't move this line:
from datetime import date
#Write your code here!
# V1 - Moving the index around a steady dateList. DONE and validated.
# def binary_year_search(dateList, searchYear):
# dateList.sort()
# maximum = len(dateList) - 1
# minimum = 0
# while maximum >= minimum:
# middle = minimum + ((maximum - minimum) // 2)
# # print('search year', searchYear)
# # print('min',minimum, dateList[minimum].year)
# # print('middle',middle, dateList[middle].year)
# # print('max',maximum, dateList[maximum].year, '\n')
# if dateList[middle].year == searchYear:
# return True
# elif dateList[middle].year > searchYear:
# maximum = middle - 1
# # repeat step 1
# elif dateList[middle].year < searchYear:
# # find new middle
# minimum = middle + 1
# # repeat step 1
# return False
#V2 - Modifying the dateList itself
def binary_year_search(dateList, searchYear):
dateList.sort()
while len(dateList) > 0:
middle = (len(dateList) - 1) // 2
# print('search year', searchYear)
# print(dateList)
if dateList[middle].year == searchYear:
return True
elif searchYear < dateList[middle].year:
dateList = dateList[:(middle - 1)]
elif searchYear > dateList[middle].year:
dateList = dateList[(middle + 1):]
return False
#The lines below will test your code. If it's working
#correctly, they will print True, then False, then True.
listOfDates = [date(2016, 11, 26), date(2014, 11, 29),
date(2008, 11, 29), date(2000, 11, 25),
date(1999, 11, 27), date(1998, 11, 28),
date(1990, 12, 1), date(1989, 12, 2),
date(1985, 11, 30)]
print(binary_year_search(listOfDates, 2016))
print(binary_year_search(listOfDates, 2007))
print(binary_year_search(listOfDates, 2008))
|
aa0dbc8189b6823a732fa090b41dd48253d1f112 | eisendaniel/misc_python | /CollatzConjecture.py | 1,489 | 3.5625 | 4 | from tkinter import Tk, Canvas
import numpy as np
PI = np.pi
GR = 1.61803398875
theta = {"left": PI / 15, "right": PI / 30}
mod = {"left": -1, "right": 1}
def collatz(start):
n = int(start)
seq = np.array([n])
while n > 1:
n = 3 * n + 1 if n % 2 else n / 2
seq = np.append(seq, int(n))
return seq[::-1]
def collatz_parity(start):
n = int(start)
seq = np.array([])
while n > 1:
if n % 2:
n = 3 * n + 1
seq = np.append(seq, "left")
else:
n /= 2
seq = np.append(seq, "right")
return seq[::-1]
class Collatz:
def __init__(self, master):
self.master = master
master.title("Collatz Conjecture")
width = 512
height = width * GR
border = (width - width / GR) / 2
origin = {"x": width / 2, "y": height - border}
canvas = Canvas(master, width=width, height=height)
canvas.pack()
segment_len = 3
parity = collatz_parity(871)
x = origin["x"]
y = origin["y"]
for p in parity:
y_step = (segment_len * np.sin(theta[p]))
x_step = mod[p] * (segment_len * np.cos(theta[p]))
canvas.create_line(x, y, x - x_step, y - y_step)
x -= x_step
y -= y_step
# canvas.create_line(origin["x"], origin["y"], 0, 0)
root = Tk()
window = Collatz(root)
root.mainloop()
|
c83c147134c5c33460ed3a7fe968f7f4af9155c2 | garandria/python-micro-benchmark | /data_structures/bench_set.py | 1,081 | 3.53125 | 4 | import random
REPET = 100000
def insertion(l):
print("++--endwarmup")
for _ in range(REPET):
s = set()
for e in l:
s.add(e)
def comp(l):
print("++--endwarmup")
for _ in range(REPET):
{e for e in l}
def iteration(s):
print("++--endwarmup")
for _ in range(REPET):
for e in s:
e
def random_in(s, n):
ml = list(s)
length = len(ml) - 1
r = [ml[random.randint(0, length)] for _ in range(n)]
print("++--endwarmup")
for _ in range(REPET):
for a in r:
a in s
def not_in(s, n):
print("++--endwarmup")
for _ in range(REPET):
for _ in range(n):
None in s
def to_set(l):
print("++--endwarmup")
for _ in range(REPET):
set(l)
def random_removal(s, n):
l = list(s)
length = len(l) - 1
r = [l[random.randint(0, length)] for _ in range(n)]
tmp = [s.copy() for _ in range(REPET)]
print("++--endwarmup")
for i in range(REPET):
ms = tmp[i]
for e in r:
ms.remove(e)
|
7fc0d469c40677d6e28c25ff36bdcf2f88d468d1 | jz1007/project-euler | /p004.py | 314 | 3.578125 | 4 | x=999
y=99
palindrome = []
for n in range(x,y,-1):
for i in range(x,y,-1):
product = n*i
product_str = str(product)
if product_str[0]==product_str[-1] and product_str[1]==product_str[-2] and product_str[2]==product_str[-3]:
palindrome.append(product)
print(max(palindrome)) |
3629725a2df9afe810098e3a40faffe6df38f00c | AdamZhouSE/pythonHomework | /Code/CodeRecords/2097/61406/280825.py | 530 | 3.640625 | 4 | numerator = int(input())
denominator = int(input())
number = str(numerator//denominator)
quotient = ""
remainder = [numerator%denominator]
while True:
x,y=divmod(remainder[-1]*10,denominator)
quotient = quotient+str(x)
remainder.append(y)
i = remainder.index(remainder[-1])
if i!= len(remainder)-1:
quotient = quotient[:i]+"("+quotient[i:]+")"
break
result = number+"."+quotient
if result.endswith("(0)"):
result = result[:-3]
if result.endswith("."):
result = result[:-1]
print(result) |
4a542ab718893ad8d367535a26cdede6c8248b54 | bossk-ig88/SecureSet-stuff | /Python/Labs/SSF/ssf100-lab8b_02try.py | 1,053 | 4.4375 | 4 | # # SSF100 Python Lab 8a
# # Base Lab
# Base10 to Base8
#!/usr/bin/python3
import math
# user number output to "string".
number=""
# User input:
# when user # is not a numeric.
# Will run/execute loop (ask user) until defined condition is met.
while(not(number.isnumeric())):
number = input("What is the decimal to convert? ")
# converts user number from "string" to an "integer".
tempnumb = int(number)
# "binary" # outputs to a "string"
octal_output = ""
# when converted user "integer" is > 0:
while(tempnumb > 0):
print("CHECK 1 = start of While loop.") # PRINT CHECK
# Decimal to Base8 conversion:
# user "integer" modulused by 2 and
# result is converted to "string" and bin_output is added to result.
octal_output = str(tempnumb % 8) + octal_output
print("CHECK 2 = start conversion. " + str(octal_output))
# user integer / 2 and converted to binary
tempnumb = int(tempnumb / 8)
# PRINT check
print("CHECK 3 = final conversion. " + str(tempnumb))
print (octal_output)
print("End of Line...")
|
bb809950f3df2373549e1f4d8a28aba43b643fad | idjelaili/Spark-Project | /Spark DataFrame/GroupBy_and_Aggregate_Functions.py | 1,986 | 3.65625 | 4 |
# coding: utf-8
# # GroupBy and Aggregate Functions
# In[1]:
from pyspark.sql import SparkSession
# In[2]:
spark = SparkSession.builder.appName("groupbyagg").getOrCreate()
# Read in the customer sales data
# In[3]:
df = spark.read.csv('sales_info.csv',inferSchema=True,header=True)
# In[4]:
df.printSchema()
# In[8]:
df.show()
# Let's group together by company!
# In[9]:
df.groupBy("Company")
# This returns a GroupedData object, off of which you can all various methods
# In[10]:
# Mean
df.groupBy("Company").mean().show()
# In[11]:
# Count
df.groupBy("Company").count().show()
# In[12]:
# Max
df.groupBy("Company").max().show()
# In[13]:
# Min
df.groupBy("Company").min().show()
# In[15]:
# Sum
df.groupBy("Company").sum().show()
# In[18]:
# Max sales across everything
df.agg({'Sales':'max'}).show()
# In[22]:
# Could have done this on the group by object as well:
# In[23]:
grouped = df.groupBy("Company")
# In[25]:
grouped.agg({"Sales":'max'}).show()
# ## Functions
# In[36]:
from pyspark.sql.functions import countDistinct, avg,stddev
# In[29]:
df.select(countDistinct("Sales")).show()
# Often you will want to change the name, use the .alias() method for this:
# In[31]:
df.select(countDistinct("Sales").alias("Distinct Sales")).show()
# In[35]:
df.select(avg('Sales')).show()
# In[38]:
df.select(stddev("Sales")).show()
# That is a lot of precision for digits! Let's use the format_number to fix that!
# In[39]:
from pyspark.sql.functions import format_number
# In[40]:
sales_std = df.select(stddev("Sales").alias('std'))
# In[41]:
sales_std.show()
# In[42]:
# format_number("col_name",decimal places)
sales_std.select(format_number('std',2)).show()
# ## Order By
#
# You can easily sort with the orderBy method:
# In[43]:
# OrderBy
# Ascending
df.orderBy("Sales").show()
# In[47]:
# Descending call off the column itself.
df.orderBy(df["Sales"].desc()).show()
|
0d90bd4f09f8969d3e03ce39f1e37f303dcdb115 | berchev/python_learning | /ch_04/strings.py | 456 | 3.71875 | 4 | #!/usr/bin/env python
print('Four score and ' + str(7) + ' years ago')
print('AT' * 5)
print(4 * '-')
secuence = 'kjjsjnnskfnsjknfjksnkcm'
print(len(secuence))
new_secuence = secuence + 'djksjdsjk'
print(new_secuence)
print(new_secuence * 2)
print("that's better")
print('She said, "That' + "'" + 's hard to read."')
print(len('\''))
print(len('it\'s'))
print('one\ttwo\nthree\tfour')
radius = 5
print("Diameter of the circle = ", radius * 2, "cm") |
5bc6d472f0db5fc3efaedc49b2fd02f54dc1385c | OmarMedhat22/Equation-Grapher | /equation.py | 1,304 | 3.875 | 4 | from tkinter import *
import numpy as np
import matplotlib.pyplot as plt
LARGE_FONT= ("Verdana", 12)
root = Tk()
label = Label(root,text = 'Enter your equation here ')
label.pack()
e = Entry(root)
e.pack()
label = Label(root,text = 'Minimum Number')
label.pack()
Minimum = Entry(root)
Minimum.pack()
label = Label(root,text = 'Maximum Number')
label.pack()
Maxiumum = Entry(root)
Maxiumum.pack()
def click():
equation = e.get()
try:
x = np.linspace(float(Minimum.get()), float(Maxiumum.get()), 100)
key = True
except:
key = False
error = 'Wrong input ranges in Maxiumum or Minimum parameters'
label = Label(root,text = error)
label.pack()
if key :
try:
y = eval(equation)
key_2=True
except:
error = 'Wrong input in equation parameters enter it again '
key_2=False
label = Label(root,text = error)
label.pack()
if key_2:
fig = plt.figure(figsize = (10, 5))
plt.plot(x, y)
plt.show()
button_1 = Button(root,text="Ok",command=click)
button_1.pack()
root.mainloop()
|
bc33545d4c3b72a7dead100b5810bfe8cb7cebee | marcin-jamroz/python4beginners | /w3/Person.py | 312 | 3.75 | 4 | class Person():
def __init__(self, name, surname):
self.name = name
self.surname = surname
def formalize(self):
return "Imię: {}, Nazwisko: {}".format(self.name, self.surname)
janek = Person("Jan", "Kos")
print(janek.__dict__)
print(janek.formalize())
for(int i = 0; i < 01) |
9991549787d60d06f1d0fed6e4d778f64b7bf678 | yitianljt/Python | /src/vars.py | 649 | 3.875 | 4 | #!/usr/bin/python
#encoding:utf-8
'''
Created on 2014年10月28日
@author: jintao
'''
import threading ,time
a=50
b=50
c=50
d=50
def printvars():
print "a=", a
print "b=", b
print "c=", c
print "d=", d
def threadcode():
global a,b,c,d
a+=50
b= b+50
c=100
d= "hello"
print "[ChildThread] values of variables in child thread"
printvars()
print "[MainThread] values of variables before child thread:"
printvars()
t = threading.Thread(target=threadcode,name = "ChildThread")
t.setDaemon(True)
t.start()
t.join()
print "[MainThread] values of variables after child thread:"
printvars()
|
ad239b3cc4cada1e443f4afa973403f3346eaac3 | Doberman0/bpdts-test-app | /helper_functions.py | 991 | 3.609375 | 4 | #!flask/bin/python
import requests # To get users from API provided
import json
from math import radians, cos, sin, asin, sqrt
from typing import List
def getUsers() -> List[dict]:
'''
This function returns all the users from the API given
Format is [{person1}, {person2}, ...]
'''
url = 'https://bpdts-test-app.herokuapp.com/users'
response_get_request = requests.get(url)
return json.loads(response_get_request.content)
def haversine(lat1:float, lon1:float, lat2:float, lon2:float) -> float:
'''
Returns the distance between point A (lat1, lon1) and point B (lat2, lon2)
As per: https://stackoverflow.com/questions/4913349/haversine-formula-in-python-bearing-and-distance-between-two-gps-points
'''
R = 3959.87433 # This is in miles. For Earth radius in kilometers use 6372.8 km
dLat = radians(lat2 - lat1)
dLon = radians(lon2 - lon1)
lat1 = radians(lat1)
lat2 = radians(lat2)
a = sin(dLat/2)**2 + cos(lat1)*cos(lat2)*sin(dLon/2)**2
c = 2*asin(sqrt(a))
return R * c
|
fe593d55bb81535e4e6e12c4529718691da415c4 | jongharyu/cca | /utils.py | 1,121 | 3.5625 | 4 | import numpy as np
def construct_gram_matrix(X):
"""
construct a gram matrix
Parameters
----------
X: data matrix; (p, n)
Returns
-------
G: gram matrix; (n, n)
(G)_{ij} = \| X_i - X_j \|^2
"""
norms = ((X.T) ** 2 @ np.ones(X.shape[0]))[:, np.newaxis] # squared norms
allone = np.ones((X.shape[1], 1))
G = allone @ norms.T + norms @ allone.T - 2 * X.T @ X
return G
import math
# Reference: https://conx.readthedocs.io/en/latest/Two-Spirals.html
def spiral_point(i, spiral_num):
"""
Create the data for a spiral.
Arguments:
i runs from 0 to 96
spiral_num is 1 or -1
"""
φ = i / (10 * 16) * math.pi
r = 6.5 * ((10 * 104 - i) / (10 * 104)) + 2 * np.random.uniform()
x0 = (r * math.cos(φ) * spiral_num) / 13 + 0.5
x1 = (r * math.sin(φ) * spiral_num) / 13 + 0.5
return (x0, x1), φ
def spiral_2d(spiral_num):
xs = []
cs = []
for i in range(10 * 97): # 10 * 97
x, c = spiral_point(i, spiral_num)
xs.append(x)
cs.append(c)
xs = np.vstack(xs).T
return xs, cs |
730b387783d2ed51179400d1514cee90245af12d | Art-m-D/word_searcher | /src/main.py | 3,256 | 3.84375 | 4 | import argparse
from typing import List, Tuple
from texttable import Texttable
from all_direction_lib import all_direction_words
from letters_grid import LettersGrid
from words_list import WordsList
def valid_words_search(height: int = 15, width: int = 15, words_file: str = None, predefined_grid: List[str] = None) -> \
Tuple[list, set]:
"""
implement main search logic
Args:
height (int): height of the WordSearch board
width (int): width of the WordSearch board
words_file (str): Path to file with words collection, default: words.txt from projects resources
predefined_grid (list[str]): used if already have predefined WordSearch board
Returns:
word_search_board(set[str]): WordSearch board
result_word_list(list[str]): List of all valid words
"""
words_dict = WordsList(words_file)
letters_grid = LettersGrid(height, width, predefined_grid)
result = set()
for letter in words_dict.dictionary:
# checking, whatever we have word's first letter on WordSearch board
if letter in letters_grid.coordinates_map:
# get list of current letter coordinates
start_coordinates = letters_grid.coordinates_map[letter]
for start_coordinate in start_coordinates:
h, w = start_coordinate
concatenated_string = ''
# construct concatenated string of all possible strings in all possible directions from current letter \
# on WordSearch board, "_" is delimiter
for func in all_direction_words:
concatenated_string += '_'
concatenated_string += func(letters_grid.grid, h, w, height, width)
for word in words_dict.dictionary[letter]:
if '_' + word in concatenated_string:
result.add(word)
return letters_grid.grid, result
if __name__ == '__main__':
parser = argparse.ArgumentParser(
description='Generate WordSearch board and find all valid words from vocabulary words.txt')
parser.add_argument('--height', dest='height', action='store', default=15, type=int,
help='height of the WordSearch board, greater zero')
parser.add_argument('--width', dest='width', action='store', default=15, type=int,
help='width of the WordSearch board, greater zero')
parser.add_argument('--words_file', dest='words_file', action='store', default=None, type=str,
help='file with words collection for WordSearch game')
args = parser.parse_args()
if args.height == 1 and args.width == 1:
print('WordSearch board has only one letter. There is no words there')
exit(0)
if args.height < 1 or args.width < 1:
print("It's not WordSearch board")
exit(0)
word_search_board, result_word_list = valid_words_search(args.height, args.width, args.words_file)
# used Texttable for board pretty output
table = Texttable()
table.set_chars([' ', ' ', ' ', ' '])
[table.add_row(i.upper()) for i in word_search_board]
print(table.draw())
print('List of all founded words: '+', '.join(result_word_list))
|
ae057404aa540df9c2413f427903a39b54ea8dde | juliafealves/tst-lp1 | /unidade-4/calcula-dv/calcula-dv.py | 555 | 3.625 | 4 | # coding: utf-8
# Laboratório de Programação 1 - 2017.2 UFCG
# Aluna: Júlia Fernandes Alves (117211383)
# Atividade: Calcula DV - Unidade 4
numero_banco = raw_input()
posicao_par = 0
posicao_impar = 0
for indice in range(len(numero_banco)):
numero = int(numero_banco[indice])
if indice % 2 == 0:
posicao_par += numero
else:
posicao_impar += numero
digito_verificador = (posicao_par * posicao_impar) % 11
if digito_verificador == 10:
numero_banco += "-X"
else:
numero_banco += "-" + str(digito_verificador)
print numero_banco |
224ee3c84e1a0dc7c3f6f5cebb37d2692d2e0979 | artyomudin/task3 | /lesson30/my_func.py | 508 | 3.734375 | 4 | from builtins import *
def caesar_alg(data, key=5):
alphabet = 'abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz'
# data = input('input a phrase here: ')
# key = int(input('input a key here: '))
val_low = data.lower()
vald = ''
for letter in val_low:
position = (alphabet.find(letter))
new_position = position + key
if letter in alphabet:
vald = vald + alphabet[new_position]
else:
vald = vald + letter
print(vald)
|
52e5c05efea8d4b39a24c1e9992abfc7ec551515 | anuunnikrishnan/Python | /PYTHON 1/DbconnectPython/exception handling.py | 437 | 3.796875 | 4 | a=int(input("enter value for num1"))
b=int(input("enter value for num2"))
try:
res=a/b
print(res)
except Exception as e:
print(e.args)
# to print exception message num1=10,num2=0
# finally method
# try:
# print("connection established")
# print("transaction process")
# print("executing querry")
# print("db close")
# except Exception as e:
# print("exception occured")
# finally:
# print("db.close")
|
6a6310583ca1f94931c683f35c1cfd1201519056 | alvasenj/GIW | /practica1/ejecicio1_3.py | 1,368 | 3.75 | 4 |
def numero_apariciones(lectura, outfile):
lineas = ""
for linea in lectura.readlines():#Bucle para leer el archivo
lineas += linea
lineas = lineas.replace("\n", " ")#Sustituimos los saltos de linea por espacios
lineas = lineas.split(" ")#Separamos las palabras por espacios
lista = []
for i in lineas:#Creamos una lista para añadir las palabras que contiene el archivo
if i not in lista:
lista.append(i)
for i in lista:#Recorremos la lista
contador = 0
for j in lineas: #Recorremos el archivo buscando las palabras de la lista
if i == j and i != " ":
contador += 1;
if i != " ":
#print("La palabra '" + i + "' aparece", contador, "veces")
outfile.write("La palabra: " +str(i) + " aparece " + str(contador) + " veces\n")#Escribimos en el archivo
nombref = raw_input('Introduzca el noimbre del fichero: ')
try:
lectura = open(nombref, 'r');
outfile = open('texto.txt', 'w') # Indicamos el valor 'w' para que cada vez que se ejecute sobre escriba lo anterior.
numero_apariciones(lectura, outfile);
lectura.close()#cerramos el archivo de lectura
outfile.close()#cerramos el archivo de escritura
except IOError:
print "Error de entrada/salida."
exit() |
a2d26fbc4ad1d9a4c747d1ad553809440653af26 | green-fox-academy/judashgriff | /Week 3/Day 3/envelope_star.py | 828 | 3.75 | 4 | from tkinter import *
root = Tk()
canvas = Canvas(root, width='300', height='300')
canvas.pack()
# reproduce this:
# [https://github.com/greenfox-academy/teaching-materials/blob/master/workshop/drawing/envelope-star/r2.png]
def make_envelope_star():
for each in range(16):
canvas.create_line(0 + (each - 1) * 10, 150, 150, 140 - (each) * 10, fill='green')
for each in range(16):
canvas.create_line(300 - (each - 1) * 10, 150, 150 , 140 - (each) * 10, fill='green')
for each in range(16):
canvas.create_line(0 + (each - 1) * 10, 150, 150, 160 + (each) * 10, fill='green')
for each in range(16):
canvas.create_line(300 - (each - 1) * 10, 150, 150, 160 + (each) * 10, fill='green')
canvas.create_line(150, 0, 150, 300, fill='green')
make_envelope_star()
root.mainloop() |
c9b421ea8475a32fbd4b5fbcaa94506573bd899b | kgager/recipes | /recipe.py | 692 | 3.75 | 4 | ingredients = []
enter_more = raw_input("Do you have any specific ingredients to enter? [y|n]: ").lower()
while enter_more == "y":
ingredients.append(raw_input("What is the ingredient? One word only please: ").lower())
enter_more = raw_input("Do you have any more ingredients to enter? [y|n]: ").lower()
recipe_type = raw_input("What kind of recipe do you want to find (no input for anything)? ")
import requests
r = requests.get("http://www.recipepuppy.com/api/?i={}&q={}".format(
','.join(ingredients),
recipe_type))
recipes = r.json()["results"]
print("Your results:")
for i in range(len(recipes)):
recipe = recipes[i]
print("%s: %s" % (i, recipe["title"]))
|
909aeb0359313b226ce49e01deffc06fe8122862 | tsurubee/study_books | /unix_processes/fork.py | 437 | 3.609375 | 4 | #fork(2)システムコールによりプロセスが生成されることを確認する
#if句が親プロセスによって実行され、else句が子プロセスによって実行されていることがわかる。
import os
print("parent process pid: {0}".format(os.getpid()))
if os.fork():
print("Here in the if block. pid: {0}".format(os.getpid()))
else:
print("Here in the else block. pid: {0}".format(os.getpid()))
|
36a9db2856cfdee2be67afe32a820466a65f7720 | AbinDass/Assignment2 | /2q15.py | 150 | 3.75 | 4 | l=[1,2,3,4,5,6,7]
print(["element{0}".format(i) for i in l])
pass
l=[1,2,3,4,5,6,7]
str="element"
str+="{0}"
l=[str.format(i) for i in l]
print(l) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.