blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
399d5d0aafde77a01cb98e4d0e5b4284eabb2db2 | simbaTmotsi/eye-vision | /ziso/save/save.py | 634 | 3.515625 | 4 | def save(filename, file):
"""
------------------------
module for saving images
------------------------
"""
def save(filename, file):
try:
saved_file = cv2.imwrite(str(filename),file)
except:
print ("Please check the file path/name, there seems to be an error")
"""
error checking
"""
# in the event of an invalid file path this will be executed
try:
assert (saved_file) == None
print ("Please check the file path/name, there seems to be an error saving the image")
except Exception as errors:
pass
# returning the variable for re-use
return saved_file |
912d357085500978b63cc66e5cae14d650f1a726 | dharm6619/CodeLibraries | /Python Foundations/variables.py | 236 | 4.03125 | 4 | # Declaration of a variable
f=0
print(f)
f="abc"
print(f)
# print("abc " * 2)
# print("abc " + str(123))
def someFunction():
global f
f = "def"
print(f)
someFunction()
print(f)
del f
print(f)
|
30233e24109e96da7db0217b6f9d48f10c49fb58 | redforks/spork-compiler | /clientlib/sftest/string.py | 7,871 | 3.734375 | 4 | # -*- coding: utf-8 -*-
from unittest import TestCase
class StringTests(TestCase):
def test_concat(self):
self.assertEqual('a', 'a' + '')
self.assertEqual('汉bc', '汉' + 'bc')
self.assertEqual(u'汉bc', u'汉' + u'bc')
def test_str_constructor(self):
self.assertEqual('', str(''))
self.assertEqual('2', str(2))
self.assertEqual('2.3', str(2.3))
def test_multiply(self):
self.assertEqual(' ', ' ' * 2)
self.assertEqual('abcabcabc', 'abc' * 3)
s = 'ab'
s *= 3
self.assertEqual('ababab', s)
def test_mod(self):
self.assertEqual('', '%s' % '')
self.assertEqual('abc', '%s' % 'abc')
self.assertEqual('1 + 2', '%d + %d' % (1, 2))
s = '%s'
s %= 4
self.assertEqual('4', s)
def test_in(self):
self.assertTrue('a' in 'abc')
self.assertTrue('ab' in 'abc')
self.assertFalse('abc' in 'ab')
self.assertFalse('a' not in 'abc')
self.assertFalse('ab' not in 'abc')
self.assertTrue('abc' not in 'ab')
def test_subscription(self):
self.assertEqual('b', 'abc'[1])
self.assertEqual('c', 'abc'[-1])
self.assertEqual('bc', 'abc'[1:])
self.assertEqual('b', 'ab'[1:])
s = '+1'
self.assertEqual(s, s[0] + s[1:])
self.assertEqual(s, s[0:])
self.assertEqual('1', '-1'[1:])
self.assertEqual('', '-1'[:0])
self.assertEqual('12', '[12]'[1:-1])
self.assertEqual('ac', 'abc'[::2])
self.assertEqual('a', 'abc'[::3])
def test_len(self):
self.assertEqual(0, len(''))
self.assertEqual(1, len('a'))
self.assertEqual(3, len(u'a汉子'))
def test_min_max(self):
self.assertEqual('a', min('abc'))
self.assertEqual('c', max('abc'))
def test_startswith(self):
self.assertTrue(''.startswith(''))
self.assertTrue('abc'.startswith(''))
self.assertTrue('abc'.startswith('a'))
self.assertTrue(u'汉子'.startswith(u'汉'))
self.assertFalse(''.startswith('a'))
def test_endswith(self):
self.assertTrue(''.endswith(''))
self.assertTrue('a'.endswith(''))
self.assertTrue('abc'.endswith('c'))
self.assertTrue(u'汉子'.endswith(u'子'))
self.assertFalse(''.endswith('a'))
def test_capitalize(self):
self.assertEqual('What a lovely day.',
'what a lovely day.'.capitalize())
self.assertEqual('Aaa', 'AAA'.capitalize())
def test_center(self):
self.assertEqual('a', 'a'.center(1), '1');
self.assertEqual(' a ', 'a'.center(3), '3');
self.assertEqual(u' 汉 ', u'汉'.center(3));
def test_count(self):
e = getattr(self, 'assertEqual')
e(0, 'abc'.count('d'))
e(1, 'abc'.count('a'))
e(2, 'abcab'.count('ab'))
def test_index(self):
self.assertEqual(0, 'a'.index('a'))
self.assertEqual(2, 'bca'.index('a'))
self.assertError(lambda: 'a'.index('b'), ValueError)
self.assertEqual(3, '/ab/c'.index('/', 2))
self.assertEqual(3, '/ab/c'.index('/', 3))
def test_isalnum(self):
self.assertTrue('1234567890abcdefghijklmnopqrstuvwxyz'.isalnum())
self.assertTrue('ABCDEFGHIJKLMNOPQRSTUVWXYZ'.isalnum())
self.assertFalse(''.isalnum())
self.assertFalse('334@3'.isalnum())
def test_isalpha(self):
self.assertFalse(''.isalpha())
self.assertFalse('abc1233dd'.isalpha())
self.assertTrue('abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQ'.isalpha())
def test_isdigit(self):
self.assertTrue('1234567890'.isdigit())
self.assertFalse('1234567890a'.isdigit())
self.assertFalse(''.isdigit())
def test_islower(self):
self.assertFalse(''.islower())
self.assertTrue('1a'.islower())
self.assertFalse('aA'.islower())
def test_isspace(self):
self.assertTrue(' '.isspace())
self.assertFalse(''.isspace())
self.assertFalse(' \ta'.isspace())
def test_istitle(self):
self.assertFalse(''.istitle())
self.assertFalse('abc cd'.istitle())
self.assertTrue('Abc'.istitle())
self.assertTrue(' Abc '.istitle())
self.assertTrue('Abc Cde'.istitle())
self.assertFalse('Abc cde'.istitle())
self.assertFalse('aAbc'.istitle())
def test_isupper(self):
self.assertFalse(''.isupper())
self.assertFalse('1a'.isupper())
self.assertFalse('aA'.isupper())
self.assertTrue('ABCDE E1'.isupper())
def test_join(self):
self.assertEqual('', ' '.join([]))
self.assertEqual('abc', ''.join('abc'))
self.assertEqual('a b c', ' '.join('abc'))
self.assertEqual('abc;cd', ';'.join(['abc', 'cd']))
self.assertRaises(TypeError, lambda: ''.join(1))
def test_ljust(self):
self.assertEqual('abc', 'abc'.ljust(2))
self.assertEqual('abc ', 'abc'.ljust(4))
self.assertEqual('abc::', 'abc'.ljust(5, ':'))
def test_lower(self):
self.assertEqual('abc', 'aBc'.lower())
def test_lstrip(self):
self.assertEqual('abc ', ' abc '.lstrip())
self.assertEqual('bc ', 'abc '.lstrip('a'))
def test_replace(self):
self.assertEqual('', ''.py_replace('a', 'A'))
self.assertEqual('AbcAd', 'abcad'.py_replace('a', 'A'))
def test_rfind(self):
self.assertEqual(-1, ''.rfind('a'))
self.assertEqual(3, 'aaaa'.rfind('a'))
def test_rindex(self):
self.assertEqual(3, 'aaaa'.rindex('a'))
self.assertError(lambda: 'a'.rindex('b'), ValueError)
def test_rjust(self):
self.assertEqual('abc', 'abc'.rjust(1))
self.assertEqual(' abc', 'abc'.rjust(4), '2')
self.assertEqual('::abc', 'abc'.rjust(5, ':'), '3')
def test_rstrip(self):
self.assertEqual(' abc', ' abc '.rstrip())
self.assertEqual(' ab', ' abc'.rstrip('c'))
def test_split(self):
self.assertEqual(['a'], 'a'.py_split())
self.assertEqual(['a', 'b'], ' a\tb '.py_split())
self.assertEqual(['a', 'b'], 'a:b'.py_split(':'))
self.assertEqual(['a', 'b:c'], 'a:b:c'.py_split(':', 1))
self.assertEqual(['a:b:c'], 'a:b:c'.py_split(':', 0))
self.assertEqual(['abc'], 'abc'.py_split(':'))
self.assertEqual([''], ''.py_split(':'))
self.assertEqual([''], ''.py_split(':', 0))
self.assertEqual([], ''.py_split())
self.assertEqual([''], ''.py_split('\n'))
def test_splitlines(self):
self.assertEqual(['a'], 'a'.splitlines())
self.assertEqual(['a', 'b'], 'a\nb'.splitlines())
msg = 'keepends argument of str.splitlines() is not supported'
self.assertError(lambda:'a\nb'.splitlines(True), NotImplementedError,
msg)
def test_strip(self):
self.assertEqual('', ' \t '.strip())
self.assertEqual('a b', ' a b\t '.strip())
def test_swapcase(self):
self.assertEqual('', ''.swapcase())
self.assertEqual('12#', '12#'.swapcase())
self.assertEqual('12aBc', '12AbC'.swapcase())
def test_title(self):
self.assertEqual('', ''.title())
self.assertEqual('A', 'a'.title())
self.assertEqual('Ab1 Cd*', 'ab1 cd*'.title())
self.assertEqual('Aaa', 'AAA'.title())
def test_translate(self):
self.assertError(lambda: ''.translate(' ' * 256),
NotImplementedError, 'str.translate() is not supported.')
def test_upper(self):
self.assertEqual('AER34', 'aeR34'.upper())
def test_zfill(self):
self.assertEqual('abc', 'abc'.zfill(1))
self.assertEqual('00a', 'a'.zfill(3))
self.assertEqual('001', '1'.zfill(3))
self.assertEqual('-01', '-1'.zfill(3))
|
728c57a99d958e46071a42d3739aeb13a246fd8f | Boellis/PatRpi3 | /IndividualStock.py | 1,460 | 3.703125 | 4 | from urllib.request import urlopen
from bs4 import BeautifulSoup
from googlesearch import search
def findStock(StockName):
#Ask what stock
#StockName = input('Enter the name of the stock you want information for: ')
#Specify this input is a stock that exists on the nasdaq and format the input
StockPage = "Nasdaq Stock " + StockName
print(StockPage)
#Search the web for the first page that is returned from the given input
StockQuote = searchStockInfo(StockPage)
#Set the page that we will be scraping
quote_page = StockQuote
#Query the website and return the html to the variable 'html_page'
html_page = urlopen(quote_page)
#Parse the html using beautfil soup and store in the variable 'soup'
soup = BeautifulSoup(html_page, 'html.parser')
#Get the price
stock_price_box = soup.find('div', attrs={'class':'qwidget-dollar'})
#Print the price
print(stock_price_box.text)
return stock_price_box.text
# Currently returns the first website queried from request
# Goal: return stock acronym, price, recent news
def searchStockInfo(stockString):
url = ""
for url in search(stockString,num=1, start=1, stop=2):
print(url)
return url
if __name__ == '__main__':
try:
print("Welcome to the Stock Price Search!")
#print("Press Ctrl + C to leave the search.")
findStock("Tesla")
except KeyboardInterrupt:
print("Program Interrupted")
|
5781e66e5bbfb2ca9f7902c0e03346fa2df61b2b | cassiossousa/dabbling-in-ai | /tictactoe/player.py | 1,124 | 3.546875 | 4 | # Defines a generic player of tic-tac-toe.
from abc import ABCMeta, abstractmethod
from random import choice
class Player():
__metaclass__ = ABCMeta
symbol = None
board = None
def __init__(self, player_id, board, symbol):
self.id = player_id
self.board = board
self.symbol = symbol
self.score = 0
def play(self):
my_play = self.strategy()
self.print_play(my_play)
return my_play, self.symbol
def print_play(self, play):
print "Player " + str(self.id) + "'s turn: " + str(play)
def my_plays(self):
if self.symbol is "O":
return self.board.round_plays
else:
return self.board.cross_plays
def opponent_plays(self):
if self.symbol is "X":
return self.board.round_plays
else:
return self.board.cross_plays
def available_plays(self):
return self.board.available_plays()
def random_play(self):
return choice(self.available_plays())
@abstractmethod
def strategy(self):
while False:
yield None
|
3ac3bf4c40a478f27b78b30a2abc34f93073fe72 | jcemelanda/HackerRankResolution | /warmup/sherlock_beast.py | 512 | 3.984375 | 4 | __author__ = 'julio'
test_case = input()
for _ in xrange(test_case):
digit_num = input()
if not digit_num % 3:
print '5' * digit_num
continue
fives = digit_num - 5
while fives >= 3:
if not fives % 3:
print '5' * fives + '3' * (digit_num - fives)
break
else:
fives -= 5
else:
if fives % 3 or fives < 0:
print '-1'
continue
if not digit_num % 5:
print '3' * digit_num |
c450c4f017804b93595bc90865dfd220dd07bd73 | shellshock1953/python | /games/snake.py | 4,175 | 3.515625 | 4 | import time
import copy
import sys, select
import os
import random
class Board():
def __init__(self, size=10):
self.size = size
self.board = self.generate()
def generate(self):
board = [[ '.' for _ in range(self.size)] for _ in range(self.size)]
return board
def show(self, snake=None):
os.system('clear')
board = copy.deepcopy(self.board)
if snake:
for snake_sell in snake:
y, x = snake_sell
board[y][x] = 'x'
for row in range(self.size):
str_row = " ".join(board[row])
print " %s " % (str_row)
class Snake():
def __init__(self, len=7, vector='right'):
self.len = len
self.vector = vector
self.body = []
self.first_gen()
def vector_to_num(self, y, x):
_y, _x = 0, 0
if self.vector == 'up': _y, _x = 1, 0
elif self.vector == 'down': _y, _x = -1, 0
elif self.vector == 'left': _y, _x = 0, -1
elif self.vector == 'right': _y, _x = 0, 1
y = y + _y
x = x + _x
return y, x
def first_gen(self):
y, x = 5, 5 # starting
self.body.append((y, x)) # aka tail
for sell in range(self.len):
y, x = self.vector_to_num(y, x)
y, x = self.mod(y, x)
self.body.append((y, x))
def step(self):
self.body.pop(0) # rm tail
head = len(self.body) - 1
y, x = self.body[head]
y, x = self.vector_to_num(y, x)
y, x = self.mod(y, x)
self.body.append((y, x))
def mod(self, y, x):
y = y%9
x = x%9
return y, x
class Game():
def __init__(self, sleep=1.0):
self.board = Board()
self.snake = Snake()
self.hello()
self.board.show(self.snake.body)
self.game_over = False
self.sleep = sleep/2
self.donut = None
self.donut_lives = 5
self.donul_sleep = 5
def hello(self):
os.system('clear')
print("")
print("=== HELLO IN SNAKE: THE GAME ===")
print("")
print(" 1) try to get donuts shown as '0'")
print(" 2) dont eat yourself")
print(" 3) move like VIM hjkl")
print("")
select.select( [sys.stdin], [], [], 5)
def run(self):
while not self.game_over:
self.board.show(self.snake.body)
self.input()
self.snake.step()
self.check_game_over()
time.sleep(self.sleep)
def input(self):
print("Move with hjkl")
i, o, e = select.select( [sys.stdin], [], [], self.sleep )
if (i):
arrow = sys.stdin.readline().strip()
if arrow not in ['h', 'j', 'k', 'l']:
print('cant understand, executing automove')
else:
if arrow == 'h' and self.snake.vector != 'right': self.snake.vector = 'left'
elif arrow == 'k' and self.snake.vector != 'up': self.snake.vector = 'down'
elif arrow == 'j' and self.snake.vector != 'down': self.snake.vector = 'up'
elif arrow == 'l' and self.snake.vector != 'left': self.snake.vector = 'right'
else:
print('nothing selected, automove')
def donut(self):
if self.donut_sleep != 0:
self.donut_sleep -= 1
else:
rand_wrong = True
while rand_wrong:
y = random.randint(0,9)
x = random.randint(0,9)
if (x, y) in self.snake.body:
continue
else:
self.donut = (x, y)
rand_wrong = False
def check_game_over(self):
uniq = []
for sell in range(self.snake.len):
if self.snake.body[sell] not in uniq:
uniq.append(self.snake.body[sell])
else:
print("")
print("")
print("=== Game Over ===")
self.game_over = True
break
if __name__ == '__main__':
game = Game()
game.run()
|
fb992c8c25e5283b82a87f67972ee0445e4e0c85 | Sindhu983/function | /function.py | 260 | 3.703125 | 4 |
def func1():
print( " I am learning Python function")
print (" still in func1")
func1()
def square(x):
return x*x
print( square(4))
def multiply(x,y=0):
print("value of x=",x)
print("value of y=",y)
return x*y
print (multiply(y=2,x=4)) |
bc75a37e05ce01e03e436a6e793e696b65bd3154 | hunter-darling/hackerrank-junk | /hackerrank-challenges/repeatedString.py | 547 | 4 | 4 | #!/bin/python3
#solved 2020-01-19
#Hunter Darling
import math
import os
import random
import re
import sys
# Complete the repeatedString function below.
def repeatedString(s, n):
l = len(s)
#print(l)
c_temp = s.count('a')
#print(c_temp)
q = int(math.floor(n/l))
#print(q)
r = n%l
#print(r)
if r == 0:
c = q*c_temp
else:
c = q*c_temp + s[:(r)].count('a')
return(c)
if __name__ == '__main__':
s = input()
n = int(input())
result = repeatedString(s, n)
print(result)
|
a61ca2a777e6452653fe7fbf6cbcf84232362311 | rafaelperazzo/programacao-web | /moodledata/vpl_data/77/usersdata/224/40216/submittedfiles/exercicio24.py | 217 | 3.671875 | 4 | # -*- coding: utf-8 -*-
import math
a=int(input('Digite o primeiro valor: '))
b=int(input('Digite o segundo valor: '))
cont=0
i=1
for i in range(1,n+1,1):
if (a%i==0) and (b%i==0):
cont=cont+i
print(cont)
|
49fdf3e106d81fcb1ea21b97c11999d3dfc5608b | JeeZeh/kattis.py | /Solutions/oddities.py | 155 | 4.03125 | 4 | m = int(input())
for i in range(0, m):
n = int(input())
if abs(n)%2 != 0:
print("%d is odd" % n)
else:
print("%d is even" % n) |
1a1befe7ec2557c875fb529fc11348e9df7ad814 | ananiastnj/PythonLearnings | /LearningPrograms/RegExp.py | 5,459 | 3.734375 | 4 | '''
***** REGULAR EXPRESSIONS *****
-> A regular expression is a special sequence of characters that help you to match or
find other strings or sets of strings using specialized syntex held in pattern
-> The module re provides full support for RE. if any error occurs module raises the exception re.error
Single line match characters pattern :
1) a, e, x, < - Exactly matches the same character
2) .(a period) - matches any single character except newline
3) \w - matches a word Character : a letter or a digit or underbar [a-zA-Z0-9_]
4) \W - matches a non-word character
5) \b - boundry between word and non-word
6) \s - matches a single white space character. Space, Newline, tab and return
7) \S - matches a any non-whitespace character
8) \t, \n, \r - Tab, Newline, Return
9) \d - Decimal digit [0-9]
10) ^ - matches start of the string
11) $ - matches end of the string
12) \ - inhibit the specialness of character
Compilation FLAGS :
-> Compilation flags let you modify some aspects of RE works. It has two names under re module
1. Longname - "IGNORECASE" 2. smallname - "I"
1) ASCII, A = Make several escapes like \w, \s, \b and \d match only on ASCII character.
2) DOTALL, S = Make, match any characters, including newline
3) IGNORECASE, I = make case-insensitive matches
4) LOCALE, L = Do a local-aware match
5) MULTILINE, M = Multi-line matching, affecting ^ and $
6) VERBOSE, X (for extended) - Enable verbose REs, which can be organized more cleanly and understandably
Functions :
re.match(pattern, string, flags=0) - match checks the match in the begining of the line
re.search(pattern, String, flags=0) - Search checks the match anywhere in the line
pattern - Pattern of RE to be matched
String - This is the string have to be checked the pattern is available or not
flags - You can use different flags using bitwise OR |
groups() - This method returns all matching sub-groups
group(num=0) - This method returns entire match on the specific group
search and replace :
re.sub(pattern,repl,string,max=0)
Patterns:
^ - Matches begining of a line
$ - Matches end of a line
. - Matches any single char except a new line
[...] - matches any single char inside a squre bracket
[^...] - matches any single char outside a squre bracket
re* - matches 0 or more occurrences of preceding expression
re+ - matches 1 or more occurrences of preceding expressions
re? - matches 0 or 1 occurrence of preceding expressions
re{n) - matches exactly n number of occurrences of preceding expressions
re{n,} - matches n or more occurrences of preceding expressions
re{n,m} - matches atleast n and atmost m occurences of preceding expressions
a|b - matches either a or b
(re) - Groups a regular expressions and remembers matched text
(?imx) - Temporarily toggles on i, m or x options within a regular expressions. If in parenthesis only that area is affected
(?-imx) - Temporarily toggles off i, m or x options within a regular expressions. If in parenthesis only that area is affected.
(?: re) - Groups regular expressions without remembering matched text
(?imx: re) - Temporarily toggles on i, m or x options within parenthesis
(?-imx: re) - Temporarily toggles off i, m or x options within parenthesis
(?#...) - Comment
(?= re) - Specify position using a pattern. does not have a range
(?! re) - Specify position pattern negation. does not have a range
(?> re) - matches independent pattern without backtracking
\w - Matches a word character
\W - Matches a non-word character
\s - Matches a whitespace. equivalent to [\t\n\r\f]
\S - Matches a nonwhitespace
\d - matches digits. [0-9]
\D - matches nondigits [^0-9]
\A - Matches a begining of a string
\Z - Matches a end of a string. If a newline exists, it match just before a newline
\z - matches a end of string
\G - matches a point where last match finished
\b - matches word boundaries when outside brackets. matches backspace(0x08) when inside bracket
\B - matches nonword boundaries
\n, \t, etc. - matches newline, carriage returns, tabs and etc.
\1...\9 - matches the nth grouped subexpressions
\10 - matches the nth grouped subexpression if it already matched. Otherwise it refers to the octal representation of a char code
'''
import re
#Replace of string
phone = "91765-91765 # Phone number"
#Delete python style comments
num = re.sub(r'#.*$',"",phone)
print("Num : ",num)
#Removing all character except number
num1 = re.sub(r'\D',"",phone)
print("Num1 : %s"%num1)
#Match and Search Group
line = "Cats are smarter than a dogs"
matchObj = re.match(r'(.*) are (.*?) .*', line , re.M | re.I)
if matchObj:
print("matchObj.group() : ", matchObj.group())
print("matchObj.group(1) : ", matchObj.group(1))
print("matchObj.group(2) : ", matchObj.group(2))
print("matchObj.groups() : ", matchObj.groups())
else:
print("No match")
searchObj = re.search(r'(.*) are (.*?) .*', line , re.M | re.I)
if matchObj:
print("searchObj.group() : ", searchObj.group())
print("searchObj.group(1) : ", searchObj.group(1))
print("searchObj.group(2) : ", searchObj.group(2))
print("searchObj.groups() : ", searchObj.groups())
else:
print("No match")
#Differend b/w match and search
matchObj1 = re.match(r'dogs', line, re.M|re.I)
if matchObj1:
print("matchObj1.group() : ", matchObj1.group())
else:
print("No match")
searchObj1 = re.search(r'dogs', line, re.M|re.I)
if searchObj1:
print("searchObj1.group() : ",searchObj1.group())
else:
print("No match") |
ff57ecdea59911bf3b39dc12a0328cdc660ea639 | qudcks0703/python | /python0303/for02.py | 155 | 3.765625 | 4 | result=[]
for i in range(1,5):
result.append(i*3)
print(result)
result=[i*3 for i in range(1,4)]
#표현식 for 항목 in 반복가능개체 if 조건 |
621a0ff1cb09f8f3aa8bb1d4ccfc2e9706d1bbbf | dr-dos-ok/Code_Jam_Webscraper | /solutions_python/Problem_136/2031.py | 640 | 3.6875 | 4 |
def worthIt(cost, curRate, boost, goal):
# calculate whether we will finish earlier if buy
timeToFinish = goal / curRate
timeToBoost = cost / curRate
timeFromBoost = goal / (curRate + boost)
if timeToFinish < timeToBoost + timeFromBoost:
return False
else:
return True
T = input()
for test in xrange(T):
[C, F, X] = [float(x) for x in raw_input().split(' ')]
curTime = 0
curRate = 2.0
while worthIt(C, curRate, F, X):
curTime += C / curRate
curRate += F
answer = (X / curRate) + curTime
print 'Case #' + str(test + 1) + ': ' + "{:1.7f}".format(answer)
|
fce0eb31b46a3838baca3c5bf1ae6082ce3323b2 | lsjhome/algorithms_for_all_py | /Chapter_05/E01_Fibo.py | 181 | 3.609375 | 4 | def fibo(n):
if n <= 1:
return n
return fibo(n-1) + fibo(n-2)
if __name__ =="__main__":
print (fibo(1))
print (fibo(3))
print (fibo(10))
|
eb59e72e9173cd3712e9cdd79e18f8d1182cfc15 | ianaquino47/Daily-Coding-Problems | /Problem_34.py | 1,151 | 4.21875 | 4 | # This problem was asked by Quora.
# Given a string, find the palindrome that can be made by inserting the fewest number of characters as possible anywhere in the word. If there is more than one palindrome of minimum length that can be made, return the lexicographically earliest one (the first one alphabetically).
# For example, given the string "race", you should return "ecarace", since we can add three letters to it (which is the smallest amount to make a palindrome). There are seven other palindromes that can be made from "race" by adding three letters, but "ecarace" comes first alphabetically.
# As another example, given the string "google", you should return "elgoogle".
def is_palindrome(s):
return s == s[::-1]
def make_palindrome(s):
if is_palindrome(s):
return s
if s[0] == s[-1]:
return s[0] + make_palindrome(s[1:-1]) + s[-1]
else:
one = s[0] + make_palindrome(s[1:]) + s[0]
two = s[-1] + make_palindrome(s[:-1]) + s[-1]
if len(one) < len(two):
return one
elif len(one) > len(two):
return two
else:
return min(one, two) |
2c70a04e773f8a74b0f624244beb2da19c3cdf90 | eduardorasgado/divide-and-conquer-algorithms | /selectionsort.py | 982 | 4.15625 | 4 | #SelectionSort
"""
Ordenamiento por seleccion
Es un algoritmo que consiste en ordenar de manera ascendente o descendente
Funcionamiento:
-Buscar el dato mas pequeño de la lista
-Intercambiarlo por el actual
-Seguir buscando el dato mas pequeño de la lista
-Intercambiarlo por el actual
-Repeticion sucesiva
"""
import time
import random
print("Selection Sort")
def generador_listas():
size = int(input("introduzca el tamaño de su lista, cuantos miembros: "))
list_1 = random.sample(range(0,size),size)
print("Lista generada, aleatoriedad presente...")
print(list_1)
return list_1
def selection_sort(lista):
time.sleep(2)
print("empezamos...")
for i in range(len(lista)):
for x in range(i+1,len(lista)):
if lista[x] < lista[i]:
lista[x], lista[i] = lista[i],lista[x]
return lista
print(selection_sort(generador_listas()))
input()
|
ab9a445d8e4180bff2255046363ef6988ed96cdc | minhajar/hajar-lamtaai-42AI-bootcamp | /module00/recipe.py | 1,963 | 4.1875 | 4 | cookbook={
"cake":{"Ingredients":["flour","eggs","sugar"],
"mealType":"dessert",
"cookingTime":60},
"sandwich":{"Ingredients":["bread","greens","chicken"],
"mealType":"lunch",
"cookingTime":10},
"salad":{"Ingredients":["greens","veggies","sauce"],
"mealType":"appetizer",
"cookingTime":20},
}
def print_recipe(recipeName):
print("Recipe for a",recipeName)
print("Ingredients are",cookbook[recipeName]["Ingredients"])
print("To have it as",cookbook[recipeName]["mealType"])
print("Takes",cookbook[recipeName]["cookingTime"],"for prep")
def delete_recipe(recipeName):
if recipeName in cookbook:
del cookbook[recipeName]
def add_new_recipe(recipeName,Ing,meal,Time):
recipe={"Ingredients":[],
"mealType":[],
"cookingTime":[]}
recipe["Ingredients"].append(Ing)
recipe["mealType"].append(meal)
recipe["cookingTime"].append(Time)
cookbook[recipeName]=recipe
def display():
print(cookbook.items())
while option!=5:
print("Please select an option by typing the corresponding number:")
print("1: Add a recipe ")
print("2: Delete a recipe")
print("3: Print a recipe")
print("4: Print the cookbook")
print("5: Quit")
option=int(input())
if option==1:
recipeName=input("print ur recipe name")
Ing=input("print the list of ingredients")
meal=input("print the meal type")
time=input("print the prep time")
add_new_recipe(recipeName,Ing,meal,Time)
elif option==2:
recipeName=input("print the recipe name")
delete_recipe(recipeName)
elif option==3:
recipeName=input("print the recipe name")
print_recipe(recipeName)
elif option==4:
display()
if option==5:
print("you quit the cookbook")
|
4f4df4e509d2016939ccd61b348272a77d8fca09 | liangsongyou/python-crash-course-code | /chapter2/new.py | 133 | 3.59375 | 4 | mess = "new mess"
print("{}".format(mess))
mess = "Yet another new mess"
print("The previous mess was changed to: {}".format(mess))
|
1099c6a0cd94af611a55a81067d49540ce6739c6 | juanall/Informatica | /TP2.py/2.3.py | 432 | 4.0625 | 4 | #Ejercicio 3
#Escribí un programa que dado un número del 1 al 6, ingresado por teclado, muestre cuál es el número que está en la cara opuesta de un dado. Si el número es menor a 1 y mayor a 6 se debe mostrar un mensaje indicando que es incorrecto el número ingresado.
numero = int(input("ingrese un numero del 1 al 6:"))
if numero >=1 and numero <=6:
print(7 - numero)
else:
print("el numero ingresado es incorrecto") |
69d7097a364b14a4a72eb9c5f70b5a2579c12d4f | arnoldvc/Leccion1 | /Leccion05/Set.py | 565 | 4.03125 | 4 | # set
planetas = {'Marte', 'Júpiter', 'Venus'}
print(planetas)
#largo
print(len(planetas))
# revisar si un elemento está presente
print('Marte' in planetas)
# agregar un elemento
planetas.add('Tierra')
print( planetas)
#no se pueden duplicar elementos
planetas.add('Tierra')
print(planetas)
# eliminar elemento posiblemente arrojando un error
planetas.remove('Tierra')
print(planetas)
# eliminar elemento sin arrojar error
planetas.discard('Júpiters')
print(planetas)
# limpiar set
planetas.clear()
print(planetas)
# eliminar el set
#del planetas
print(planetas) |
81f584cd1b42d1954bd3acc0d98bb9850eadcb83 | nda11/CS0008-f2016 | /ch3/ch3-ex9.py | 645 | 4.21875 | 4 |
#get the input for user
number=input('give me the number:')
# assighn number
number=int(number)
# I test if it is out of range
if not(number>=0 and number<=36):
print (' you enter number that outside the range')
if number==0:
color='green'
print ('your color is', color)
elif (number>=1 and number<=10) or (number >= 19 and number <= 28):
if number %2==0:
color=('black')
else:
color=('red')
print ('your color is', color)
elif (number>=11 and number<=18)or((number>=29 and number<=36)):
if number %12==0:
color=('red')
else:
color=('black')
print ('your color is', color) |
1f14a35d989ba8754660426c04c83271a699565a | DevmallyaK/Neural-Network-Basics-with-Tensorflow-Keras | /Neural_Network_Basics_Using_Tensorflow_&_Keras.py | 3,131 | 3.671875 | 4 | # Import the Libraries
import tensorflow as tf
from tensorflow import keras
tf.keras.Model()
from tensorflow.keras.models import Sequential
from tensorflow.keras import Model
import numpy as np
import matplotlib.pyplot as plt
# Import the dataset
mnist = keras.datasets.mnist
(x_train, y_train), (x_test, y_test) = mnist.load_data()
print(x_train.shape, y_train.shape)
# normalize the data : 0.255 -> 0.1
x_train, x_test = x_train / 255.0, x_test / 255.0
# Plot the data
for i in range(6):
plt.subplot(2, 3, i+1)
plt.imshow(x_train[i], cmap='gray')
plt.show()
# model
model = keras.models.Sequential([
keras.layers.Flatten(input_shape=(28, 28)), # Flattens our image to reduce to 1-D
keras.layers.Dense(128, activation = 'relu'), # Fully connected layer
keras.layers.Dense(10), # Final layer
])
print(model.summary())
# We can write in this from also
'''model = keras.Sequential()
model.add(keras.layers.Flatten(input_shape=(28, 28)))
model.add(keras.layers.Dense(128, activation = 'relu'))
model.add(keras.layers.Dense(10))
print(model.summary())'''
# Loss & optimizer
loss = keras.losses.SparseCategoricalCrossentropy(from_logits=True) # For multiclass problem because y is an int class level also sometimes label include onehot
optim = keras.optimizers.Adam(lr=0.001) # create optimizer lr is the hyper parameter
metrics = ["accuracy"]
model.compile(loss=loss, optimizer=optim, metrics=metrics) # configure the model for training
# training
batch_size = 64
epochs = 5
model.fit(x_train, y_train, batch_size=batch_size, epochs=epochs, shuffle=True, verbose=2)
# evaluate the model
model.evaluate(x_test, y_test, batch_size=batch_size, verbose=2)
# predictions
probability_model = keras.models.Sequential([
model,
keras.layers.Softmax()
])
predictions = probability_model(x_test)
pred0 = predictions[0]
print(pred0)
label0 = np.argmax(pred0)
print(label0)
# 2nd way
# model + softmax
predictions = model(x_test)
predictions = tf.nn.softmax(predictions)
pred0 = predictions[0]
print(pred0)
label0 = np.argmax(pred0)
print(label0)
# 3rd way
predictions = model.predict(x_test, batch_size=batch_size)
predictions = tf.nn.softmax(predictions)
pred0 = predictions[0]
print(pred0)
label0 = np.argmax(pred0)
print(label0)
# For 5 different labels
pred05s = predictions[0:5]
print(pred05s.shape)
label05s = np.argmax(pred05s, axis = 1)
print(label05s)
# Or we can do in another way
import tensorflow as tf
mnist = tf.keras.datasets.mnist
(x_train, y_train),(x_test, y_test) = mnist.load_data()
x_train, x_test = x_train / 255.0, x_test / 255.0
model = tf.keras.models.Sequential([
tf.keras.layers.Flatten(input_shape=(28, 28)),
tf.keras.layers.Dense(128, activation='relu'),
tf.keras.layers.Dropout(0.2),
tf.keras.layers.Dense(10, activation='softmax')
])
model.compile(optimizer='adam',
loss='sparse_categorical_crossentropy',
metrics=['accuracy'])
model.fit(x_train, y_train, epochs=5)
model.evaluate(x_test, y_test) |
670d548d3c8a923aa1bdc49fffba2976a8f39c9c | C14427818/Advanced_Security | /Lab4.py | 1,204 | 4.03125 | 4 | #!/usr/bin/python
from Crypto.PublicKey import RSA
from Crypto import Random
print "Lab 4 RSA Algorithm"
'''
STEPS IN CODE BUT ALL DONE IN RSA LIBRARY OF PYTHON
#1 TWO PRIME NUMBERS P AND Q
def generate_keypair(p, q):
if not (is_prime(p) and is_prime(q)):
raise ValueError('Both numbers must be prime.')
elif p == q:
raise ValueError('p and q cannot be equal')
#2 N =PQ CALCULATE MODULUS
n = p * q
#3 CALCULATE TOTIENT
tot = (p-1) * (q-1)
#4CHOOSE INT COPRIME TO T
e = random.randrange(1, tot)
g = gcd(e, tot)
while g != 1:
e = random.randrange(1, tot)
g = gcd(e, tot)
#HERE Use Extended Euclid's Algorithm (Included in RSA Library) to generate the private key
#5PUBLIC KEY: (n,e) PRIVATE KEY: (d, n)
return ((e, n), (d, n))
'''
dataInput = 'Advanced Security C14427818'
print (dataInput)
#Generating key
random = Random.new().read
key = RSA.generate(1024, random)
publicKey = key.publickey()
print "Public key =>" , publicKey
#Encrypting with key
encryptData = publicKey.encrypt(dataInput, 32)[0]
print (encryptData)
#Decrypting with key
decryptData = key.decrypt(encryptData)
print (decryptData)
|
38f8d2c7d2512e40e85007b8824fcc506f45c48a | PushkarIshware/pythoncodes | /bridgelabz_pythonproj/functional/cardextend.py | 3,820 | 4.03125 | 4 | '''
/**********************************************************************************
* Purpose: Deck of cards extend
* @author : Janhavi Mhatre
* @python version 3.7
* @platform : PyCharm
* @since 10-1-2019
*
***********************************************************************************/
'''
import random
import numpy as np
from utilities import datastructqueue
class DeckOfCards:
"""This class is used to write logic for deck of cards"""
def shuffle(self):
"""Method to distribute 9 cards to 4 users"""
suits = ["Clubs", "Diamonds", "Hearts", "Spades"]
Rank = ["2", "3", "4", "5", "6", "7", "8", "9", "10", "11 Jack", "12 Queen", "13 King", "14 Ace"]
list_cards = [] # list to hold cards.
while len(list_cards) < 36: # loop will run till 36 because we want to distribute 36 cards to 4 players.
for i in range(0, 9): # used to get only 9 numbers
random_no = random.randint(1, 13) # generate random number within 1 and 13
cards_rank = Rank[random_no - 1]
random_no_suits = random.randint(0, 3) # generates random number for suits.
cards_rank = cards_rank + ' ' + suits[random_no_suits] # adds suit and Rank together.
if cards_rank not in list_cards: # if list of cards does not contains cards_rank already:
if len(list_cards) is not 36:
list_cards.append(cards_rank) # append cards_rank to list of cards
row = 4
column = 9
two_d_array = [[0 for j in range(column)] for i in range(row)] # list comprehensions for matrix.
index = 0
for i in range(row): # row iteration
for j in range(column): # column iteration .
two_d_array[i][j] = list_cards[index]
index += 1
# print(two_d_array)
a = np.array(two_d_array)
print(a)
# print("list of cards , : ",list_cards)
limit = 9
l1 = [] # four lists are used for slicing of 36 elements in 4 parts(9 each).
l2 = []
l3 = []
l4 = []
for i in list_cards[0:9]:
i = tuple((int(i[:2]), i[2:])) # because we are getting data like ['12 Queen Spades']. all in string
# format so we split first two chars converts it to int and add in tuple which makes to separate
# elements in one small tuple.
# also it makes the sorting easy with Int.
l1.append(i) # appends data to list.
l1.sort() # sorts the data.
print()
print("Queue data")
print()
print("Player 1 Cards")
for j in l1:
q1.enqueue(j) # adds data of player 1 to queue 1.
q1.show()
print()
for i in list_cards[9:18]:
i = tuple((int(i[:2]), i[2:]))
l2.append(i)
l2.sort()
print("Player 2 Cards")
for l in l2:
q2.enqueue(l) # adds data of player 2 to queue 2.
q2.show()
print()
for i in list_cards[18:27]:
i = tuple((int(i[:2]), i[2:]))
l3.append(i)
l3.sort()
print("Player 3 Cards")
for m in l3:
q3.enqueue(m) # adds data of player 3 to queue 3.
q3.show()
print()
for i in list_cards[27:]:
i = tuple((int(i[:2]), i[2:]))
l4.append(i)
l4.sort()
print("Player 4 Cards")
for n in l4:
q4.enqueue(n) # adds data of player 4 to queue 4.
q4.show()
return list_cards, two_d_array
q1 = datastructqueue.Queue() # Queue class objects.
q2 = datastructqueue.Queue()
q3 = datastructqueue.Queue()
q4 = datastructqueue.Queue()
card = DeckOfCards()
card.shuffle()
|
57f489912e9906f1fb5e2bd0a03b8263fe277b36 | stdiorion/competitive-programming | /contests_atcoder/agc018/agc018_a.py | 232 | 3.5 | 4 | import math
from functools import reduce
def gcd(*n): return reduce(math.gcd, n)
n, k = map(int, input().split())
a = list(map(int, input().split()))
if max(a) < k or k % gcd(*a):
print("IMPOSSIBLE")
else:
print("POSSIBLE") |
9af941661b450ba18f8d1c1cc6afc4d320964737 | y-usuf/hackerrank-practice | /plus_minus.py | 894 | 4.125 | 4 | '''
Given an array of integers, calculate the fractions of its elements that are positive, negative, and are zeros. Print the decimal value of each fraction on a new line.
'''
n = int(input())
arr = list(map(int, input().split())) [:n]
#initializing count.
pos_sum = 0
neg_sum = 0
zero_sum = 0
#Using lambda to count the values of +ve, -ve and zeros in the array.
#The function filter(function, list) offers an elegant way to filter out all the elements of a list, for which the function function returns True.
pos_sum = len(list(filter(lambda x: (x > 0), arr)))
neg_sum = len(list(filter(lambda x: (x < 0), arr)))
zero_sum = len(list(filter(lambda x: (x == 0), arr)))
#Finding the decimal value of each fraction.
pos_ans = format(pos_sum/n, '.6f')
neg_ans = format(neg_sum/n, '.6f')
zero_ans = format(zero_sum/n, '.6f')
print(pos_ans)
print(neg_ans)
print(zero_ans) |
4b312dac988e5c61d7399aaa80d9bdd2419feeda | Alexrg/Python_challenges | /math/basic_math/area_calculator.py | 2,348 | 4.5625 | 5 | import math
"""
Write a Python function rectangle_area that takes two parameters width and
height corresponding to the lengths of the sides of a rectangle and returns
the area of the rectangle in square inches
"""
def rectangle_area(width, height):
"""
Calculate the area of a rectangle
Args:
width (number): Width of the rectangle
heigth (number): Heigth of the rectangle
Returns:
area (number): The calculated area of the rectangle
"""
area = width * height
return area
rectangle = rectangle_area(4,5)
"""
Write a Python function circle_area that takes a single parameter radius
corresponding to the radius of a circle in inches and returns the the area of a
circle with radius radius in square inches. Do not use π = 3.14, instead use the
math module to supply a higher-precision approximation to π.
"""
def circle_area(radius):
"""
Calculate the area of a circle given the radius
Args:
radius (number): The radius of a circle
Returns:
area (number): The calculated area of the circle
"""
area = math.pi * math.pow(radius, 2)
return area
circle = circle_area(35)
"""
There are several ways to calculate the area of a regular polygon. Given the
number of sides, nn, and the length of each side, s, the polygon's area is:
ns^2 / 4tan(n / π)
For example, a regular polygon with 5 sides, each of length 7 inches, has an
area of 84.3033926289 square inches. Write a function that calculates the area
of a regular polygon, given the number of sides and length of each side. Submit
the area of a regular polygon with 7 sides each of length 3 inches. Enter a
number (and not the units) with at least four digits of precision after the
decimal point. Note that the use of inches as the unit of measurement in these
examples is arbitrary. Python only keeps track of the numerical values, not
the units.
"""
def polygon_area(number_of_sides, side_length):
"""
Calculate the area of a polygon given the number of sides and their length
Args:
number_of_sides (number): Number of sides of the polygon
side_length (number): Size of the polygon sides
Returns:
area (number): The calculated area of the polygon
"""
area = (number_of_sides * math.pow(side_length,2)) / (4 * math.tan(math.pi/number_of_sides))
return area
polygon = polygon_area(7, 3)
print("The area of a 7 sides polygon is {}".format(polygon))
|
231eb8189fc494cd1829a301b785e7fb35186397 | rrdrake/vvtools | /vvt/config/script_util/simple_aprepro.py | 14,592 | 4 | 4 | #!/usr/bin/env python3
from __future__ import division # Make python2 and python3 handle divisions the same.
import sys
import os
import math
import random
import re
class SimpleAprepro:
"""
This class is a scaled-down version of Aprepro, a text preprocessor
for mathematical expressions. It only supports the subset of
capabilities from Aprepro that are most useful for V&V and automated
testing. While the general behavior is the same as Aprepro, the
replaced text is not guaranteed to be the same (e.g. the number of
digits of printed accuracy might not be the same).
The source of Aprepro lives in Seacas:
https://github.com/gsjaardema/seacas
and the documentation can be found here:
https://gsjaardema.github.io/seacas/
Quick Description
-----------------
A file can be written with mathematical expressions between curly
braces (on a single line) and it will write a new file with those
chunks replaced. For example:
Input: "I have {n_bananas = 6} bananas.
Would you like {n_bananas / 2}?"
Output: "I have 6 bananas.
Would you like 3 bananas?"
It is also able to handle simple mathematical functions like sin(),
cos(), and sqrt().
Inputs
------
src_f filename of the file to process
dst_f filename of where to write the processed file
chatty bool defining if messages should be written to screen
override dictionary of values to override or None
immutable bool defining if variables can be overwritten
Outputs
-------
eval_locals dictionary of variable names and values that were
evaluated while processing src_f.
"""
def __init__(self, src_f, dst_f,
chatty=True,
override=None,
immutable=False):
self.src_f = src_f
self.dst_f = dst_f
self.chatty = chatty
if override is None:
self.override = {}
else:
self.override = override
self.immutable = immutable
self.src_txt = []
self.dst_txt = []
# These are defined here so that each time process() is called
# it gets a new version of the locals and globals so that there
# isn't cross-call contamination. Commented entries are present
# in Aprepro but are not supported here.
self.safe_globals = {
"abs": math.fabs,
"acos": math.acos,
#"acosd"
"acosh": math.acosh,
"asin": math.asin,
#"asind"
"asinh": math.asinh,
"atan": math.atan,
"atan2": math.atan2,
#"atan2d"
#"atand"
"atanh": math.atanh,
"ceil": math.ceil,
"cos": math.cos,
#"cosd"
"cosh": math.cosh,
"d2r": math.radians,
#"dim"
#"dist"
"exp": math.exp,
#"find_word"
"floor": math.floor,
"fmod": math.fmod,
"hypot": math.hypot,
#"int" (I think this is part of the python interpreter)
#"julday"
#"juldayhms"
#"lgamma"
"ln": math.log,
"log": math.log,
"log10": math.log10,
"log1p": math.log1p,
"max": max,
"min": min,
"nint" : round,
#"polarX"
#"polarY"
"r2d" : math.degrees,
"rand" : random.uniform,
"rand_lognormal" : random.lognormvariate,
"rand_normal" : random.normalvariate,
"rand_weibull" : random.weibullvariate,
"sign": math.copysign,
"sin": math.sin,
#"sind"
"sinh": math.sinh,
"sqrt": math.sqrt,
#"srand"
#"strtod"
"tan": math.tan,
#"tand"
"tanh": math.tanh,
#"Vangle"
#"Vangled"
#"word_count"
# Predefined Variables from Aprepro
"PI": math.pi,
"PI_2": 2 * math.pi,
"SQRT2": math.sqrt(2.0),
"DEG": 180.0 / math.pi,
"RAD": math.pi / 180.0,
"E": math.e,
"GAMMA": 0.57721566490153286060651209008240243,
"PHI": (math.sqrt(5.0) + 1.0) / 2.0,
}
self.eval_locals = {}
def safe_eval(self, txt):
"""
Evaluate the text given in 'txt'. If it has an assignment operator
assign the value to the appropriately named key in 'eval_locals'.
If 'immutable==True', allow values to be evaluated and stored, but
do not allow them to be overwritten. Return the string representation
of the computed value.
"""
# For each call, make sure the override variables are in place.
self.eval_locals.update(self.override)
if "^" in txt:
raise Exception("simple_aprepro() only supports exponentiation via **" +
" and not ^. As aprepro supports both, please use ** instead." +
" Encountered while processing '{0}'".format(txt))
if "=" in txt:
name, expression = [_.strip() for _ in txt.split("=", 2)]
if self.immutable and name in self.eval_locals.keys():
raise Exception("Cannot change '{0}'".format(name)
+ " because it is immutable. Context:"
+ " '{0}'".format(txt))
if name in self.override:
print("* !!! override variable '{0}' cannot".format(name)
+ " be updated. Context: '{0}'".format(txt))
else:
self.eval_locals[name] = eval(expression,
self.safe_globals,
self.eval_locals)
val = self.eval_locals[name]
else:
val = eval(txt, self.safe_globals, self.eval_locals)
if type(val) is str:
# Python3 and non-unicode vars in python2.
return val
elif str(type(val)) == "<type 'unicode'>":
# Unicode vars in python2.
return val.encode('ascii')
return repr(val)
def load_file(self):
"""
This file reads the file given by self.src_f and saves the list
of lines to self.src_txt. It is modular so that testing can
occur without actual files.
"""
with open(self.src_f, 'r') as src:
self.src_txt = src.readlines()
def dump_file(self):
"""
This function dumps the processed file to self.dst_f. It is
modular so that testing can occur without actual files. If
dst_f is 'None', do not write to disk.
"""
if self.dst_f is None:
return
with open(self.dst_f, 'w') as dst:
# line breaks should already be present
dst.write("".join(self.dst_txt))
def process(self):
"""
Output
-------
eval_locals dictionary of variable names and values that were
evaluated while processing src_txt.
"""
if self.chatty:
print("\n" + "*" * 72)
print("* Calling SimpleAprepro.process()")
print("* --- Current state")
print("* src_f = {0}".format(self.src_f))
print("* dst_f = {0}".format(self.dst_f))
print("* chatty = {0}".format(self.chatty))
print("* override = {0}".format(self.override))
# Process the input file line-by-line
for jdx, line in enumerate(self.src_txt):
# Process escaped curly braces.
clean_line = line.replace("\{", "{").replace("\}", "}")
# Process the aprepro directive blocks.
split_line = re.split(r"({[^{]*?})", clean_line)
for idx, chunk in enumerate(split_line):
if chunk.startswith("{") and chunk.endswith("}"):
# Found a chunk to evaluate.
split_line[idx] = self.safe_eval(chunk[1:-1])
joined_line = "".join(split_line)
if self.chatty:
print("* {0: 4d}: {1}".format(jdx, repr(joined_line)))
self.dst_txt.append("".join(split_line))
if self.chatty:
print("* End call to SimpleAprepro.process()")
print("*" * 72 + "\n")
return self.eval_locals
def test0():
"""
Test how integers are represented.
"""
processor = SimpleAprepro("", "")
processor.src_txt = ["# abc = {abc = 123}", "# abc = { abc }"]
out = processor.process()
assert processor.dst_txt == ["# abc = 123", "# abc = 123"]
assert out == {"abc": 123}
def test1():
"""
Test how floats are represented with only several digits.
"""
processor = SimpleAprepro("", "")
processor.src_txt = ["# abc = {abc = 123.456}", "# abc = { abc }"]
out = processor.process()
assert processor.dst_txt == ["# abc = 123.456", "# abc = 123.456"]
assert out == {"abc": 123.456}
def test2():
"""
Test how floats are represented with machine precision.
"""
processor = SimpleAprepro("", "")
processor.src_txt = ["# abc = {abc = PI}", "# abc = { abc }"]
out = processor.process()
assert processor.dst_txt == ["# abc = 3.141592653589793",
"# abc = 3.141592653589793"]
assert out == {"abc": math.pi}
def test3():
"""
Test for integer division
"""
processor = SimpleAprepro("", "")
processor.src_txt = ["# abc = {abc = 1 / 3}"]
out = processor.process()
assert out == {"abc": float(1.0) / float(3.0)} # all floats, in case you were unsure
# 12345678901234567
assert processor.dst_txt[0][:17] == "# abc = 0.3333333"
def test4():
"""
Test for wrong exponentiation.
"""
processor = SimpleAprepro("", "")
processor.src_txt = ["# abc = {abc = 2 ^ 2}"]
out = processor.process()
assert out == {"abc": 4}
assert processor.dst_txt == ["# abc = 4",]
def simple_aprepro(src_f, dst_f,
chatty=True,
override=None,
immutable=False):
"""
This function is a simplified interface to the SimpleAprepro class.
It instantiates and object and calls the process() function and
returns the dictionary of evaluted values.
Inputs
------
src_f filename of the file to process
dst_f filename of where to write the processed file. If 'None'
return the dictionary of values and do not write to disk.
chatty bool defining if messages should be written to screen
override dictionary of values to override or None
immutable bool defining if variables can be overwritten
Outputs
-------
eval_locals dictionary of variable names and values that were
evaluated while processing src_f.
"""
processor = SimpleAprepro(src_f, dst_f,
chatty=chatty,
override=override,
immutable=immutable)
processor.load_file()
eval_locals = processor.process()
processor.dump_file()
return eval_locals
def main(args):
import argparse
import json
# Parse inputs
parser = argparse.ArgumentParser("simple_aprepro.py")
parser.add_argument('input_file', action='store',
help='File to be processed.')
parser.add_argument('output_file', action='store', default=None,
help='File to be written.')
parser.add_argument('--params', dest='parameters_jsonl',
action='store', default=None,
help='Create multiple files parameterizing from a jsonl file.')
parser.add_argument('--chatty', dest='chatty', action='store_true', default=False,
help='Increase verbosity [default: %(default)s]')
args = parser.parse_args(args)
# Check inputs
if not os.path.isfile(args.input_file):
sys.exit("Input file not found: {0}".format(args.input_file))
if args.parameters_jsonl is not None:
# Ensure that the jsonl file exists.
if not os.path.isfile(args.parameters_jsonl):
sys.exit("Parameter file not found: {0}".format(args.parameters_jsol))
# Read in all the realizations.
realizations = []
with open(args.parameters_jsonl, 'r') as F:
for line in F.readlines():
realizations.append(json.loads(line, encoding='utf-8'))
# Create each file.
base, suffix = os.path.splitext(args.output_file)
for realization in realizations:
sorted_items = sorted(realization.items(), key=lambda x: x[0])
param_string = ".".join(["{0}={1}".format(key, value) for key, value in sorted_items])
output_f = base + "." + param_string + suffix
simple_aprepro(args.input_file, output_f, override=realization, chatty=args.chatty)
print("Wrote {0}".format(output_f))
else:
# Process file
simple_aprepro(args.input_file, args.output_file, chatty=args.chatty)
if __name__ == '__main__':
main(sys.argv[1:])
|
b163aacca460dbcc7fa69343b6ee68ef54e9f04b | kgaurav7/tournament_planner | /tournament.py | 3,812 | 3.5 | 4 | #!/usr/bin/env python
#
# tournament.py -- implementation of a Swiss-system tournament
#
import psycopg2
import bleach
def connect():
"""Connect to the PostgreSQL database. Returns a database connection."""
return psycopg2.connect("dbname=tournament")
def deleteMatches():
"""Remove all the match records from the database."""
try:
conn = connect()
cur = conn.cursor()
cur.execute("""DELETE FROM Tournament;""")
conn.commit()
cur.close()
conn.close()
except:
print 'Unable to connect to the database'
def deletePlayers():
"""Remove all the player records from the database."""
try:
conn = connect()
cur = conn.cursor()
cur.execute("""DELETE FROM Players;""")
conn.commit()
cur.close()
conn.close()
except:
print 'Unable to connect to the database'
def countPlayers():
"""Returns the number of players currently registered."""
try:
conn = connect()
cur = conn.cursor()
cur.execute("""SELECT COUNT(*) FROM Players;""")
result = cur.fetchone()
count = result[0]
cur.close()
conn.close()
return count
except:
print 'Unable to connect to the database'
def registerPlayer(name):
try:
conn = connect()
cur = conn.cursor()
cur.execute("""INSERT INTO Players(Name) Values (%s)""", (bleach.clean(name), ))
conn.commit()
cur.close()
conn.close()
except:
print 'Unable to connect to the database'
def playerStandings():
"""Returns a list of the players and their win records, sorted by wins.
The first entry in the list should be the player in first place, or a player
tied for first place if there is currently a tie.
Returns:
A list of tuples, each of which contains (id, name, wins, matches):
id: the player's unique id (assigned by the database)
name: the player's full name (as registered)
wins: the number of matches the player has won
matches: the number of matches the player has played
"""
try:
conn = connect()
cur = conn.cursor()
cur.execute("""SELECT * FROM CURRENT_STANDINGS;""");
result = cur.fetchall()
conn.commit()
cur.close()
conn.close()
return result
except:
print 'Unable to connect to the database'
def reportMatch(winner, loser):
"""Records the outcome of a single match between two players.
Args:
winner: the id number of the player who won
loser: the id number of the player who lost
"""
try:
conn = connect()
cur = conn.cursor()
cur.execute("""UPDATE Tournament SET matches=array_append(matches, %s),
results=array_append(results, 'win') where Player1=%s""",
(loser, winner));
cur.execute("""UPDATE Tournament SET matches=array_append(matches, %s),
results=array_append(results, 'lose') where Player1=%s""",
(winner, loser));
conn.commit()
cur.close()
conn.close()
except:
print 'Unable to connect to the database'
def swissPairings():
"""Returns a list of pairs of players for the next round of a match."""
standings = playerStandings()
size = len(standings)
l = []
i = 0
while(i < size-1):
l.append([standings[i][0], standings[i][1], standings[i+1][0], standings[i+1][1]])
i += 2
return l
|
bba5e7727c6abedaf3ad8fc1fef28615bbd38c81 | EladAssia/InterviewBit | /Two Pointers Problems/Intersection_Of_Sorted_Arrays.py | 1,129 | 4.0625 | 4 | # Find the intersection of two sorted arrays.
# OR in other words,
# Given 2 sorted arrays, find all the elements which occur in both the arrays.
# Example :
# Input :
# A : [1 2 3 3 4 5 6]
# B : [3 3 5]
# Output : [3 3 5]
# Input :
# A : [1 2 3 3 4 5 6]
# B : [3 5]
# Output : [3 5]
# NOTE : For the purpose of this problem ( as also conveyed by the sample case ), assume that elements that appear more than once in both
# arrays should be included multiple times in the final output.
##########################################################################################################################################
class Solution:
# @param A : tuple of integers
# @param B : tuple of integers
# @return a list of integers
def intersect(self, A, B):
B = list(B)
C = []
for ii in range(len(A)):
if A[ii] in B:
C.append(A[ii])
B[B.index(A[ii])] = None
return C
##########################################################################################################################################
|
525c1d6b1fe4f591439f6074b766ad275bdd622a | Htoon/Python-Tkinter | /tk_textbox_with_scrollbar.py | 410 | 3.640625 | 4 | import tkinter as tk
import tkinter.scrolledtext as scrolledtext
root = tk.Tk()
root.resizable(0,0)
# windowwin frame
canvas = tk.Canvas(root, width = 520, height = 400)
canvas.pack()
# scrolledtext
input_textbox = scrolledtext.ScrolledText(root, undo=True, font=('courier new', 10))
canvas.create_window(10, 40, width = 500, height = 300, window=input_textbox, anchor='nw')
root.mainloop()
|
1824863c5831b3cc9aea20701a6eb2c9676f3cdc | chase001/chase_learning | /Python接口自动化/GWE_test/common/scripts/parama.py | 2,985 | 4.0625 | 4 |
# def bubbleSort(arr):
# n = len(arr)
#
# # 遍历所有数组元素
# for i in range(n):
#
# # Last i elements are already in place
# for j in range(0, n - i - 1):
#
# if arr[j] > arr[j + 1]:
# arr[j], arr[j + 1] = arr[j + 1], arr[j]
#
#
# arr = [64, 34, -20,25, 12, 22, 90,11]
#
# bubbleSort(arr)
#
# print("排序后的数组:")
# for i in range(len(arr)):
# print("%d" % arr[i])
# # 入门,这是装饰器函数,参数 func 是被装饰的函数
# def logger(func):
# def wrapper(*args, **kw):
# print('主人,我准备开始执行:{} 函数了:'.format(func.__name__))
#
# # 真正执行的是这行。
# func(*args, **kw)
#
# print('主人,我执行完啦。')
# return wrapper
#
# @logger
# def add(x, y):
# print('{} + {} = {}'.format(x, y, x+y))
#
#
# add(12142,1245151)
#
# #带参数的函数装饰器
# def say_hello(contry):
# def wrappe(func):
# def deco(*args,**kwargs):
# if contry =="china":
# print("您好,北京.")
# if contry == "english":
# print("hello paris.")
# else:
# return print('hello world.')
# #真正执行函数的地方
# func(*args,**kwargs)
#
# return deco
# return wrappe
#
# # 小明,中国人
# @say_hello("china")
# def xiaoming():
# pass
#
# # jack,美国人
# @say_hello("america")
# def jack():
# pass
#
# xiaoming()
# #不带参数的类装饰器
# class logger(object):
# def __init__(self, func):
# self.func = func
#
# def __call__(self, *args, **kwargs):
# print("[INFO]: the function {func}() is running..."
# .format(func=self.func.__name__))
# return self.func(*args, **kwargs)
#
# @logger
# def say(something):
# print("say {}!".format(something))
#
# say("hello")
#当前时间
import datetime
def now(days= 0, minutes = 0, seconds = 0, format = "%Y-%m-%d %H:%M:%S"):
"""
根据传参以当前时间为基准计算前后时间
例如 今天是2019-11-2 00:00:00
delay_time = now(days=1, format="%Y-%m-%d") 此时得到2019-11-3
:return:
"""
time_result = (datetime.datetime.now()+datetime.timedelta(days=days,minutes=minutes,seconds=seconds)).strftime(format)
return time_result
#高阶:带参数的类装饰器
class logger(object):
def __init__(self, func):
self.func = func
def __call__(self, *args, **kwargs):
print("[INFO]{now}: the function {func}() is running..."
.format(now=now(),func=self.func.__name__))
return self.func(*args, **kwargs)
# @logger
# def paomao(list):
# ll = len(list)
# for i in range(0,ll):
# for m in range(0,ll-i-1):
# if list[m] > list[m+1]:
# list[m],list[m+1] = list[m+1],list[m]
# return list
#
# a=paomao(list=[1026,99,-22,37,66,102,896,-300])
# print(a) |
d4d2b28086c5415fc59e57abd208dc67292901bd | Satily/leetcode_python_solution | /solutions/solution112.py | 805 | 3.796875 | 4 | from data_structure import TreeNode, build_binary_tree
class Solution:
def hasPathSum(self, root, sum):
"""
:type root: TreeNode
:type sum: int
:rtype: bool
"""
if root is None:
return False
if root.left is None and root.right is None:
return sum == root.val
else:
return self.hasPathSum(root.left, sum - root.val) or self.hasPathSum(root.right, sum - root.val)
if __name__ == "__main__":
tree = build_binary_tree(
((((None, 7, None), 11, (None, 2, None)), 4, None), 5, ((None, 13, None), 8, (None, 4, (None, 1, None))))
)
print(Solution().hasPathSum(tree, 22))
tree = build_binary_tree(
(None, -2, (None, -3, None))
)
print(Solution().hasPathSum(tree, 0))
|
c032faff325da53f1224e35205e20d270150351f | Occhima/stanford-cs221-code | /sentiment/submission.py | 5,979 | 3.515625 | 4 | #!/usr/bin/python
import random
import collections
import math
import sys
from util import *
############################################################
# Problem 3: binary classification
############################################################
############################################################
# Problem 3a: feature extraction
def extractWordFeatures(x):
"""
Extract word features for a string x. Words are delimited by
whitespace characters only.
@param string x:
@return dict: feature vector representation of x.
Example: "I am what I am" --> {'I': 2, 'am': 2, 'what': 1}
"""
# BEGIN_YOUR_CODE (our solution is 4 lines of code, but don't worry if you deviate from this)
features = collections.defaultdict(int)
for word in x.split():
features[word] += 1
return features
# END_YOUR_CODE
############################################################
# Problem 3b: stochastic gradient descent
def learnPredictor(trainExamples, testExamples, featureExtractor, numIters, eta):
'''
Given |trainExamples| and |testExamples| (each one is a list of (x,y)
pairs), a |featureExtractor| to apply to x, and the number of iterations to
train |numIters|, the step size |eta|, return the weight vector (sparse
feature vector) learned.
You should implement stochastic gradient descent.
Note: only use the trainExamples for training!
You should call evaluatePredictor() on both trainExamples and testExamples
to see how you're doing as you learn after each iteration.
'''
# featureExtractor = extractCharacterFeatures(6) # for problem 3e
weights = {} # feature => weight
# BEGIN_YOUR_CODE (our solution is 12 lines of code, but don't worry if you deviate from this)
def predictor(x):
return 1 if dotProduct(weights, featureExtractor(x)) > 0 else -1
for x, y in trainExamples:
for feature in featureExtractor(x):
weights[feature] = 0
for i in range(numIters):
for x, y in trainExamples:
if dotProduct(weights, featureExtractor(x)) * y < 1:
increment(weights, eta * y, featureExtractor(x))
# print(evaluatePredictor(testExamples, predictor))
# END_YOUR_CODE
return weights
############################################################
# Problem 3c: generate test case
def generateDataset(numExamples, weights):
'''
Return a set of examples (phi(x), y) randomly which are classified correctly by
|weights|.
'''
random.seed(42)
# Return a single example (phi(x), y).
# phi(x) should be a dict whose keys are a subset of the keys in weights
# and values can be anything (randomize!) with a nonzero score under the given weight vector.
# y should be 1 or -1 as classified by the weight vector.
def generateExample():
# BEGIN_YOUR_CODE (our solution is 2 lines of code, but don't worry if you deviate from this)
phi = {feature: random.random() for feature in random.sample(list(weights), len(weights) - 1)}
y = 1 if dotProduct(weights, phi) > 0 else -1
# END_YOUR_CODE
return (phi, y)
return [generateExample() for _ in range(numExamples)]
############################################################
# Problem 3e: character features
def extractCharacterFeatures(n):
'''
Return a function that takes a string |x| and returns a sparse feature
vector consisting of all n-grams of |x| without spaces mapped to their n-gram counts.
EXAMPLE: (n = 3) "I like tacos" --> {'Ili': 1, 'lik': 1, 'ike': 1, ...
You may assume that n >= 1.
'''
def extract(x):
# BEGIN_YOUR_CODE (our solution is 6 lines of code, but don't worry if you deviate from this)
features = collections.defaultdict(int)
s = x.replace(' ', '')
for i in range(len(s)+1-n):
features[s[i:i+n]] += 1
return features
# END_YOUR_CODE
return extract
############################################################
# Problem 4: k-means
############################################################
def kmeans(examples, K, maxIters):
'''
examples: list of examples, each example is a string-to-double dict representing a sparse vector.
K: number of desired clusters. Assume that 0 < K <= |examples|.
maxIters: maximum number of iterations to run (you should terminate early if the algorithm converges).
Return: (length K list of cluster centroids,
list of assignments (i.e. if examples[i] belongs to centers[j], then assignments[i] = j)
final reconstruction loss)
'''
# BEGIN_YOUR_CODE (our solution is 25 lines of code, but don't worry if you deviate from this)
def distance(x, mu):
""" Return the squared distance between two vectors x and y """
return sum((x[i] - mu[i])**2 for i in x)
centers = random.sample(examples, K)
z = [0] * len(examples)
for t in range(maxIters):
# step 1
for i, x in enumerate(examples):
min_d = 1000000000
for k, mu in enumerate(centers):
d = distance(x, mu)
if d < min_d:
min_d = d
z[i] = k
# step 2
for k, mu in enumerate(centers):
sum_x = collections.defaultdict(float)
count = z.count(k)
for i, x in enumerate(examples):
if z[i] == k:
increment(sum_x, 1 / count, x)
centers[k] = sum_x
# calculate loss
loss = 0
for i, x in enumerate(examples):
diff = x.copy()
increment(diff, -1, centers[z[i]])
loss += dotProduct(diff, diff)
return (centers, z, loss)
# END_YOUR_CODE
# examples = generateClusteringExamples(2, 4, 2)
# K = 2
# maxIters = 5
# centers, assignments, loss = kmeans(examples, K, maxIters)
# outputClusters('clusters.txt', examples, centers, assignments) |
06e7b82cdddf294ba03e8d2d4bdc5997b66b2e2d | woorud/Algorithm | /practice/1992 쿼드트리.py | 767 | 3.609375 | 4 | def quadtree(x, y, n):
global matrix, answer
flag = False
check = matrix[x][y]
for i in range(x, x+n):
if flag:
break
for j in range(y, y+n):
if matrix[j][i] != check:
answer += '('
quadtree(x, y, n//2)
quadtree(x, y+n//2, n//2)
quadtree(x+n//2, y, n//2)
quadtree(x+n//2, y+n//2, n//2)
answer += ')'
flag = True
if not flag:
if matrix[y][x] == 1:
answer += '1'
else:
answer += '0'
n = int(input())
matrix = []
answer = ''
for i in range(n):
matrix.append(list(map(int, str(input()))))
quadtree(0, 0, n)
print(answer)
|
c37b0fe040aab49f012bb5b2e348a9f37f17a2b0 | he1016180540/Python-data-analysis | /Experiment-2/Untitled-1.py | 168 | 3.859375 | 4 | import math
def f(x): return math.pow(x//100, 3) + \
math.pow(x//10 % 10, 3)+math.pow(x % 10, 3)
for x in range(100, 1000):
if(f(x) == x):
print(x)
|
e23f4a285ef54f1e48a73ad13b20c624475c7642 | therikb31/Hospital_Database_Management_Python | /20.py | 900 | 3.5625 | 4 | import mysql.connector
mydb=mysql.connector.connect(host="localhost",user="root",passwd="12345",database="Rik")
mycursor=mydb.cursor()
ch=int(input("Search according to the following Criteria\n1.Code\n2.Name\n3.Price(Range)\n4.Author Name\nEnter Choice:"))
if ch==1:
code=raw_input("Enter Book Code:")
sql="Select * from Book where Code="+"'"+code+"'"
elif ch==2:
name=raw_input("Enter Book Name:")
sql="Select * from Book where Name="+"'"+name+"'"
elif ch==3:
print "Enter the Price Ranging:-"
lprice=raw_input("From:")
uprice=raw_input("To:")
sql="Select * from Book where Price Between "+lprice+" And "+uprice
elif ch==4:
author=raw_input("Enter Book Author:")
sql="Select * from Book where Author="+"'"+author+"'"
mycursor.execute(sql)
x=mycursor.fetchall()
if x==[]:
print "Record Not Found"
for i in x:
print i
|
72d6bd0e6c38d90b4230e978dba27f392f094f0b | mhesshomeier/big-data-spring2018 | /week-03/submission/pset2_test2.py | 3,375 | 3.609375 | 4 | ```python
import pandas as pd
import numpy as np
import matplotlib.pylab as plt
# This line lets us plot on our ipython notebook
%matplotlib inline
# Read in the data
df = pd.read_csv('data/skyhook_2017-07.csv', sep=',')
# check it output
df.head
## check out the data types
df.dtypes
## check out the shape
df.shape
# columns
df.columns
type(df.columns)
bastille = df[df['date'] == '2017-07-14']
bastille.head
# Create a new date column formatted as datetimes.
df['date_new'] = pd.to_datetime(df['date'], format='%Y-%m-%d')
df['date_new'].head
# Determine which weekday a given date lands on, and adjust it to account for the fact that '0' in our hours field corresponds to Sunday, but .weekday() returns 0 for Monday.
df['weekday'] = df['date_new'].apply(lambda x: x.weekday() + 1)
df['weekday'].replace(7, 0, inplace = True)
#check it out
df['weekday'].head
# range
range(0,10,1)
# Remove hour variables outside of the 24-hour window corresponding to the day of the week a given date lands on.
# df[df['date'] == '2017-07-10'].groupby('hour')['count'].sum()
for i in range(0, 168, 24):
j = range(0,168,1)[i - 5]
if (j > i):
df.drop(df[
(df['weekday'] == (i/24)) &
(
( (df['hour'] < j) & (df['hour'] > i + 18) ) |
( (df['hour'] > i + 18 ) & (df['hour'] < j) )
)
].index, inplace = True)
else:
df.drop(df[
(df['weekday'] == (i/24)) &
(
(df['hour'] < j) | (df['hour'] > i + 18 )
)
].index, inplace = True)
Your second task is to further clean the data. While we've successfully cleaned our data in one way
(ridding it of values that are outside the 24-hour window that correspond to a given day of the week)
it will be helpful to restructure our `hour` column in such a way that hours are listed in a more familiar 24-hour range.
To do this, you'll want to more or less copy the structure of the code we used to remove data from hours outside of a given day's
24-hour window. You'll then want to use the [DataFrame's `replace` method](https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.replace.html).
Note that you can use lists in both `to_replace` and `value`.
After running your code, you should have either a new column in your DataFrame or new values in the 'hour' column.
These should range from 0-23. You can test this out in a couple ways; the simplest is probably to `df['hour'].unique()`;
if you're interested in seeing sums of total pings by hour, you can run `df.groupby('hour')['count'].sum()`.
for i in range(0, 168, 24):
j = range(0,168,1)[i - 5]
print(i, j)
if (j > i):
df['hour'].replace(range(i, i +19, 1), range(5, 24, 1), inplace = True) ## replacing the range from i to i+19 with 5 to 24
#df['hour'].replace((i, i + 5, 2), range(0, 5, 1), inplace = True)
#else:
# df['hour'].replace(range(j, i + 19, 1), range(0, 24, 1), inplace = True) ## range (x, y, # by which you count)
df['hour'].unique()
# if (j > i): ## i is the first hour of a day when a day runs from 0 to 23,
# df.drop(df[
# (df['weekday'] == (i/24)) &
# (
# ( (df['hour'] < j) & (df['hour'] > i + 18) ) |
# ( (df['hour'] > i + 18 ) & (df['hour'] < j) )
# )
# ].index, inplace = True)
# else:
'''
df.drop(df[
(df['weekday'] == (i/24)) &
(
(df['hour'] < j) | (df['hour'] > i + 18 )
)
].index, inplace = True)
'''
|
b5b74e510cf8e1595e66ed8241a69bb2a427fd89 | varshinireddyt/Python | /CCI/RemoveDups.py | 1,171 | 3.96875 | 4 | """
Solutions 2.1: Remove Duplicate: Write code to remove duplicates from an unsorted linked list.
Time Complexity: O(n*2)
"""
#Using Two Pointers
class ListNode:
def __init__(self,data):
self.data = data
self.next = None
class LinkedList:
def __init__(self):
self.head = None
def insert(self,data):
node = ListNode(data)
if self.head is None:
self.head = node
else:
node.next = self.head
self.head = node
def printList(self):
current = self.head
while current:
print(current.data)
current = current.next
def removeDups(self):
first = second =self.head
while first is not None:
while second.next is not None:
if second.next.data == first.data:
second.next = second.next.next
else:
second = second.next
first = second = first.next
l = LinkedList()
l.insert("F")
l.insert("O")
l.insert("L")
l.insert("L")
l.insert("O")
l.insert("W")
l.insert("U")
l.insert("P")
# l.printList()
l.removeDups()
l.printList()
|
95911d695fc5c654f3cba2cfd3b6e7b08a257929 | NoorAbdallh/pythonTestBasic | /lec1/try.py | 675 | 3.875 | 4 | def inputNumber(sen):
try:
print(sen)
num = int(input())
except:
num = 0
return num
#num1 = inputNumber('input number 1 : ')
#num2 = inputNumber('input number 2 : ')
#print('sum is ' + str(num1 + num2))
#try:
print('div is :' + str(num1/num2))
#except:
#print('num2 must not be zero!!')
try:
n = int(input('input first num : '))
n2 = int(input('input sec num : '))
print(n/n2)
except ValueError:
print('input int number !')
except ZeroDivisionError:
print('set num2 of none zero value!!')
else:
print('will be printed if we do not have any error ')
finally:
print('will be printed any way')
|
da2a799dcab556ee793941b2bfec874aae4342ea | sunminky/algorythmStudy | /알고리즘 스터디/개인공부/Loop/MillionairePJT.py | 593 | 3.59375 | 4 | # https://swexpertacademy.com/main/code/problem/problemDetail.do?problemLevel=2&problemLevel=3&contestProbId=AV5LrsUaDxcDFAXc&categoryId=AV5LrsUaDxcDFAXc&categoryType=CODE&problemTitle=&orderBy=RECOMMEND_COUNT&selectCodeLang=CCPP&select-1=3&pageSize=10&pageIndex=1
if __name__ == '__main__':
for tc in range(int(input())):
answer = 0
criteria = -1
input()
for e in reversed(input().split()):
e = int(e)
if e > criteria:
criteria = e
answer += max(criteria - e, 0)
print(f"#{tc + 1} {answer}")
|
868dd1cbab9cd61a4086712a9ad54a5f50a8d464 | jameskulu/Data-Types-and-Function-Assingment-Insight-Workshop | /Data Types/15.py | 431 | 4.28125 | 4 | # 15. Write a Python function to insert a string in the middle of a string.
# Sample function and result :
# insert_sting_middle('[[]]<<>>', 'Python') -> [[Python]]
# insert_sting_middle('{{}}', 'PHP') -> {{PHP}}
def insert_string(outer_string, inner_string):
outer_first = outer_string[:2]
outer_last = outer_string[2:4]
return f'{outer_first}{inner_string}{outer_last}'
print(insert_string('[[]]<<>>', 'Python'))
|
70db2053031ccec97e69b032380b342740079e2e | Sabotaz/cracking-the-coding-interview | /src/exo_1_1.py | 368 | 3.78125 | 4 | def uniq(s):
return len(set(s)) == len(s)
def uniq2(s):
all = set()
for i in s:
if i in all:
return False
all.add(i)
return True
def uniq3(s):
# without additionnal datastructure
for i in range(len(s)):
for j in range(i+1, len(s)):
if s[i] == s[j]:
return False
return True
|
b14550a51266da2c5eea8296dbdb7d9efd781f29 | crizzy9/Algos | /leetcode/sorted_subseq.py | 1,102 | 3.984375 | 4 | # Find a sorted subsequence of size 3 in linear time
# 3.3
# Given an array of n integers, find the 3 elements such that a[i] < a[j] < a[k] and i < j < k in 0(n) time. If there are multiple such triplets, then print any one of them.
#
# Examples:
#
# Input: arr[] = {12, 11, 10, 5, 6, 2, 30}
# Output: 5, 6, 30
#
# Input: arr[] = {1, 2, 3, 4}
# Output: 1, 2, 3 OR 1, 2, 4 OR 2, 3, 4
#
# Input: arr[] = {4, 3, 2, 1}
# Output: No such triplet
import sys
def sorted_subseq(arr):
min1 = sys.maxsize
min2 = sys.maxsize
min3 = 0
for a in arr:
if min1 > a:
min1 = a
elif min2 > a:
min2 = a
else:
min3 = a
break
return [min1, min2, min3]
def sorted_subseq_n(arr, n):
seq = [sys.maxsize]*n
for a in arr:
for i in range(len(seq)):
if seq[i] > a:
seq[i] = a
break
return seq
a1 = [12, 11, 10, 5, 6, 2, 30]
a2 = [6, 9, 5, 7, 8, 4, 10]
print(sorted_subseq(a1))
print(sorted_subseq(a2))
print(sorted_subseq_n(a1, 3))
print(sorted_subseq_n(a2, 3))
|
b9323faae9adc1afc4c9ca4c16e069a35169af15 | xdc7/PythonForInformatics | /misc/ListFromFile.py | 211 | 3.6875 | 4 | data = open('romeo.txt')
finalList = []
for line in data:
l = line.rstrip()
words = l.split()
for word in words:
if word not in finalList:
finalList.append(word)
print(finalList) |
9ec1560ecb65a7099b6e4760a5b98c3b95e0bad5 | 824zzy/Leetcode | /Q_Greedy/BasicGreedy/L2_2498_Frog_Jump_II.py | 436 | 3.796875 | 4 | """ https://leetcode.com/problems/frog-jump-ii/description/
The best strategy for the frog is to jump skipping one stone.
Therefore, our answer is the longest jump between st[i] and st[i-2].
"""
from header import *
class Solution:
def maxJump(self, A: List[int]) -> int:
# when there are only two stones
ans = A[1]-A[0]
for i in range(2, len(A)):
ans = max(ans, A[i]-A[i-2])
return ans |
a9614936c86234fe1256adb4a7bdafd4df01ab68 | Chloemartin99/PythonSem1 | /Sessions/Sess9_10/url_file.py | 476 | 3.875 | 4 | #count amount of times the word 'the' appears in an url
from urllib.request import urlopen
fd = urlopen("https://en.wikipedia.org/wiki/Main_Page")
counter = 0
punctuation = '.,<>-=!\/"?!:;[]{}()|_+$#@^%&*'
text = ""
for line in fd:
text = text+ line.decode().rstrip()
for p in punctuation:
text = text.replace(p, " ")
words = text.split()
print(words)
for word in words:
if word =='The' or word=='the':
counter+=1
print(counter)
fd.close() |
c9dfae92c7adc9d19571ba816836208ce7f10fd1 | medvedodesa/Lesson_Python_Hillel | /Lesson_14/oop.py | 413 | 3.703125 | 4 |
'''
class ClassName(parent_list):
body_of_class
'''
class Point:
xx = 23
yy = 0
def __init__(self, X=0, Y=0):
self.x = X
self.y = Y
pt1 = Point(3, 6)
# print(id(pt1))
# print(pt1.x)
# print(pt1.xx)
pt2 = Point()
# print(id(pt2))
#
# print(pt1.x)
# print(pt1.y)
# pt1.x = 9
# print(pt1.x)
# print(pt2.x)
print(pt1.xx)
print(pt2.xx)
Point.xx = 125
print(pt1.xx)
print(pt2.xx)
|
9d57491fe1b6c1b677050891badbac9ba359c2ba | FarzanRashid/Codewars-solutions | /Product Of Maximums Of Array (Array Series #2).py | 268 | 4.03125 | 4 | def max_product(lst, n_largest_elements):
output = 1
lst.sort()
lst.reverse()
nums = []
for i in range(0, n_largest_elements):
nums.append(lst[i])
for i in nums:
output *= i
return output
print(max_product([4, 3, 5], 2))
|
8e613fb0d4111b3b7402ff58d570f4933d57ae62 | AdamZhouSE/pythonHomework | /Code/CodeRecords/2804/60764/234125.py | 159 | 3.59375 | 4 | str=input()
nums=str.split('+');
nums.sort();
for i in range(len(nums)):
if i!=len(nums)-1:
print(nums[i],end="+")
else:
print(nums[i]) |
022f118231ba617738b48f8d45141df339c1cfca | bikramjitnarwal/CodingBat-Python-Solutions | /String-2.py | 1,978 | 4 | 4 | # double_char:
# Given a string, return a string where for every char in the original, there are two chars.
def double_char(str):
string = ""
for i in range(len(str)):
string += str[i]*2
return string
# count_hi:
# Return the number of times that the string "hi" appears anywhere in the given string.
def count_hi(str):
count = 0
for i in range(len(str)-1):
if str[i] == 'h' and str[i+1] == 'i':
count += 1
return count
# cat_dog:
# Return True if the string "cat" and "dog" appear the same number of times in the given string.
def cat_dog(str):
dogCount = 0
catCount = 0
length = len(str)
for i in range(length - 2):
if str[i] == 'd' and str[i + 1] == 'o' and str[i + 2] == 'g':
dogCount += 1
elif str[i] == 'c' and str[i + 1] == 'a' and str[i + 2] == 't':
catCount += 1
if dogCount == catCount:
return True
else:
return False
# count_code:
# Return the number of times that the string "code" appears anywhere in the given string, except we'll accept any
# letter for the 'd', so "cope" and "cooe" count.
def count_code(str):
count = 0
for i in range(len(str) - 3):
if str[i] == 'c' and str[i + 1] == 'o' and str[i + 3] == 'e':
count += 1
return count
# end_other:
# Given two strings, return True if either of the strings appears at the very end of the other string, ignoring
# upper/lower case differences (in other words, the computation should not be "case sensitive").
# Note: s.lower() returns the lowercase version of a string.
def end_other(a, b):
if a.lower().endswith(b.lower()) or b.lower().endswith(a.lower()):
return True
else:
return False
# xyz_there:
# Return True if the given string contains an appearance of "xyz" where the xyz is not directly preceeded by a
# period (.). So "xxyz" counts but "x.xyz" does not.
def xyz_there(str):
return str.count('.xyz') != str.count('xyz') |
b168a7b9a7a788c28b8ec5abc22fd2f542c4ae29 | alexjercan/algorithms | /old/leetcode/problems/merge-two-sorted-lists.py | 1,109 | 3.84375 | 4 | class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
class Solution:
def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode:
result = None
list_iter = result
while l1 and l2:
if not result:
if l1.val < l2.val:
result = l1
l1 = l1.next
else:
result = l2
l2 = l2.next
list_iter = result
else:
if l1.val < l2.val:
list_iter.next = l1
l1 = l1.next
else:
list_iter.next = l2
l2 = l2.next
list_iter = list_iter.next
if l1:
if not result:
result = l1
else:
list_iter.next = l1
elif l2:
if not result:
result = l2
else:
list_iter.next = l2
return result
Solution().mergeTwoLists(None, ListNode(0, None)) |
cc86a876aff1efefa6d7816d195ec2083828f17e | wyattm14/Robot-Navigation | /RobotNavigation.py | 29,388 | 3.671875 | 4 |
# https://www.geeksforgeeks.org/reading-writing-text-files-python/
# https://pythonprogramming.net/euclidean-distance-machine-learning-tutorial/
from math import sqrt
import sys
import time
# import time
#opening a file with an arg command
file1 = open(sys.argv[1],"r")
#initializing variables
grid = []
mangrid = []
current = []
first_line = 0
arrSize = 0
rowcounter = -1
columncounter = 0
initial_x = 0
initial_y = 0
man_x = 0
man_y = 0
ManhatLeft = 100
ManhatRight = 100
ManhatUp= 100
Manhatdown = 100
EuclidDown = 100
EuclidUp = 100
EuclidLeft = 100
EuclidRight = 100
goal = 0
goalman = 0
path_cost = 0
path_cost_man = 0
downtracker = 0
uptracker = 0
righttracker = 0
lefttracker = 0
equaltracker = 0
stringx = ""
eD = 0
eU = 0
eR= 0
eL = 0
mD = 0
mU = 0
mR= 0
mL = 0
posneg = 0
#iteration through the lines
for x in file1:
if (rowcounter == -1):
arrSize = int(x)
print (arrSize)
rowcounter += 1
subArray = []
#iterate through the charecters in each line
for c in x:
if (c == "." or c == "g" or c == "+" or c == "i"):
subArray.append(c)
#finding the initial state
if (c == "i"):
initial_x = columncounter
initial_y = rowcounter
man_x = columncounter
man_y = rowcounter
#finding the goal state
if c == "g":
goal_x = columncounter
goal_y = rowcounter
columncounter += 1
#creating the grids
if (len(subArray) == arrSize):
grid.append(subArray[:])
mangrid.append(subArray[:])
subArray = []
rowcounter += 1
columncounter = 0
# for line in mangrid:
# print (line)
fringe = []
#formula for the euclidean distance
def EuclideanDist(x,y):
return sqrt((x-goal_x)**2+(y-goal_y)**2)
#formula for the manhattan distance
def ManhattanDist(x,y):
return abs(x-goal_x)+abs(y-goal_y)
#putting the initial state on the fringe
def initialToFringe():
global fringe
fring = []
fringe.append(initial_x)
fringe.append(initial_y)
#moving down for the manhattan distance
def moveDownMan():
global man_y
global path_cost_man
if man_y == (arrSize-1):
print ("you cant move down anymore")
else:
man_y = man_y + 1
mangrid[man_y][man_x]="o"
path_cost_man += 1
# print ("the manhattan path cost is: ", path_cost_man)
# print ("MANHATTAN GRID")
# for theline in mangrid:
# "".join(theline)
# print (theline)
# print (grid)
initialToFringe()
#moving up for the manhattan distance
def moveUpMan():
global man_y
global path_cost_man
if (man_y == 0):
print ("you cant move up anymore")
else:
man_y = man_y - 1
mangrid[man_y][man_x]="o"
path_cost_man += 1
# print ("the manhattan path cost is: ", path_cost_man)
# print ("MANHATTAN GRID")
# for theline in mangrid:
# "".join(theline)
# print (theline)
initialToFringe()
#moving right for the manhattan distance
def moveRightMan():
global man_x
global path_cost_man
if man_x == (arrSize-1):
print ("you cannot move right anymore")
print (mangrid[man_y][man_x])
if mangrid[man_y][man_x+1] == "g":
# print ("you have reached the goal state bruh")
# for line in mangrid:
# print (line)
goalman = 1
else:
man_x = man_x + 1
mangrid[man_y][man_x]="o"
path_cost_man += 1
# print ("the manhattan path cost is: ", path_cost_man)
# print ("MANHATTAN GRID")
# for theline in mangrid:
# "".join(theline)
# print (theline)
# print (grid)
initialToFringe()
#moving left for the manhattan distance
def moveLeftMan():
global man_x
global path_cost_man
if (man_x == 0):
print("cannot move left anymore")
print (mangrid[man_y][man_x])
if mangrid[man_y][man_x-1] == "g":
for line in mangrid:
print (line)
print ("you have reached the goal state left man")
goalman = 1
else:
man_x = man_x - 1
mangrid[man_y][man_x]="o"
path_cost_man += 1
# print ("the manhattan path cost is: ", path_cost_man)
# print ("MANHATTAN GRID")
# for theline in mangrid:
# "".join(theline)
# print (theline)
initialToFringe()
#moving left for the Euclidean distance
def moveLeft():
global initial_x
if (initial_x == 0):
print("cannot move left anymore")
print (grid[initial_y][initial_x])
if grid[initial_y][initial_x-1] == "g":
print ("you have reached the goal state left euc")
goal = 1
else:
for line in grid:
print (line)
initial_x = initial_x - 1
grid[initial_y][initial_x]="o"
global path_cost
path_cost += 1
print ("the euclidean path cost is: ", path_cost)
print ("EUCLIDEAN GRID")
for line in grid:
print("".join(line))
# print (EuclidLeft, "l")
# print (EuclidUp, "u")
# print (EuclidDown, "d")
# print (EuclidRight, "r")
# print ("left")
initialToFringe()
#moving right for the Euclidean distance
def moveRight():
global initial_x
if initial_x == (arrSize-1):
print ("you cannot move right anymore")
print (grid[initial_y][initial_x])
if grid[initial_y][initial_x+1] == "g":
print (initial_y,initial_x, "coordinates")
print ("you have reached the goal state bitch")
goal = 1
else:
for line in grid:
print (line)
initial_x = initial_x + 1
grid[initial_y][initial_x]="o"
global path_cost
path_cost += 1
print ("the euclidean path cost is: ", path_cost)
print ("EUCLIDEAN GRID")
for line in grid:
print ("".join(line))
# print (EuclidLeft, "l")
# print (EuclidUp, "u")
# print (EuclidDown, "d")
# print (EuclidRight, "r")
# print ("right")
initialToFringe()
#moving up for the Euclidean distance
def moveUp():
global initial_y
if (initial_y == 0):
print ("you cant move up anymore")
else:
initial_y = initial_y - 1
grid[initial_y][initial_x]="o"
global path_cost
path_cost += 1
print ("the euclidean path cost is: ", path_cost)
print ("EUCLIDEAN GRID")
for line in grid:
print ("".join(line))
# print (EuclidLeft, "l")
# print (EuclidUp, "u")
# print (EuclidDown, "d")
# print (EuclidRight, "r")
# print ("up")
initialToFringe()
#moving down for the Euclidean distance
def moveDown():
global initial_y
if initial_y == (arrSize-1):
print ("you cant move down anymore")
else:
initial_y = initial_y + 1
grid[initial_y][initial_x]="o"
global path_cost
path_cost += 1
print ("the euclidean path cost is: ", path_cost)
print ("EUCLIDEAN GRID")
for line in grid:
print ("".join(line))
# print (EuclidLeft, "l")
# print (EuclidUp, "u")
# print (EuclidDown, "d")
# print (EuclidRight, "r")
# print ("down")
initialToFringe()
#evaluating the euclidean distances for up down left and right, given it is a legal move.
def evaluateEuclid():
global initial_x
global initial_y
global EuclidLeft
global EuclidDown
global EuclidUp
global EuclidRight
global posneg
# print ("HEY WE IN EVALEUCLID")
#if it is in the initial state
if grid[initial_y][initial_x] == "i":
# print("In the initial state")
if initial_x -1 >= 0:
# print("In the checking left ")
if (grid[initial_y][initial_x-1] == '.'):
leftmove = initial_x - 1
eL = EuclidLeft
EuclidLeft = EuclideanDist(leftmove,initial_y)
posneg = EuclidLeft - eL
# print ("this is Euclid left: ", EuclidLeft)
if initial_x + 1<= arrSize-1:
# print("In the checking right ")
if (grid[initial_y][initial_x+1] == '.'):
rightmove = initial_x + 1
eR = EuclidRight
EuclidRight = EuclideanDist(rightmove,initial_y)
posneg = EuclidRight - eR
# print ("this is Euclid right: ", EuclidRight)
if initial_y + 1<= arrSize -1:
# print("In the checking down ")
if (grid[initial_y+1][initial_x] == '.'):
downmove = initial_y + 1
eD = EuclidDown
EuclidDown = EuclideanDist(initial_x,downmove)
posneg = EuclidDown -eD
# print ("this is Euclid down: ", EuclidDown)
if initial_y - 1>= 0:
# print("In the checking up ")
if (grid[initial_y-1][initial_x] == '.'):
eU = EuclidUp
upmove = initial_y - 1
EuclidUp = EuclideanDist(initial_x,upmove)
posneg = EuclidUp - eU
# not in the initial state
if grid[initial_y][initial_x] != "i":
if initial_x - 1>= 0:
# print("In the checking left ")
if (grid[initial_y][initial_x-1] == '.'):
leftmove = initial_x - 1
eL = EuclidLeft
EuclidLeft = EuclideanDist(leftmove,initial_y)
posneg = EuclidLeft - eL
# print ("this is Euclid left: ", EuclidLeft)
if initial_x + 1<= arrSize -1:
# print("In the checking right ")
print (grid [initial_y][initial_x+1] )
if (grid[initial_y][initial_x+1] == '.'):
rightmove = initial_x + 1
eR = EuclidRight
EuclidRight = EuclideanDist(rightmove,initial_y)
posneg = EuclidRight - eR
# print ("this is Euclid right: ", EuclidRight)
# print (initial_y, "This is initial y bruh")
if initial_y+1<= arrSize-1:
# print("In the checking down ")
if (grid[initial_y+1][initial_x] == '.'):
downmove = initial_y + 1
eD = EuclidDown
EuclidDown = EuclideanDist(initial_x,downmove)
posneg = EuclidDown - eD
# print ("this is Euclid down: ", EuclidDown)
if initial_y - 1>= 0:
# print("In the checking up ")
if (grid[initial_y-1][initial_x] == '.'):
eU = EuclidUp
upmove = initial_y - 1
EuclidUp = EuclideanDist(initial_x,upmove)
posneg = EuclidUp - eU
# print ("this is Euclid up: ", EuclidUp)
# def seeWhatsEqual():
# if equaltracker > 0:
# if EuclidUp == EuclidRight and EuclidUp != 100:
# # print ("up and right are equal")
# elif EuclidUp == EuclidLeft and EuclidUp != 100:
# # print ("up and left are equal")
# elif EuclidDown == EuclidRight and EuclidDown != 100:
# # print ("down and right are equal")
# elif EuclidDown == EuclidLeft and EuclidDown != 100:
# # print ("down and left are equal")
# elif EuclidLeft == EuclidRight and EuclidRight != 100:
# # print ("left and right are equal")
# else:
# print ("nevermind, nothing is equal")
#evaluating the manhattan distances for up, down, left =, and right
def evaluateMan():
global man_x
global man_y
global ManhatLeft
global Manhatdown
global ManhatUp
global ManhatRight
# print(mangrid)
# for thing in mangrid:
# print("".join(thing))
# print(man_y, " man_y")
# time.sleep(.5)
# print(man_x, " man_x")
#checking if its in the initial state
if mangrid[man_y][man_x] == "i":
if man_x -1 >= 0:
if (mangrid[man_y][man_x-1] == '.'):
leftmoveman = man_x - 1
mL = ManhatLeft
ManhatLeft = ManhattanDist(leftmoveman,man_y)
# print ("this is Manhattan left: ", ManhatLeft)
if man_x + 1<= arrSize-1:
if (mangrid[man_y][man_x+1] == '.'):
# print ("RIGHHHHTT")
rightmoveman = man_x + 1
mR = ManhatRight
ManhatRight = ManhattanDist(rightmoveman,man_y)
# print ("this is Manhattan right: ", ManhatRight)
if man_y + 1<= arrSize -1:
if (mangrid[man_y+1][man_x] == '.'):
downmoveman = man_y + 1
mD = Manhatdown
Manhatdown = ManhattanDist(man_x,downmoveman)
# print ("this is Manhattan down: ", Manhatdown)
if man_y - 1>= 0:
if (mangrid[man_y-1][man_x] == '.'):
# print("LEFTTTTT")
mU = ManhatUp
upmoveman = man_y - 1
ManhatUp = ManhattanDist(man_x,upmoveman)
# print ("this is Manhattan up: ", ManhatUp)
#if it is not in the initial state
if mangrid[man_y][man_x] != "i":
if man_x - 1>= 0:
if (mangrid[man_y][man_x-1] == '.'):
leftmoveman = man_x - 1
mL = ManhatLeft
ManhatLeft = ManhattanDist(leftmoveman,man_y)
# print ("this is Euclid left: ", ManhatLeft)
if man_x + 1<= arrSize -1:
if (mangrid[man_y][man_x+1] == '.'):
rightmoveman = man_x + 1
mR = ManhatRight
ManhatRight = ManhattanDist(rightmoveman,man_y)
# print ("this is Manhattan right: ", ManhatRight)
if man_y + 1<= arrSize-1:
if (mangrid[man_y+1][man_x] == '.' ):
downmoveman = man_y + 1
mD = Manhatdown
Manhatdown = ManhattanDist(man_x,downmoveman)
# print ("this is Manhattan down: ", Manhatdown)
if man_y - 1>= 0:
if (mangrid[man_y-1][man_x] == '.'):
mU = ManhatUp
upmoveman = man_y - 1
ManhatUp = ManhattanDist(man_x,upmoveman)
# print ("this is Manhattan up: ", ManhatUp)
# evaluting which manhattan distances are the lowest, simultaneously checking if the goal state has been reached
def letsmoveman():
# time.sleep(.5)
# for line in mangrid:
# print (line)
#
# print ("end here")
global goalman
while (goalman != 1):
evaluateMan()
#for the left sude
if (ManhatLeft != 100):
if man_x-1 >= 0:
if (ManhatLeft < Manhatdown and ManhatLeft < ManhatUp and ManhatLeft < ManhatRight) and mangrid[man_y][man_x-1] != "+":
if (mangrid[man_y][man_x-1] == "g"):
print ("THE GOAL HAS BEEN REACHED: ")
print ("the manhattan path cost is: ", path_cost_man)
print ("MANHATTAN GRID")
for theline in mangrid:
print("".join(theline))
goalman = 1
break
moveLeftMan()
evaluateMan()
if man_x - 1 >= 0:
if (ManhatLeft == ManhatUp or ManhatLeft == Manhatdown or ManhatLeft == ManhatRight and mangrid[man_y][man_x-1] != "+"):
if (mangrid[man_y][man_x-1] == "g"):
print ("THE GOAL HAS BEEN REACHED: ")
goalman = 1
print ("the manhattan path cost is: ", path_cost_man)
print ("MANHATTAN GRID")
for theline in mangrid:
print("".join(theline))
break
moveLeftMan()
evaluateMan()
# for the up movement
if (ManhatUp != 100):
if man_y - 1>= 0 and mangrid[man_y-1][man_x] != "+":
if (ManhatUp < ManhatLeft and ManhatUp < Manhatdown and ManhatUp < ManhatRight):
if (mangrid[man_y-1][man_x] == "g"):
print ("THE GOAL HAS BEEN REACHED: ")
print ("the manhattan path cost is: ", path_cost_man)
print ("MANHATTAN GRID")
for theline in mangrid:
print("".join(theline))
goalman = 1
break
moveUpMan()
evaluateMan()
if man_y - 1>= 0 and mangrid[man_y-1][man_x] != "+":
if (ManhatUp == ManhatLeft or ManhatUp == Manhatdown or ManhatUp == ManhatRight):
if (mangrid[man_y-1][man_x] == "g"):
print ("THE GOAL HAS BEEN REACHED: ")
print ("the manhattan path cost is: ", path_cost_man)
print ("MANHATTAN GRID")
for theline in mangrid:
print("".join(theline))
goalman = 1
break
moveUpMan()
evaluateMan()
# for the down movement
if (Manhatdown != 100):
# print ("good here")
if man_y + 1 <= arrSize -1:
# print ("good here 2")
# print (ManhatUp, "up")
# print (ManhatLeft, "left")
# print (Manhatdown, "down")
# print (ManhatRight, "right")
if (Manhatdown < ManhatLeft and Manhatdown < ManhatUp and Manhatdown < ManhatRight and mangrid[man_y+1][man_x] != "+"):
# print ("good here 3")
if (mangrid[man_y+1][man_x] == "g"):
print ("good here 4")
print ("THE GOAL HAS BEEN REACHED: ")
print ("the manhattan path cost is: ", path_cost_man)
print ("MANHATTAN GRID")
for theline in mangrid:
print("".join(theline))
goalman = 1
break
moveDownMan()
evaluateMan()
if man_y + 1 <= arrSize -1:
if (Manhatdown == ManhatLeft or Manhatdown == ManhatUp or Manhatdown == ManhatRight and mangrid[man_y+1][man_x] != "+"):
if (mangrid[man_y+1][man_x] == "g"):
print ("THE GOAL HAS BEEN REACHED: ")
print ("the manhattan path cost is: ", path_cost_man)
print ("MANHATTAN GRID")
for theline in mangrid:
print("".join(theline))
goalman = 1
break
moveDownMan()
evaluateMan()
# for the right movement
if (ManhatRight != 100):
if man_x + 1 <= arrSize - 1:
if (ManhatRight < ManhatUp and ManhatRight < Manhatdown and ManhatRight < ManhatLeft and mangrid[man_y][man_x+1] != "+"):
if (mangrid[man_y][man_x+1] == "g"):
print ("THE GOAL HAS BEEN REACHED: ")
print ("the manhattan path cost is: ", path_cost_man)
print ("MANHATTAN GRID")
for theline in mangrid:
print("".join(theline))
goalman = 1
break
moveRightMan()
evaluateMan()
elif man_x + 1 <= arrSize - 1:
if (ManhatRight == ManhatUp or ManhatRight == Manhatdown or ManhatRight == ManhatLeft and mangrid[man_y][man_x+1] != "+"):
if (mangrid[man_y][man_x+1] == "g"):
print ("THE GOAL HAS BEEN REACHED: ")
print ("the manhattan path cost is: ", path_cost_man)
print ("MANHATTAN GRID")
for theline in mangrid:
print("".join(theline))
goalman = 1
break
moveRightMan()
evaluateMan()
letsmoveman()
#evaulating the lowest euclidean distances and making movements based on that, simultaneously checking if the goal has been reached
def letsmove():
global stringx
global goal
global equaltracker
global downtracker
global lefttracker
global righttracker
global uptracker
while (goal != 1):
# time.sleep(.5)
# print ("FIX THIS RECURSIONNNNNN")
evaluateEuclid()
# print (EuclidUp, "up")
# print (EuclidDown, "down")
# print (EuclidRight, "right")
# print (EuclidLeft, "left")
# for line in grid:
# print (line)
# for down movements
if (EuclidDown != 100):
if (EuclidDown < EuclidLeft and EuclidDown < EuclidUp and EuclidDown < EuclidRight and grid[initial_y+1][initial_x] != "+"):
# print (initial_x, "X")
# print (initial_y, "Y")
if initial_y + 1<= arrSize-1:
if (grid[initial_y+1][initial_x] == "g"):
print ("THE GOAL HAS BEEN REACHED: ")
goal = 1
print ("the euclidean path cost is: ", path_cost)
print ("THIS IS THE EUCLIDEAN GRID")
for line in grid:
print("".join(line))
break
moveDown()
evaluateEuclid()
downtracker += 1
if downtracker == 1 and righttracker == 0 and lefttracker == 0 and uptracker == 0:
# print ("down was the first move")
stingx = "down"
elif (EuclidDown == EuclidLeft or EuclidDown == EuclidUp or EuclidDown == EuclidRight and grid[initial_y+1][initial_x] != "+"):
equaltracker += 1
# seeWhatsEqual()
if initial_y + 1<= arrSize-1:
if (grid[initial_y+1][initial_x] == "g"):
print ("THE GOAL HAS BEEN REACHED: ")
goal = 1
print ("the euclidean path cost is: ", path_cost)
print ("THIS IS THE EUCLIDEAN GRID")
for line in grid:
print("".join(line))
break
moveDown()
evaluateEuclid()
downtracker += 1
if downtracker == 1 and righttracker == 0 and lefttracker == 0 and uptracker == 0:
# print ("down was the first move")
stringx = "down"
# for left movements
if (EuclidLeft != 100):
if (EuclidLeft < EuclidDown and EuclidLeft < EuclidUp and EuclidLeft < EuclidRight and grid[initial_y][initial_x-1] != "+"):
if initial_x -1 >= 0:
if (grid[initial_y][initial_x-1] == "g"):
print ("THE GOAL HAS BEEN REACHED: ")
goal = 1
print ("the euclidean path cost is: ", path_cost)
print ("THIS IS THE EUCLIDEAN GRID")
for line in grid:
print("".join(line))
break
moveLeft()
evaluateEuclid()
lefttracker += 1
if lefttracker == 1 and righttracker == 0 and downtracker == 0 and uptracker == 0:
# print ("left was the first move")
stringx = "left"
elif (EuclidLeft == EuclidUp or EuclidLeft == EuclidDown or EuclidLeft == EuclidRight and grid[initial_y][initial_x-1] != "+"):
equaltracker += 1
if initial_x -1 >= 0:
# seeWhatsEqual()
if (grid[initial_y][initial_x-1] == "g"):
print ("THE GOAL HAS BEEN REACHED: ")
goal = 1
print ("the euclidean path cost is: ", path_cost)
print ("THIS IS THE EUCLIDEAN GRID")
for line in grid:
print("".join(line))
break
moveLeft()
evaluateEuclid()
lefttracker += 1
if lefttracker == 1 and righttracker == 0 and downtracker == 0 and uptracker == 0:
# print ("left was the first move")
stringx = "left"
#for up movements
if (EuclidUp != 100):
if (EuclidUp < EuclidLeft and EuclidUp < EuclidDown and EuclidUp < EuclidRight and grid[initial_y-1][initial_x] != "+"):
if initial_y - 1 >= 0:
if (grid[initial_y-1][initial_x] == "g"):
print ("THE GOAL HAS BEEN REACHED: ")
goal = 1
print ("the euclidean path cost is: ", path_cost)
print ("THIS IS THE EUCLIDEAN GRID")
for line in grid:
print("".join(line))
break
moveUp()
evaluateEuclid()
uptracker += 1
if uptracker == 1 and righttracker == 0 and downtracker == 0 and lefttracker == 0:
# print ("up was the first move")
stringx = "up"
elif (EuclidUp == EuclidLeft or EuclidUp == EuclidDown or EuclidUp == EuclidRight and grid[initial_y-1][initial_x] != "+"):
equaltracker += 1
if initial_y - 1>= 0:
# seeWhatsEqual()
if (grid[initial_y-1][initial_x] == "g"):
print ("THE GOAL HAS BEEN REACHED: ")
goal = 1
print ("the euclidean path cost is: ", path_cost)
print ("THIS IS THE EUCLIDEAN GRID")
for line in grid:
print("".join(line))
break
moveUp()
evaluateEuclid()
uptracker += 1
if uptracker == 1 and righttracker == 0 and downtracker == 0 and lefttracker == 0:
# print ("up was the first move")
stringx = "up"
#for right movements
if (EuclidRight != 100):
if (EuclidRight < EuclidUp and EuclidRight < EuclidDown and EuclidRight < EuclidLeft and grid[initial_y][initial_x+1] != "+"):
if initial_x + 1 <= arrSize-1:
if (grid[initial_y][initial_x+1] == "g"):
print ("THE GOAL HAS BEEN REACHED: ")
goal = 1
print ("the euclidean path cost is: ", path_cost)
print ("THIS IS THE EUCLIDEAN GRID")
for line in grid:
print("".join(line))
break
moveRight()
evaluateEuclid()
righttracker += 1
if righttracker == 1 and uptracker == 0 and downtracker == 0 and lefttracker == 0:
# print ("up was the first move")
stringx = "right"
elif (EuclidRight == EuclidUp or EuclidRight == EuclidDown or EuclidRight == EuclidLeft and grid[initial_y][initial_x+1] != "+"):
equaltracker += 1
# seeWhatsEqual()
if initial_x + 1 <= arrSize-1:
if (grid[initial_y][initial_x+1] == "g"):
print ("THE GOAL HAS BEEN REACHED: ")
goal = 1
print ("the euclidean path cost is: ", path_cost)
print ("THIS IS THE EUCLIDEAN GRID")
for line in grid:
print("".join(line))
break
moveRight()
evaluateEuclid()
righttracker += 1
if righttracker == 1 and uptracker == 0 and downtracker == 0 and lefttracker == 0:
# print ("up was the first move")
stringx = "right"
letsmove()
#running euclidean first
letsmove()
print ("\nTime for the next search grid: \n")
#running manhattan next
letsmoveman()
file1.close()
|
9e24b20386c310454e8ce60ad16a33ed5a8d67dd | HemantSrivastava01/Python-Practice-Program | /duplicate_list.py | 570 | 3.890625 | 4 | import math
# To get Entry from User-->
NumArr = []
n = int(input("Enter the list size : "))
print("\n")
for i in range(0, n):
print("Enter number at location", i, " : ")
item = int(input())
NumArr.append(item)
print("User Entered List is : ", NumArr)
def Repeat(x):
_size = len(x)
repeated = []
for i in range(_size):
k = i+1
for j in range(k, _size):
if x[i] == x[j] and x[i] not in repeated:
repeated.append(x[i])
return repeated
print("the element repeated in the list : ", Repeat(NumArr))
|
715a9496a5164e134430f67f4bc349e1fcb17ba6 | aroraakshit/coding_prep | /path_sum_III.py | 2,836 | 3.8125 | 4 |
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution: #almost works
def pathSum3(self, root, s, arr, os):
if not root:
return 0
if root.val == s:
print(arr+[root.val], s)
num_paths = 1
else:
num_paths = 0
if root.left:
if s == os:
num_paths += self.pathSum3(root.left, os, [], os)
num_paths += self.pathSum3(root.left, os - root.val, [root.val], os)
else:
num_paths += self.pathSum3(root.left, s - root.val, arr+[root.val], os)
if root.right:
if s == os:
num_paths += self.pathSum3(root.right, os, [], os)
num_paths += self.pathSum3(root.right, os - root.val, [root.val], os)
else:
num_paths += self.pathSum3(root.right, s - root.val, arr+[root.val], os)
return num_paths
def pathSum(self, root: TreeNode, s: int) -> int:
return self.pathSum3(root, s, [], s)
class Solution: # takes about 1060ms, Credits: https://medium.com/@lenchen/leetcode-437-path-sum-iii-c5c1f6bf7d67
def pathSum(self, root, sum):
"""
:type root: TreeNode
:type sum: int
:rtype: int
"""
# approach: examine sum for both subtrees and remember to run
# children even if there is a valid path found
if not root:
return 0
return self.pathSumRecursive(root, sum) + self.pathSum(root.left, sum) + self.pathSum(root.right, sum)
def pathSumRecursive(self, root, sum):
if not root:
return 0
return (1 if root.val == sum else 0) + self.pathSumRecursive(root.left, sum - root.val) + self.pathSumRecursive(root.right, sum - root.val)
class Solution: # 60ms, credits - LeetCode
def pathSum(self, root: 'TreeNode', sum: 'int') -> 'int':
res, targetSum = 0, sum
def pathSumUtil(node, runningSum, mem):
nonlocal res, targetSum
runningSum += node.val
complement = runningSum - targetSum
res += mem.get(complement, 0)
mem[runningSum] = mem.get(runningSum, 0) + 1
if node.left:
pathSumUtil(node.left, runningSum, mem)
if node.right:
pathSumUtil(node.right, runningSum, mem)
# Backtracking, so remove pathSum
mem[runningSum] -= 1
if not root:
return 0
mem = {0: 1}
pathSumUtil(root, 0, mem)
return res |
a57929450cd171611beb3166318d383dd05b2951 | kubaunold/evolutionaryAlgorithm | /helperFolder/dynamicEquation.py | 400 | 3.609375 | 4 | from sympy import symbols
# Symbolic Math
# Working with mathematical symbols in a programmatic way,
# instead of working with numerical values in a programmatic way.
# n <= 5
x1, x2, x3, x4, x5 = symbols('x1 x2 x3 x4 x5')
expr = 2*x1 + x2
#Booth Funtion with global minimum in f(1,3)=0
exprBF = (x1+2*x2-7)**2 + (2*x1 + x2 - 5)**2
print(exprBF.subs(x1,1).subs(x2,3))
# print(expr.subs(x1, 2)) |
326a4339386953103576132ade3665601b18ac9b | whoiskhairul/python | /encription hackerrank.py | 506 | 3.71875 | 4 | import math
# Complete the encryption function below.
def encryption(s):
s = s.replace(" ", "")
length = len(s)
m = math.isqrt(length)
n = math.sqrt(length)
if m != n:
p = m + 1
list = [p]
r = []
i = 0
j = 0
while i <= length:
list[j] = s[i: i + p:]
i = i + p
j = j + 1
for x in list:
for y in list:
r[x] = r + list[y][x]
print(r)
if __name__ == '__main__':
s = input()
result = encryption(s)
|
2d49f2ae3842b3ec30677dd7d6fed90a2da3bae2 | blutarche/someone-in-the-maze | /elements.py | 2,724 | 3.703125 | 4 | import pygame
from pygame.locals import *
from maze_algo import make_maze
class Map(object):
WALK_LIMIT = 5
def __init__(self, row, column, piece_size):
self.row = row
self.column = column
self.map = make_maze(walk_limit=Map.WALK_LIMIT,
w=(column-1)/2,
h=(row-1)/2)
self.map[row-2][column-2] = -1
self.piece_size = piece_size
def walkto(self, x, y, before_x, before_y):
if self.map[y][x] != 0:
self.map[before_y][before_x] -= 1
return True
else:
return False
def is_atgoal(self, x, y):
if self.map[y][x] == -1:
return True
else:
return False
def render(self, surface):
y = 1
for row in self.map:
x = 1
for piece in row:
self.render_piece(surface, x, y, piece)
x = x + 1
y = y + 1
def render_piece(self, surface, x, y, piece):
s = pygame.Surface((self.piece_size, self.piece_size))
if piece != -1:
color_code = int(float(piece)*255 / float(Map.WALK_LIMIT))
s.set_alpha(color_code)
s.fill((255,255,255))
else:
s.set_alpha(255)
s.fill((0,200,0))
surface.blit(s, (x * self.piece_size, y * self.piece_size))
#########################################
class Player(object):
def __init__(self, size, color, pos, gamemap):
(self.x, self.y) = pos
self.color = color
self.map = gamemap
self.size = size
self.atgoal = False
def up(self):
if self.is_walkable(self.x, self.y - 1, self.x, self.y):
self.y = self.y - 1
def down(self):
if self.is_walkable(self.x, self.y + 1, self.x, self.y):
self.y = self.y + 1
def left(self):
if self.is_walkable(self.x - 1, self.y, self.x, self.y):
self.x = self.x - 1
def right(self):
if self.is_walkable(self.x + 1, self.y, self.x, self.y):
self.x = self.x + 1
def is_walkable(self, x, y, before_x, before_y):
print "Walk from (%d,%d) to (%d,%d)" % (before_x, before_y, x ,y)
can_walk = self.map.walkto(x, y, before_x, before_y)
if can_walk and self.map.is_atgoal(x, y):
self.atgoal = True
return can_walk
def is_atgoal(self):
return self.atgoal
def render(self, surface):
x = self.x + 1
y = self.y + 1
radius = self.size / 2
pos_render = (x*self.size + radius , y*self.size + radius)
pygame.draw.circle(surface, self.color, pos_render, radius-1, 0)
|
8c5ba7707866e42df8c4513f800e335ba9bf97af | GennadiiStavytsky/PythonMarathon | /00/t11_bot/bot.py | 827 | 4.0625 | 4 | mainstring = input("Enter your first string: ")
substring = input("Enter your second string: ")
if mainstring == "" or substring == "":
print("One of the strings is empty.")
else:
com = input("Enter your command: ")
if com != "concat" and com != "find" and com != "beatbox":
print("usage: command find | concat | beatbox")
elif com == "concat":
print(f"Your strings is: {mainstring + ' ' + substring}")
elif com == "find":
if substring in mainstring:
print(True)
else:
print(False)
elif com == "beatbox":
beat1 = int(input("Enter your first beatbox number: "))
beat2 = int(input("Enter your second beatbox number: "))
newstring = mainstring * beat1
newsub = substring * beat2
print(newstring + newsub) |
e1792b5137ce77e4b6b9bd70665952dc5c6adde9 | jinurajan/Datastructures | /LeetCode/monthly_challenges/2021/january/02_find_corresponding_node_of_binary_tree_in_a_clone.py | 2,612 | 3.96875 | 4 | """
Find a Corresponding Node of a Binary Tree in a Clone of That Tree
Given two binary trees original and cloned and given a reference to a node target in the original tree.
The cloned tree is a copy of the original tree.
Return a reference to the same node in the cloned tree.
Note that you are not allowed to change any of the two trees or the target node and the answer must be a reference to a node in the cloned tree.
Follow up: Solve the problem if repeated values on the tree are allowed.
Input: tree = [7,4,3,null,null,6,19], target = 3
Output: 3
Explanation: In all examples the original and cloned trees are shown. The target node is a green node from the original tree. The answer is the yellow node from the cloned tree.
Example 2:
Input: tree = [7], target = 7
Output: 7
Input: tree = [8,null,6,null,5,null,4,null,3,null,2,null,1], target = 4
Output: 4
Input: tree = [1,2,3,4,5,6,7,8,9,10], target = 5
Output: 5
Input: tree = [1,2,null,3], target = 2
Output: 2
Constraints:
The number of nodes in the tree is in the range [1, 10^4].
The values of the nodes of the tree are unique.
target node is a node from the original tree and is not null.
"""
# Definition for a binary tree node.
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution1:
def getTargetCopy(self, original: TreeNode, cloned: TreeNode, target: TreeNode) -> TreeNode:
result = [None]
def find_node(node, target, result):
if not node:
# null return
return
if node.val == target.val:
result[0] = node
return
find_node(node.left, target, result)
find_node(node.right, target, result)
find_node(cloned, target, result)
return result[0]
class Solution:
def getTargetCopy(self, original: TreeNode, cloned: TreeNode, target: TreeNode) -> TreeNode:
if not original:
return None
if original == target:
return cloned
reference = self.getTargetCopy(original.left, cloned.left, target)
if reference:
return reference
return self.getTargetCopy(original.right, cloned.right, target)
root1 = TreeNode(7)
root1.left = TreeNode(4)
root1.right = TreeNode(3)
root1.right.left = TreeNode(6)
root1.right.right = TreeNode(19)
root2 = TreeNode(7)
root2.left = TreeNode(4)
root2.right = TreeNode(3)
root2.right.left = TreeNode(6)
root2.right.right = TreeNode(19)
print(Solution().getTargetCopy(root1, root2, root1.right).val)
|
babe1266cc6f21a9e65512c69c9c8deba26b15fe | drkiettran/testing_python | /test/calculate_test.py | 503 | 3.5625 | 4 | import unittest
from app.calculate import Calculate, main
class TestCalculate(unittest.TestCase):
def setUp(self):
self.calc = Calculate()
def test_add_method_returns_correct_result(self):
self.assertEqual(5, self.calc.add(2, 3))
def test_add_method_raises_typeerror_if_not_ints(self):
self.assertRaises(TypeError, self.calc.add, "Hello", "World")
def test_main(self):
self.assertTrue(main())
if __name__ == '__main__':
unittest.main()
|
bc0a00fbcc706ccae50259a4c0c744a8c4076ccd | oltionzefi/daily-coding-problem | /problem_22/problem_22.py | 733 | 3.59375 | 4 | def original_sentence(dictionary, string):
return generate_list(dictionary, string, len(string), [])
def generate_list(dictionary, string, length, results):
for i in range(length + 1):
prefix = string[0:i]
if dictionary_contains(dictionary, prefix):
if i == length:
results.append(prefix)
# should be checked for returning the values of every scenario
print(results)
results.append(prefix)
generate_list(dictionary, string[i:length], length-i, results)
def dictionary_contains(dictionary, string):
for value in range(len(dictionary)):
if dictionary[value] == string:
return True
return False
|
9f4e3c001190ba5339ebb92f4b173c00944fd825 | goo314/2019-LearningFair-MoneyDiary-py | /nose.py | 579 | 3.640625 | 4 | import turtle as t
def move(a, b, t):
t.penup()
t.goto(a, b)
t.pendown()
return
#코_원
def circle(nose_color):
t.color('black', nose_color)
move(0, -60, t)
t.begin_fill()
t.circle(20)
t.end_fill()
return
#코_세모
def triangle(nose_color):
t.color('black', nose_color)
move(-20, -50, t)
t.begin_fill()
for i in range(3):
t.forward(40)
t.left(120)
t.end_fill()
return
def nose(x, y):
if x == 'a':
circle(y)
else:
triangle(y)
return
|
1184142bc6cf5ab8f62201645d418ab215dcf453 | sdytlm/sdytlm.github.io | /downloads/code/LeetCode/Python/Binary-Tree-Preorder-Traversal.py | 664 | 3.875 | 4 | # Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def preorderTraversal(self, root):
"""
:type root: TreeNode
:rtype: List[int]
"""
ret = []
self.searchTree(root,ret)
return ret
def searchTree(self, root, ret):
if root == None:
return
ret.append(root.val)
if root.left != None:
self.searchTree(root.left,ret)
if root.right!=None:
self.searchTree(root.right,ret)
return
|
63c95a6d09e0e8f19563eaada26898ce941a6b26 | aratik711/100-python3-programs | /12.py | 436 | 4.0625 | 4 | """
Write a program, which will find all such numbers between 1000 and 3000 (both included) such that each digit of the number is an even number. The numbers obtained should be printed in a comma-separated sequence on a single line.
"""
answer = []
for i in range(1000, 3000):
i = str(i)
if ((int(i[0])%2==0) and (int(i[1])%2==0) and (int(i[2])%2==0) and (int(i[3])%2==0) ):
answer.append(i)
print(','.join(answer))
|
3f29f98cad0a0f2cba01bf7c44a100ca24f91d72 | UjjwalDhakal7/basicpython | /stringtypes.py | 2,086 | 4.84375 | 5 | #String datatypes
#Any sequence of characters within single or double quotes is a string.
a = 'Hello World'
A = "Hello World"
print(type(A))
print(type(a))
#Using triple quotes to represent a string.
#1. To define a doc string.
#2. To enclose string values having single or double quotes.
a = 'I love python programming.'
b = 'I want to be a "Python developer".'
c = "I am learning 'string' literals."
d = """It is 'fun to learn' when you understand the concept."""
e = '''"Python" is the 'msot popular' language in the world.'''
print(a,b,c,d,e)
#3. To define multi line string literals.
f = """I
am
a
programmer."""
print(f)
#Accesing a character by Index
#We can use the index to fetch a character.
print(a[2])
print(a[-3])
#Python supports both forward and negative index
#Slicing a string
#syntax : s[beginning index : (end-1) index]
z = 'abcdefghijklmnopqrstuvwxyz'
print(z[3:9])
#If we don't assing the beginning index, the default value will be last.
print(z[:10])
#If we don't assing the ending index, the default value will be last.
print(z[3:])
#example : if we have to print love from 'a' then:
print(a[2:6])
print(z[:]) #will print the whole string.
#slice operators never gives index error.
print(z[5:2000]) #will print from the 5th to last.
print(z[20:1]) #will return an empty value as there in not 1 index after 20.
#Applications of Slice operators
# Concatenation ; '+' can be used to join strings together
i = 'Nation'+'300'
print(i)
#Star Operator : string repetition operator
j = 'Nepal'
print(j*5)
print(5*j)
print(j*len(j))
#Note : * operator works as long as one argument is string and other is int.
#to print the first character in uppercase
b = 'apple'
output = b[0].upper()+b[1:]
print(output)
#to print the last character in uppercase
output = b[0:4]+b[-1].upper()
print(output)
#to print the first and last character in uppercase
p = 'this is my program'
output = print(p[0].upper()+p[1:len(p)-1]+p[-1].upper())
|
2af99668bed9ba892ceb15663ca2b30abd999800 | huyngopt1994/python-Algorithm | /leet-code/linked_list/linked_list_cycle.py | 917 | 3.8125 | 4 | # Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
def hasCycle(self, head: ListNode) -> bool:
# just go slow and go fast, if one of the node is reach to None => return false
# If the node from go slow == go fast => loop => return True
if head is None:
return False
slow_node = head
fast_node = head
while True:
slow_node = self.go_slow(slow_node)
fast_node = self.go_fast(fast_node)
if (slow_node and fast_node) is None:
return False
if slow_node == fast_node:
return True
def go_slow(self, node: ListNode) -> ListNode:
return node.next
def go_fast(self, node: ListNode):
if node.next is not None:
return node.next.next
return None
|
68653a631583306cc53e8e9e7a8d3a9c18d05400 | ss2576/Interview | /Lesson_2/task_5.py | 2,297 | 3.671875 | 4 | """
5. Реализовать расчет цены товара со скидкой.
Величина скидки должна передаваться в качестве аргумента в дочерний класс.
Выполнить перегрузку методов конструктора дочернего класса
(метод init, в который должна передаваться переменная — скидка),
и перегрузку метода str дочернего класса.
В этом методе должна пересчитываться цена и возвращаться результат —
цена товара со скидкой.
Чтобы все работало корректно, не забудьте инициализировать дочерний
и родительский классы
(вторая и третья строка после объявления дочернего класса).
"""
class ItemDiscount:
def __init__(self, name, price):
self.__name = name
self.__price = price
@property
def name(self):
return self.__name
@property
def price(self):
return self.__price
@price.setter
def price(self, value):
self.__price = value
class ItemDiscountReport(ItemDiscount):
def __init__(self, name, price, discount):
super().__init__(name, price)
self.__discount = discount
def __str__(self):
return f'Наименование товара: {self.name}. Цена товара со скидкой: {self.price - self.price * self.__discount / 100} руб.'
def get_parent_data(self):
return f'Наименование товара: {self.name}. Цена товара: {self.price} руб.'
def main():
try:
name = input('Введите наименование товара:\n')
price = int(input('Введите цену товара\n'))
discount = int(input('Введите процент скидки\n'))
item_rep = ItemDiscountReport(name, price, discount)
print(item_rep.get_parent_data())
print(item_rep)
except Exception as e:
print(f'{type(e).__name__}: {e}')
if __name__ == '__main__':
main() |
02cc29dc1e9b5ce6d4b8823d4d874ba2e2eadb6c | gerardomdn95/Batch15-Front | /week1/Figuras/Figures.py | 332 | 3.6875 | 4 | class Figures
def __init__(self,name,area,perimeter):
self.name = name
self.perimeter = perimeter
self.area = area
def area(self)
print("The perimeter of the %s is %s" % (self.name, self.area))
def perimetro(self)
print("The area of the %s is %s" (+self.name, self.perimeter)) |
4930b57a15de87942cda14f783d3f6158b5bc4a1 | ashutosh77198/python-tutorials-2 | /Assign2.py | 6,668 | 3.953125 | 4 | #QUES1
"""
x="Python is a great language!", said Fred. "I don't ever remember
having this much fun before."
print(x)
"""
#QUES 2
"""
year=int(input("Enter year to be checked:"))
if(year%4==0 and year%100!=0 or year%400==0):
print("The year is a leap year!")
else:
print("The year isn't a leap year!")
"""
#QUES3
"""
list=[]
extraid=[]
eid=[]
new=[]
x=input("Enter a number to use in a lopp")
for i in range(int(x)):
b=input("enter a string")
list.append(b)
extraid.append(id(list[i]))
print(list)
print(extraid)
list.sort()
for j in list:
print(j)
eid.append(id(j[i]))
new.append(j)
print(eid)
print(new)
"""
"""
student_tuples = [
('Ashutosh', 'kumar', 24),
('saroj', 'ghimire', 20),
('nirmal', 'karki', 58),
('karun', 'karki', 29)
]
b=sorted(student_tuples, key=lambda student: student[2])
student_tuples.sort(key=lambda student: student[2])#unnecessary
print(b)
print(student_tuples)
"""
#ques 6
"""
list1=["ashutosh", "verma", "shrestha","john"]
if "john" in list1:
print("Found")
else:
print("not found")
"""
#QUES 7
"""
age=0
tuples = [
('Ashutosh', 'kumar', 24),
('saroj', 'ghimire', 18),
('nirmal', 'karki', None),
('karun', 'karki', 99)]
new = []
for val in tuples:
if val[2] != None :
new.append(val)
print(new)
for i in new:
age=i[2]+ age
finalavg=age/len(new)
print(finalavg)
for j in new:
if finalavg < j[2]:
print(j[0] + " " +"is OLD")
else:
print(j[0] + " " +"is YOUNG")
"""
#QUES 8
"""
def is_prime(ranum):
if ranum > 1:
for i in range(2,ranum):
if ranum % i == 0:
print(ranum, "It is a not a prime number and FALSE")
break
else:
print(ranum, "It is a prime number and TRUE")
else:
print(ranum, "It is not a prime number and False")
is_prime(int(input("Enter a number")))
"""
#QUES 9
"""
def binary_search(arr, low, high, x):
if high >= low:
mid = (high + low) // 2
if arr[mid] == x:
return mid
elif arr[mid] > x:
return binary_search(arr, low, mid - 1, x)
else:
return binary_search(arr, mid + 1, high, x)
else:
return -1
# Test array
arr = [7, 8, 11, 15, 2]
x = 10
result = binary_search(arr, 0, len(arr) - 1, x)
if result != -1:
print("It is present at index", word(result))
else:
print("It is not present in array")
"""
#QUES 10
"""
def change_case(word):
initial = [word[0].lower()]
b=[]
print(word[1:])
for c in word[1:]:
if c in ('ABCDEFGHIJKLMNOPQRSTUVWXYZ'):
initial.append('_')
initial.append(c.lower())
else:
initial.append(c)
return ''.join(initial)
word = "ThisIsCamelCased"
print(change_case(word))
"""
#QUES 11
"""
import os
print (os.path.splitext("README.txt")[1])
filename = input("Input the Filename: ")
extension = filename.split(".")
print(extension)
print ("The extension of the file is : " + extension[0])
"""
#QUES 13 and 14
"""
def include(entry,entry2):
fileInfo=entry
fileInfo2 = entry2
csvfile=open('fileInfo.csv','w',newline='')
csvfile2 = open('fileInfo2.csv', 'w', newline='')
object=csv.writer(csvfile)
for row in fileInfo:
object.writerow(row)
print(object)
csvfile.close()
fields = list(fileInfo2[0].keys())
object2 = csv.DictWriter(csvfile2, fieldnames=fields)
object2.writeheader()
object2.writerows(fileInfo2)
csvfile2.close()
include([('Name', 'Address', 'age'),('George', '4312 Abbey Road', 22), ('John', '54 Love Ave', 21)],[{'name': 'George', 'address': '4312 Abbey Road', 'age': 22}, {'name':
'John', 'address': '54 Love Ave', 'age': 21}])
"""
#QUES 15
"""
class Person:
def __init__(self, Firstname, surname, address, telephone, email,account):
self.name = Firstname
self.surname = surname
self.address = address
self.telephone = telephone
self.email = email
self.accountno= account
def account(self):
print("acccount number is",self.accountno)
person = Person(
"Saroj",
"Ghimire",
"kalanki12, kathmandu",
"9801905420",
"saroj.ghimire@example.com",
"10180018383881"
)
print(person.name)
print(person.email)
print(person.account())
"""
#QUES 17
"""
num1= int(input("enter a number"))
num2= int(input("enter a second number"))
oper=input("enter a operator you want to use ")
print(type(oper))
if oper=="+":
sum=num1+num2
print("The sum of two numbers is ",sum)
elif oper=="-":
sub=num1-num2
print("The substraction of two numbers is ",sub)
elif oper=="*":
multi=num1*num2
print("The multiplication of two numbers is ",multi)
elif oper=="/":
if num2==0:
next=int(input ("Please enter another number because dividing with 0 can cause undefined errors"))
div=num1/next
print("The division of two numbers is ",div)
"""
#QUES18
"""
class py_solution:
def is_valid_parenthese(self, string):
stack, char = [], {"(": ")", "{": "}", "[": "]"}
for paren in string:
if paren in char:
stack.append(paren)
elif len(stack) == 0 or char[stack.pop()] != paren:
return False
return len(stack) == 0
print(py_solution().is_valid_parenthese("(){}[]"))
print(py_solution().is_valid_parenthese("{)}"))
#print(py_solution().is_valid_parenthese("()"))
"""
#ques 20
"""
def extarxt(A, arr_size, sum):
# Fix the first element as A[i]
for i in range(0, arr_size - 2):
# Fix the second element as A[j]
for j in range(i + 1, arr_size - 1):
# Now look for the third number
for k in range(j + 1, arr_size):
if A[i] + A[j] + A[k] == sum:
print("Triplet is", A[i],
", ", A[j], ", ", A[k])
# If we reach here, then no
# triplet was found
return print("yes")
# Driver program to test above function
A =[-25, -10, -7, -3, 2, 4, 8, 10]
sum = 0
arr_size = len(A)
extarxt(A, arr_size, sum)
"""
#ques 18
"""
import json
with open('user.json','w') as file:
json.dump({
"name": "Ashutosh Verma",
"age": 24,
"friends": ["niraml","saroj"],
"balance": 35.80,
"other_names":("babul","rahul"),
"active":True,
"spouse":None
}, file, sort_keys=True, indent=4)
with open('user.json', 'r') as file:
user_data = json.load(file)
print(user_data)
"""
|
15415458f1e3945e2cc2a2ab02bfdd2a4d3ea3da | ericmintun/rl-tools | /rl/postprocessors.py | 3,824 | 3.96875 | 4 | '''
Postprocessors are in charge of taking the output of a network and
producing definite actions, expected rewards, or other requested results
derived from the network output.
Postprocessors operate in torch variables since they need to connect
forward to the network trainer.
'''
import torch
from torch.autograd import Variable
import numpy as np
class PredictionPostprocessor:
'''
A trivial post processor for supervised learning that just passes
through the outputs of the network.
Initialization values:
none
Methods:
predictions(input) : just returns input
'''
def __init__(self):
pass
def predictions(self, input):
return input
class DiscreteQPostprocessor:
'''
A postprocessor for Q learning in an environment with a discrete
action space. Assumes the network outputs an estimated value Q for
each available action. At the moment, this essentially does nothing
but run the torch max function or pick values out of an array.
Initialization values:
none
Methods:
best_action(input, output_q=False) :
Input is a 2D array of estimated values Q of the form
(batch, action). Returns a 1D array of the actions with the
highest estimated rewards. If output_q is True, returns a 2-tuple
of the form (actions, q_values) where q_values are the values of
the optimal actions.
estimated_reward(input, actions) :
Input is a 2D array of estimated values Q, and actions is a 1D
array of actions of interest, which are integers between 0 and the
length of the second dimension of input. For each element in the
batch, returns the ith Q given action i.
'''
def __init__(self):
pass
def best_action(self, input, output_q=False):
q, action = torch.max(input, 1)
if output_q == True:
return (action, q)
else:
return action
def estimated_reward(self, input, actions):
if type(actions) == Variable: #This isn't great
return torch.gather(input,1,actions.view(-1,1)).view(-1)
else:
return torch.gather(input,1,Variable(actions.view(-1,1))).view(-1)
class CapsuleBasicPostprocessor(PredictionPostprocessor):
'''
A postprocessor designed for basic capsules. Extracts probability of
an entities existence from the length of the supplied pose vector.
Initialization values:
none
Methods:
predictions(input) :
Input is a 3D tensor of the form (batch, label, pose_element).
Returns a 2D tensor of the form (batch, label) where each
element is a number from 0 to 1 yielding the predicted
probability that element exists.
mask(input, mask_vectors) :
input is a 3D tensor of the form (batch, label, pose_element).
mask_vector is a 2D tensor of the form (batch, label), where
every element is a zero or a one. Returns a 3D tensor of the
same form as input, where every element of the pose vector
corresponding to a zero in mask_vectors is set to zero.
'''
def __init__(self):
super(CapsuleBasicPostprocessor, self).__init__()
def predictions(self, input):
#print(torch.norm(input, dim=2))
return torch.norm(input,dim=2)
def mask(self, input, mask_vectors):
if type(mask_vectors) is Variable:
m = mask_vectors
elif type(mask_vectors) is torch.Tensor:
m = Variable(mask_vectors)
else:
raise TypeError("mask_vectors must be either a torch tensor or torch variable.")
#Permute the pose_elements to the first index so multiply broadcasts correctly
return (input.permute(2,0,1) * mask_vectors.type(torch.LongTensor)).permute(0,1,2)
|
901bb203bf344cf6ab4aa05292dea52426714416 | ian-dqn/perceptron | /first_neuron.py | 742 | 3.5625 | 4 | import numpy as np
def sigmoid(x):
return 1 / (1 + np.exp(-x))
def sigmoid_derivative(x):
return x * (1 - x)
train_inputs = np.array([[0,0,1],
[1,1,1],
[1,0,1],
[0,1,1]])
train_outputs = np.array([[0,1,1,0]]).T
np.random.seed(1)
synaptic_weights = 2 * np.random.random((3, 1)) - 1
print('Random starting synaptic weights:')
print(synaptic_weights)
for i in range(20000):
input_layer = train_inputs
outputs = sigmoid(np.dot(input_layer, synaptic_weights))
error = train_outputs - outputs
adjustements = error *sigmoid_derivative(outputs)
synaptic_weights += np.dot(input_layer.T, adjustements)
print('Synaptic weights after training')
print(synaptic_weights)
print('outputs after training:')
print(outputs)
|
43f67becf734831185f45b8eadee7c417aab3b9c | qua-platform/qua-libs | /examples-old/basics/intro-to-macros/intro-to-macros.py | 2,471 | 3.921875 | 4 | """
intro-to-macros.py: An intro to usage of macros in QUA
Author: Gal Winer - Quantum Machines
Created: 26/12/2020
Created on QUA version: 0.6.393
"""
from qm.QuantumMachinesManager import QuantumMachinesManager
from qm.qua import *
from qm import SimulationConfig
from configuration import config
QMm = QuantumMachinesManager()
def declare_vars(stream_num=1):
"""
A macro to declare QUA variables. Stream num showcases a way to declare multiple streams in an array
Note that variables and streams need to be explicitly returned to the QUA function to be in scope
"""
time_var = declare(int, value=100)
amp_var = declare(fixed, value=0.2)
stream_array = [declare_stream() for num in range(stream_num)]
return [time_var, amp_var, stream_array]
def modify_var(addition=0.3):
"""
A macro to modify a QUA variable. In this case, the variable does not
need to be returned.
"""
assign(b, b + addition)
def qua_function_calls(el):
"""
A macro that calls QUA play statements
:param el: The quantum element used by the QUA statements
:return:
"""
play("playOp", el, duration=300)
play("playOp" * amp(b), el, duration=300)
with program() as prog:
[t, b, c_streams] = declare_vars()
# Plays pulse with amplitude of 0.2 (from config) * b=0.2 (from declare_vars) for t=100ns (from declare_vars)
save(b, c_streams[0]) # Saves b into stream for printing at the end
play("playOp" * amp(b), "qe1", duration=t)
# Plays pulse with amplitude of 0.2 (from config) * b=0.5 (after modify_var) for t=100ns (from declare_vars)
modify_var()
save(b, c_streams[0]) # Saves b into stream for printing at the end
play("playOp" * amp(b), "qe1", duration=t)
# Plays pulse twice, first with amplitude 0.2 (from config) for duration 300ns (from qua_function_calls).
# Second with with 0.2 (from config) * b=0.5 (after modify_var) for duration 300ns (from qua_function_calls).
qua_function_calls("qe1")
with stream_processing():
c_streams[0].save_all("out_stream")
QM1 = QMm.open_qm(config)
job = QM1.simulate(prog, SimulationConfig(int(1500)))
res = job.result_handles
out_str = res.out_stream.fetch_all()
samples = job.get_simulated_samples()
samples.con1.plot()
print("##################")
print("b is saved twice, once before the call to modify_var and once afterwards")
print(f"Before:{out_str[0]}, After:{out_str[1]}")
print("##################")
|
bac3751657727eba6d350ce85425c2d91066064e | matthewatabet/algorithms | /sort/heapsort.py | 1,278 | 3.96875 | 4 | class PriorityQueue(object):
'''
Zero indexed heap.
'''
def __init__(self):
self.data = []
def _exchange(self, i, j):
t = self.data[i]
self.data[i] = self.data[j]
self.data[j] = t
def _less(self, i, j):
return self.data[i] < self.data[j]
def _promote(self, i):
while i > 0 and self._less(((i + 1)/2) - 1, i):
self._exchange(((i + 1)/2) - 1, i)
i = ((i + 1)/2) - 1
def _demote(self, i):
while ((i + 1) * 2) - 1 < len(self.data):
j = ((i + 1) * 2) - 1
if (j < len(self.data) - 1 and
self._less(j, j+1)):
j += 1
if self._less(j, i):
break
self._exchange(i, j)
i = j
def add(self, x):
i = len(self.data)
self.data.append(x)
self._promote(i)
def pop(self):
ret = self.data.pop(0)
if self.data:
self._demote(0)
return ret
def heap_sort(data):
pq = PriorityQueue()
for d in data:
pq.add(d)
ret = []
for i in range(0, len(data)):
ret.append(pq.pop())
return ret
print heap_sort([4, 2, 13, 12, 9, 2, 9, 9])
print heap_sort([3, 4, 1, 1, 2, 2, 1, 1])
|
97ef5942db351e6fdbe08256cf075e5df402bb2f | kwr0113/BOJ_Python | /step10/2447-3.py | 272 | 3.65625 | 4 | # 2447-3.py
def star(x):
if x == 1:
return ['*']
x = x // 3
a = star(x)
topbottom = [i * 3 for i in a]
middle = [i + ' ' * x + i for i in a]
return topbottom + middle + topbottom
n = int(input())
mystar = '\n'.join(star(n))
print(mystar) |
1a5c57eabd3d487cdfe5df7ca5375fc35c9070f2 | vaavaav/LEI | /3ano/2semestre/pl/aula7/listas/listas2_yacc.py | 1,514 | 3.75 | 4 | '''
listas_yacc.py
aula7: 2021-04-13
Listas heterogéneas: inteiros e alfanuméricos
[78]
[1,2,3]
[121,asa,c45]
T = {number, '[', ']', alfanum, ','}
N = {Lista, Elementos, Elemento}
p1: Lista -> '[' Elementos ']'
p1.5: Lista -> '[' ']'
p2: Elementos -> Elemento
p3: Elementos -> Elementos ',' Elemento
p4, p5: Elemento -> alfanum | number
'''
import ply.yacc as yacc
from listas_lex import tokens
def p_Lista(p):
"Lista : PA Elementos PF"
pass
def p_Lista_empty(p):
"Lista : PA PF"
pass
def p_Elementos(p):
"Elementos : Elementos VIRG Elemento"
p.parser.elems += 1
def p_Elementos_Elemento(p):
"Elementos : Elemento"
p.parser.elems = 1
def p_Elemento_number(p):
"Elemento : number"
p.parser.numbers.append(p[1])
def p_Elemento_alfanum(p):
"Elemento : alfanum"
p.parser.alfanum.append(p[1])
def p_error(p):
print('Erro sintático: ', p)
parser.success = False
# Build the parser
parser = yacc.yacc()
# Read input and parse it by line
import sys
for linha in sys.stdin:
parser.success = True
parser.numbers = []
parser.alfanum = []
parser.elems = 0
parser.parse(linha)
if parser.success:
print("Frase válida reconhecida: ", linha)
print("#elementos: ", parser.elems)
print("Números: ", parser.numbers)
print("Alfanuméricos: ", parser.alfanum)
else:
print("Frase inválida. Corrija e tente de novo...")
|
ae846be11a095f14c090941f9e60b81bd9908e23 | SteffanySympson/BLUE-MOD-1 | /Desafios/Desafio Sena.py | 1,819 | 4.09375 | 4 | # Faça um programa que ajude um jogador da MEGA SENA a criar
# palpites.O programa vai perguntar quantos jogos serão gerados e vai sortear 6
# números entre 1 e 60 para cada jogo, cadastrando tudo em uma lista composta.
#um número deve ser randomizado
# lista principal
#contador
#enquanto for verdade repete
import random
from random import randint
print(" Roleta da Sorte Blue - JOGA NA MEGA!!! ")
print()
quantidade = (int(input("Quantos jogos serão sorteados?")))
print()
TotalDeJogos = 1
jogos = []
lista = []
while TotalDeJogos <= quantidade:
cont = 0 #o contador tem que estar dentro do 1º enquanto se não ele não roda 6 vezes nos loopins depois do 1º
while True: #enquanto for verdade
num = randint(1,60) #num será sorteado aleatoriamente entre 1 e 60 (mega sena não tem 0)
if num not in lista: #se num não estiver contido na variável lista, faça:
lista.append(num) #na variável lista, insira a variável num
cont +=1 #cada vez que rodar insira mais um, soma mais um no contador
if cont >= 6: #quando o contador chegar a 6
break #pare de rodar
lista.sort() #arruma decrescente a lista
jogos.append(lista[:]) #[:] cria uma cópia da lista que foi sorteada
lista.clear() #a variável lista é apagada a cada rodada do random, lembrando q ela está copiada dentro da lista jogos
TotalDeJogos +=1 #para não entrar em looping eterno
print(" ", f".....SORTEANDO..... {quantidade}", ".....JOGOS.....")
for i, l in enumerate(jogos): #A função enumerate() retorna uma tupla (é igual a lista mas não pode ser modificada) de dois elementos a cada iteração: um número sequencial e um item da sequência correspondente.
print(f"Jogo {i+1}: {l}")
print()
print("BOA SORTE!!!")
|
7c4aba9ab641b9488ec1eaf778a42548f342e092 | Riley-Milligan/pythonweekone | /day3/sixreverse.py | 83 | 4.15625 | 4 | to_reverse = input("What word would you like to reverse?")
print(to_reverse[::-1]) |
00c392f6d795efec60950ff303bbcc489aff5738 | leonhostetler/undergrad-projects | /computational-physics/07_derivatives/derivative.py | 799 | 4.21875 | 4 | #! /usr/bin/env python
"""
Numerically compute the derivative of f(x) = x(x-1) using different
values for the small number delta.
Leon Hostetler, Feb. 21, 2017
USAGE: python derivative.py
"""
from __future__ import division, print_function
# Main body of program
def f(x):
"""
This function returns the value of f(x) = x(x-1)
"""
return x*(x-1)
def der(x, delta):
"""
This function returns the derivative f'(x) at x given a value for delta.
"""
return (f(x+delta) - f(x))/delta
print("\n The actual value is f'(1) = 1. Following are the numerical approximations.\n")
# Here, we compute f'(1) numerically using different values of
# delta and print the results.
for i in range(2, 20, 2):
print("f'(1) with delta = ", 10**(-i), " is: ", der(1, 10**(-i)), sep="")
|
d80fb86b726b06fa58924cfbe2861eb51f78599e | mrahul16/Green-Index---Hadoop | /mapper.py | 582 | 3.6875 | 4 | #!/usr/bin/env python
import sys
total = 0
green = 0
# input comes from STDIN (standard input)
for line in sys.stdin:
line = line.strip()
rgb = line.split(',')
# print '%s\t%d' % ("green", 100)
if len(rgb) > 0:
r, g, b = rgb
total += 1
if int(g) > int(r) and int(g) > int(b):
# print '%s\t%d' % ("green", 100)
green += 1
# if total == 0 :
# # print(1)
# print '%s\t%d' % ("green", 1)
if total != 0:
print '%s\t%f' % ("green", float(green) / float(total))
# print (float(green) / float(total))
|
b78580ba071016af237dcd90668bb1fb3412f6aa | aaronbae/competitive | /kickstart/contention.py | 1,588 | 3.578125 | 4 | class Interval:
def __init__(self, l, r):
self.left = l
self.right = r
def length(self):
return r-l
class Organizer:
def __init__(self, num, book):
self.data = {}
self.N = num
self.Q = book
def add(self, interval):
if interval.length() not in self.data:
self.data[interval.length()] = []
self.data[interval.length()].append(interval)
def calculate(self):
curr_min = self.N
seats = set()
keys = list(self.data.keys())
keys.sort()
for length in keys:
intervals = self.data[length]
for i in intervals:
def solve(N, Q, LR):
# Step 1: group by subset
# Step 2: merge the subsets two at a time
return 0
def main():
'''
# Standard input reading scheme
t = int(input()) # read a line with a single integer
for i in range(1, t + 1):
N, Q = map(int, input().split())
LR = []
for _ in range(1, Q+1):
N, Q = map(int, input().split())
LR.append([N,Q])
val = solve(N, Q, LR)
print("Case #{}: {}".format(i, val))
'''
# Custom Testing
a = [[1, 2],
[3, 4],
[2, 5]]
val = solve(5, 3, a)
print("Case 1: {}".format(val))
b = [[10, 11],
[10, 10],
[11, 11]]
val = solve(30, 3, b)
print("Case 2: {}".format(val))
c = [[1, 8],
[4, 5],
[3, 6],
[2, 7]]
val = solve(10, 4, c)
print("Case 3: {}".format(val))
main()
|
cb2f3a53e0040a7dd242532601d1b6398f1b907e | Infero93/advent-of-code-2019 | /6/script_1.py | 1,116 | 3.84375 | 4 | def read_input():
values = []
with open('6/input.txt', 'r') as f:
values = f.readlines()
return [value.strip() for value in values]
def count_steps(dest_planet, start_planet, orbits, count = 0):
if dest_planet == start_planet:
return count
planets = orbits[start_planet]
if len(planets) == 0:
return 0
for planet in planets:
new_count = count_steps(dest_planet, planet, orbits, count + 1)
if new_count and new_count > 0:
return new_count
return 0
values = read_input()
orbits = {}
planets = set()
for value in values:
planet1, planet2 = value.split(')')
if planet1 not in orbits:
orbits[planet1] = set()
if planet2 not in orbits:
orbits[planet2] = set()
orbits[planet1].add(planet2)
planets.add(planet1)
planets.add(planet2)
count = 0
start_planet = 'COM'
for dest_planet in planets:
result = count_steps(dest_planet, start_planet, orbits)
print(f"From {start_planet} to reach {dest_planet} it takes {result} steps")
count += result
print(f"Overall steps: {count}") |
d897c1579a483432d6d82e1a0186d59b77748e71 | gitchaussette/test-git | /1910/script1910.py | 116 | 3.515625 | 4 | given_list = [1,5,4,7,8,7,4,1,2,6,4,7,]
comprehension_list = [x for x in given_list]
print(comprehension_list) |
dd7269499f3a5059d5d1d96f50d456d981c850b8 | rodrigohuila/python_scripts | /MyScripts/sendEmail2.py | 3,950 | 3.546875 | 4 | #! /usr/bin/python3
import os, email, smtplib, ssl
from email import encoders
from email.mime.base import MIMEBase
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
# Capturing some info from user
subjectEmail = "An email with attachment from Python"
fromAddr = "rodrigo.huila@gmail.com"
toAddr = "rodrigo.huila@gmail.com" #input(\nWrite the recipient email (PARA)')
password = input("\nWrite the password or passcode (CONTRASEÑA):\n")
#Create a multipart message and set headers
message = MIMEMultipart("alternative")
message["From"] = fromAddr
message["To"] = toAddr
message["subject"] = subjectEmail
# Create the plain-text and HTML version of your message
text = """\
Hi,
How are you?
Real Python has many great tutorials:
www.realpython.com"""
html = """\
<html>
<body>
<p>Buen día,<br><br><br>
Cordial saludo,<br>
<a href="http://www.realpython.com">Real Python</a>
has many great tutorials.<br><br><br>
Rodrigo Huila<br>
Planificador
</p>
<br>
<div style="border: 1px solid rgba(37, 201, 255,.5); display: inline-block; border-radius: 3px;">
<table style="font-family: arial; height:90px; border-collapse: collapse; border: ">
<tr>
<td style="padding: 7px">
<img src="https://www.google.com/s2/u/0/photos/public/AIbEiAIAAABECOaXmNbolOq56AEiC3ZjYXJkX3Bob3RvKig5MTEzMGE0M2ZhMTY2ZDg3ZjE2NmEzOWFmZjIwNGQwOWIxYjYzYjg2MAHDS1i3U-Un2c5uh0eEds7YWkFPFw"
alt=""
width="80"
height="80"
style="display:block; border-radius: 50%; margin-right: 7px; float: left"
>
<div style="width: 5px; height: 80px; background:#75c8fd; float: right">
</td>
<td style="vertical-align:top; padding:7px 14px 7px 3px">
<strong style="margin: 0; font-size:17px; color: rgba(40, 45, 49,.9); line-height: 24px; height: 24px; display:block">Hector Rodrigo Huila</strong>
<p style='font-size:12px; margin: 0px 0 6px; height: 30px'>
<span style="margin: 0; color: #666">Ingeniero Informático
</span>
<br>
<a href='https://ed.team' style="color: #0B2161; font-weight: bold">rodrigo.huila@gmail.com</a>
</p>
<div id="sociales" ></div>
</td>
</tr>
</table>
</body>
</html>
"""
#Turn these into plain/html MIMEText object
part1 = MIMEText(text, "plain")
part2 = MIMEText(html, "html")
# Add HTML/plain-text parts to MIMEMultipart message
# The email client will try to render the last part first
message.attach(part1)
message.attach(part2)
#Attachment
#Directorio donde esta el archivo de excel
os.chdir("/home/rodrigo/Downloads/Victoria")
filename = "DIPLOMAS CALI 18-07-2020 1.pdf"
# Open PDF file in binary mode
with open(filename, "rb") as attachment:
# Add file as application/octet-stream
# Email client can usually download this automatically as attachment
part = MIMEBase("application", "octet-stream")
part.set_payload(attachment.read())
# Encode file in ASCII characters to send by email
encoders.encode_base64(part)
# Add header as key/value pair to attachment part
part.add_header(
"Content-Disposition",
f"attachment; filename= {filename}",
)
# Add attachment to message and convert message to string
message.attach(part)
text = message.as_string()
# Log and Create secure connection with server and send email
context = ssl.create_default_context()
with smtplib.SMTP_SSL("smtp.gmail.com", 465, context=context) as server:
server.login(toAddr, password)
sendmailStatus = server.sendmail(
toAddr, fromAddr, message.as_string()
)
if sendmailStatus != {}:
print('There was a problem sending email to %s: %s' %
(toAddr, sendmailStatus))
else:
print('\nThe email to %s was sent correctly' % (toAddr))
#Disconnecting from the SMTP Server
#conn.quit()
|
4ccb1bda8088b4fababcebfb6dfef90fb3a02de2 | gowitz/canalisations | /cana.py | 7,983 | 3.53125 | 4 | # -*- coding: utf-8 -*-
# from math import *
import math
class Point:
def __init__(self, pid, x, y, z):
self.pid = pid
self.x = x
self.y = y
self.z = z
def getX(self):
return self.x
def getY(self):
return self.y
def getZ(self):
return self.z
def getID(self):
return self.pid
def info(self):
print("ID : " + str(self.pid) + "\n" \
"X : " + str(self.x) + "\n" \
"Y : " + str(self.y) + "\n" \
"Z : " + str(self.z))
class Chambre(Point):
def __init__(self, pid, x, y, z):
Point.__init__(self, pid, x, y, z)
def info(self):
print("ID : " + str(self.pid) + "\n" \
"X : " + str(self.x) + "\n" \
"Y : " + str(self.y) + "\n" \
"ZC : " + str(self.z[0])+ "\n" \
"ZR : " + str(self.z[1])+ "\n" \
"ZS : " + str(self.z[2]))
for i in range(len(self.z) - 3):
print("ZE" + str(i+1) + ": " + str(self.z[3+i]))
def getCC(self):
return self.z[0]
def getCR(self):
return self.z[1]
def getCS(self):
return self.z[2]
def getCE(self, e):
if len(self.z) > 3 and 3 + e <= len(self.z):
return self.z[2 + e]
else:
return
class Troncon():
def __init__(self, chd, cha, e, diam, mat):
self.chd = chd # chambre depart [chambre]
self.cha = cha # chambre arrive [chambre]
self.e = e # entree dans chambre arrivee [integer]
self.diam = diam # diametre [integer]
self.mat = mat # materiaux [string]
def getLength(self):
return math.sqrt(((self.chd.getX() - self.cha.getX()) ** 2) + ((self.chd.getY() - self.cha.getY()) ** 2))
def getSlope(self):
return (self.chd.getCS() - self.cha.getCE(self.e)) / self.getLength() * 100
def getDiametre(self):
return str(self.diam)
def getMaterial(self):
return str(self.mat)
def setDiametre(self, diam):
self.diam = diam
def setMaterial(self, mat):
self.mat = mat
def getTextAngle(self):
deltaX = self.chd.getX() - self.cha.getX()
deltaY = self.chd.getY() - self.cha.getY()
if deltaX != 0:
return math.atan(( deltaY / deltaX ) / (2 * math.pi * 360))
else:
return 90
def getDirection(self):
if self.cha.getX() > self.chd.getX():
return "d"
elif self.cha.getX() == self.chd.getX() and self.cha.getY() > self.chd.getY():
return "d"
else:
return "g"
def info(self):
longueur = ("%.2f" % self.getLength
())
pente = ("%.2f" % self.getSlope())
sens = self.getDirection()
mat = self.getMaterial()
diam = self.getDiametre()
prefixe = ''
sufixe = ''
if sens == 'd':
sufixe = ' -->'
else:
prefixe = '<-- '
print(prefixe + mat + " ∅" + diam + " / L=" + longueur + "m / i=" + pente + "%" + sufixe)
def calculateLength(pd, pa):
if not type(pd) is Chambre or not type(pa) is Chambre:
raise TypeError("Only Chambre are allowed")
return math.sqrt(((pd.getX() - pa.getX()) ** 2) + ((pd.getY() - pa.getY()) ** 2))
def calculateSlope(pd, pa, e):
if not type(pd) is Chambre or not type(pa) is Chambre:
raise TypeError("Only Chambre are allowed")
if not type(e) is int:
raise TypeError("Only Int are allowed")
return (pd.getCS() - pa.getCE(e)) / calculateLength(pd, pa) * 100
def calculateTextAngle(pd, pa):
if not type(pd) is Chambre or not type(pa) is Chambre:
raise TypeError("Only Chambre are allowed")
deltaX = pd.getX() - pa.getX()
deltaY = pd.getY() - pa.getY()
if deltaX != 0:
return math.atan(( deltaY / deltaX ) / (2 * math.pi) * 360)
else:
return 90
"""
def calculateTextAngle(pd, pa):
a = calculeAngleDeg(pd, pa)
if pa.getX() > pd.getX():
if pa.getY() > pd.getY():
at = a
else:
at = 360 - a
else:
if pa.getY() > pd.getY():
at = 180 - a
else:
at = 180 + a
if at > 90 and at <= 270:
at = at-180
return at
"""
def defineDirection(pd, pa):
if not type(pd) is Chambre or not type(pa) is Chambre:
raise TypeError("Only Chambre are allowed")
if pa.getX() > pd.getX():
return "d"
elif pa.getX() == pd.getX() and pa.getY() > pd.getY():
return "d"
else:
return "g"
def infoTroncon(pd, pa, e):
if not type(pd) is Chambre or not type(pa) is Chambre:
raise TypeError("Only Chambre are allowed")
if not type(e) is int:
raise TypeError("Only Int are allowed")
length = calculateLength(pd, pa)
slope = calculateSlope(pd, pa, e)
direction = defineDirection(pd, pa)
prefix = ''
sufix = ''
if direction == 'd':
sufix = ' -->'
else:
prefix = '<-- '
return prefix + "L=" + str(round(length,3)) + "m / i=" + str(round(slope,2)) + "%" + sufix
""" ****************************************************************************
DATA
**************************************************************************** """
p1 = Point('ch1', 542665.593, 151723.232, 557.37)
p2 = Point('ch2', 542627.071, 151711.858, 558.12)
ch1 = Chambre('44', 542665.593, 151723.232, [0, 557.37, 557.37])
ch2 = Chambre('43A', 542627.071, 151711.858, [558.12, 556.57, 556.57, 558.12])
ch3 = Chambre('45', 542674.80, 151707.27, [558.73, 556.95, 556.95, 558.73])
ch4 = Chambre('71', 542240.29, 151638.15, [550.20, 547.99, 547.99, 548])
ch5 = Chambre('72', 542209.70, 151638.38, [549.89, 547.62, 547.62, 547.64])
ch6 = Chambre('74', 542203.31, 151643.88, [549.70, 547.50, 547.50, 547.66, 547.54])
ch7 = Chambre('93', 542191.71, 151668.17, [550.15, 548.35, 548.35, 549.03,548.4])
ch8 = Chambre('94', 542236.28, 151664.04, [551.30, 549.25, 549.25, 549.34, 549.34])
ch9 = Chambre('12A', 542326.06, 151638.34, [551.45, 549.27, 549.27, 551.45, 551.45])
ch10 = Chambre('12ext2', 542186.03, 151680.95, [553.56, 552.56, 552.56, 552.6])
ch11 = Chambre('12ext3', 542149.05, 151690.17, [555.17, 554.17, 554.17, 554.14])
ch12 = Chambre('12ext4', 542190.20, 151674.40, [553.42, 552.42, 552.42, 552.44])
ch13 = Chambre('12ext6', 542123.83, 151700.77, [0.00, 555.00, 555.00])
ch14 = Chambre('14A', 542328.11, 151667.21, [0.00, 550.73, 550.73])
ch100 = Chambre('100', 0, 0, [7, 5, 5])
ch101 = Chambre('101', 5, 0, [2, 0, 0, 0])
ch102 = Chambre('102', 5, 5, [2, 0, 0, 0])
ch103 = Chambre('103', 0, 5, [2, 0, 0, 0])
ch104 = Chambre('104', -5, 5, [2, 0, 0, 0])
ch105 = Chambre('105', -5, 0, [2, 0, 0, 0])
ch106 = Chambre('106', -5, -5, [2, 0, 0, 0])
ch107 = Chambre('107', 0, -5, [2, 0, 0, 0])
ch108 = Chambre('108', 5, -5, [2, 0, 0, 0])
troncons = []
troncons.append(Troncon(ch100, ch101, 1, 500, 'PVC'))
troncons.append(Troncon(ch100, ch102, 1, 400, 'PVC'))
troncons.append(Troncon(ch100, ch103, 1, 350, 'PVC'))
troncons.append(Troncon(ch100, ch104, 1, 315, 'PVC'))
troncons.append(Troncon(ch100, ch105, 1, 300, 'PVC'))
troncons.append(Troncon(ch100, ch106, 1, 250, 'PVC'))
troncons.append(Troncon(ch100, ch107, 1, 200, 'PVC'))
troncons.append(Troncon(ch100, ch108, 1, 150, 'PVC'))
""" ****************************************************************************
TEST
**************************************************************************** """
print(infoTroncon(ch100, ch101, 1) + '\t\t' + str(calculateTextAngle(ch100, ch101)))
print(infoTroncon(ch100, ch102, 1) + '\t\t' + str(calculateTextAngle(ch100, ch102)))
print(infoTroncon(ch100, ch103, 1) + '\t\t' + str(calculateTextAngle(ch100, ch103)))
print(infoTroncon(ch100, ch104, 1) + '\t\t' + str(calculateTextAngle(ch100, ch104)))
print(infoTroncon(ch100, ch105, 1) + '\t\t' + str(calculateTextAngle(ch100, ch105)))
print(infoTroncon(ch100, ch106, 1) + '\t\t' + str(calculateTextAngle(ch100, ch106)))
print(infoTroncon(ch100, ch107, 1) + '\t\t' + str(calculateTextAngle(ch100, ch107)))
print(infoTroncon(ch100, ch108, 1) + '\t\t' + str(calculateTextAngle(ch100, ch108)))
troncons[7].setDiametre(500)
troncons[7].setMaterial('PE')
for t in troncons:
t.info()
ch100.info()
"""
longueur = calculateLength(p1, p2)
pente = calculateSlope(p1, p2)
azi = calculeAngleDeg(p1, p2)
angleTexte = calculeAngleTexte(p1, p2)
p1.getInfo()
print
p2.getInfo()
print
print defineDirection(p1, p2) + "L=" + str(round(longueur,3)) + "m / i=" + str(round(pente,2)) + "%"
print azi
print angleTextedifineDirection
difineDirection
"""
|
5c74963c69fa6f36415c858bddb1f6790c105f3a | Nampq281/phamquynam-fundamentals-c4e21 | /session03/homework03/serious2.1_4.py | 477 | 3.8125 | 4 |
flock_sheep = [5, 7, 300, 90, 24, 50, 75]
print ("Hello, my name is Nam, and here are my ship sizes ", flock_sheep)
biggest = max(flock_sheep)
print ("Now my biggest sheep has size ", biggest, "let's sheer it")
sheep_no = flock_sheep.index(biggest)
flock_sheep[sheep_no] = 8
print ("After sheering, here is my flock ", flock_sheep)
growth = 50
for i in range(len(flock_sheep)):
flock_sheep[i] += growth
print ("One month has passed, now here is my flock ", flock_sheep) |
50aa6de0884b1432515833a7c6b8560a37afbdc5 | gitter-badger/survival-python | /07 Data Types Details/integers_and_floats_2.py | 254 | 3.546875 | 4 | a = int(2.8)
b = int('2')
# Not supported int('2.8') would return an error
c = float('2')
d = float('2.1')
e = float(2)
f = int(float('2.8'))
print(a, type(a))
print(b, type(b))
print(c, type(c))
print(d, type(d))
print(e, type(e))
print(f, type(f))
|
6e820ab8a69f7003e387c0b12af40c35178f2ca1 | buidler/LeetCode | /二分查找/1111. 有效括号的嵌套深度.py | 1,358 | 3.65625 | 4 | """
示例 1:
输入:seq = "(()())"
输出:[0,1,1,1,1,0]
示例 2:
输入:seq = "()(())()"
输出:[0,0,0,1,1,0,1,1]
解释:本示例答案不唯一。
按此输出 A = "()()", B = "()()", max(depth(A), depth(B)) = 1,它们的深度最小。
像 [1,1,1,0,0,1,1,1],也是正确结果,其中 A = "()()()", B = "()", max(depth(A), depth(B)) = 1 。
"""
class Solution(object):
def maxDepthAfterSplit(self, seq):
"""
:type seq: str
:rtype: List[int]
"""
res = []
if not seq:
return res
depth, max_depth = 0, 0
for ch in seq:
if ch == "(":
depth += 1
if depth > max_depth:
max_depth = depth
else:
depth -= 1
a_depth = 0
mid = 1 + (max_depth-1)//2
for ch in seq:
if ch == "(":
if a_depth < mid:
res.append(0)
a_depth += 1
else:
res.append(1)
else:
if a_depth > 0:
res.append(0)
a_depth -= 1
else:
res.append(1)
return res
if __name__ == '__main__':
solution = Solution()
print(solution.maxDepthAfterSplit(seq="(()())"))
|
6f1d38474e51fd597359e78ee2ca46b6c17927bc | jszandula/JetBrains-Academy-Projects | /coffee_loop.py | 3,435 | 4 | 4 | class CoffeMachine():
def __init__(self):
self.water = 400
self.milk = 540
self.beans = 120
self.cups = 9
self.money = 550
def user_interaction(self, action = str(input("Write action (buy, fill, take, remaining, exit) : "))
):
while action != 'exit':
if action == 'buy':
self.buy()
elif action == 'fill':
self.fill()
elif action == 'take':
self.take()
else:
self.remaining()
action = str(input("Write action (buy, fill, take, remaining, exit) : "))
exit()
def buy(self):
which_coffee = input("What do you want to buy? 1 - espresso, 2 - latte, 3 - cappuccino, back to main menu: ")
if which_coffee == 'back':
self.user_interaction(action = str(input("Write action (buy, fill, take, remaining, exit) : ")))
elif int(which_coffee) == 1:
if self.water < 250:
print("Sorry, not enough water!")
elif self.beans < 16:
print("Sorry, not enough coffee beans!")
else:
print("I have enough resources, making you a coffee!")
self.water -= 250
self.beans -= 16
self.money += 4
self.cups -= 1
elif int(which_coffee) == 2:
if self.water < 350:
print("Sorry, not enough water!")
elif self.milk < 75:
print("Sorry, not enough milk!")
elif self.beans < 20:
print("Sorry, not enough coffee beans!")
else:
print("I have enough resources, making you a coffee!")
self.water -= 350
self.milk -= 75
self.beans -= 20
self.money += 7
self.cups -= 1
else:
if self.water < 200:
print("Sorry, not enough water!")
elif self.milk < 100:
print("Sorry, not enough milk!")
elif self.beans < 12:
print("Sorry, not enough coffee beans!")
else:
print("I have enough resources, making you a coffee!")
self.water -= 200
self.milk -= 100
self.beans -= 12
self.money += 6
self.cups -= 1
def fill(self):
self. add_water = int(input("Write how many ml of water do you want to add: "))
self.add_milk = int(input("Write how many ml of milk do you want to add: "))
self.add_beans = int(input("Write how many grams of coffee beans do you want to add: "))
self.add_cups = int(input("Write how many disposable cups of coffee do you want to add: "))
self.water += self.add_water
self.milk += self.add_milk
self.beans += self.add_beans
self.cups += self.add_cups
def take(self):
print("I gave you $" + str(self.money))
self.money = 0
def remaining(self):
print("The coffee machine has:")
print(str(self.water) + " of water")
print(str(self.milk) + " of milk")
print(str(self.beans) + " of coffee beans")
print(str(self.cups) + " of disposable cups")
print("$" + str(self.money) + " of money")
print()
coffee = CoffeMachine()
coffee.user_interaction() |
edd815175fb97fdec8e4139b235be01be6810415 | m2rik/MLprojects | /SVM/SVMsklearn.py | 1,793 | 3.671875 | 4 | #classification algorithm
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
#dataset problem- classify whether the person will purchase a product or not
#age/salary independent,purchase is the dependent variable
D=pd.read_csv("Social_Network_Ads.csv")
X=D.iloc[:,[2,3]].values
y=D.iloc[:,4].values#depedent variable
#maybe curved or linear line for classification
from sklearn.cross_validation import train_test_split
X_train,X_test,y_train,y_test=train_test_split(X,y,test_size=0.25,random_state=0)
from sklearn.preprocessing import StandardScalar
sc=StandardScalar() #feature scaling[-2,+2]
X_train=sc.fit_transform(X_train)
X_test=sc.transform(X_test)
Classfier=SVC(kernel='linear',random_state=0)
Classfier.fit(X_train,y_train)
y_pred=Classfier.predict(X_test)
from sklearn.metrics import confusion_matrix
cm=confusion_matrix(y_test,y_pred)
#visualizing the SVM KERNELS
from matplotlib.colors import ListedColormap
X_set,y_set = X_test,y_test
X1,X2=np.meshgrid(np.arange(start=X_set[:,0].min()-1, stop = X_set[:,0].max()+1,step=0.01),
np.arange(start=X_set[:,1].min()-1, stop = X_set[:,1].max()+1,step=0.01))
plt.contour(X1,X2,Classfier.predict(np.array([X1.ravel(),X2.ravel()]).T).reshape(X1.shape),
alpha=0.75,cmap=ListedColormap(('red','green')))
plt.xlim(X1.min(),X1.max())
plt.ylim(X2.min(),X2.max())
for i,j in enumerate(np.unique(y_set)):
plt.scatter(X_set[y_set==j,0],X_set=[y_set==j,1],
c=ListedColormap(('red','green'))(1),label=j)
plt.title('SVM (test set)')
plt.xlabel('age')
plt.ylabel('Estimated Salary')
plt.legend()
plt.show()
#also we can create a sample dataset by...
from sklearn.datasets import make_classification
X,y=make_classification(n_samples=1000,n_features=20,n_informative=8,n_redundant=3,n_repeated=2,random_state=seed) |
bf15138e810cbffc17fdcbbacba14bb1a8b5ff61 | muralweirdo/PF-codes | /a03.py | 804 | 3.921875 | 4 | ## IMPORTS GO HERE
## END OF IMPORTS
#### YOUR CODE FOR good_enough() FUNCTION GOES HERE ####
def good_enough (n,g):
if abs(g*g-n) < 0.1:
return True
else:
return False
#### End OF MARKER
#### YOUR CODE FOR sqrt() FUNCTION GOES HERE ####
def sqrt (n,g=0):
count=1
if good_enough(n,g):
return (g)
else:
g = improve_guess(n,g)
count=count+1
a = sqrt(n,g)
print("Took: ",count," steps")
return a
#### End OF MARKER
#### YOUR CODE FOR improve_guess() FUNCTION GOES HERE ####
def improve_guess (n,g):
if g==0:
g=g+0.1
g = g-( ((g*g)-n)/(2*g) )
return g
else:
g = g-( ((g*g)-n)/(2*g) )
return g
#### End OF MARKER
if __name__ == '__main__':
print(sqrt(36))
|
55bfaead7a57bff5c4cd582146d995353696e53f | panu2306/Python-Articles | /programs_in_python/programming_excercise/4.py | 523 | 4.3125 | 4 | '''
Write a program which accepts a sequence of comma-separated numbers from console and generate a list and a tuple which contains every number.
Suppose the following input is supplied to the program:
34,67,55,33,12,98
Then, the output should be:
['34', '67', '55', '33', '12', '98']
('34', '67', '55', '33', '12', '98')
'''
def generate_list_and_tuple(input):
l = [i for i in input.split(',')]
t = tuple(l)
return l, t
l, t = generate_list_and_tuple('34,67,55,33,12,98')
print("List: {}\nTuple: {}".format(l, t))
|
ad9b8de4db681f2b8395420446c21f8d5a3c0936 | RashiSinghvi/CIPHERSCHOOLS_ASSIGNMENTS | /web app/Adult project/adult_data.py | 5,780 | 3.75 | 4 | import streamlit as st
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
def load_sidebar():
st.sidebar.header("Income Prediction of a person using given dataset")
st.sidebar.info('''
1) Original owners of database - US Census Bureau\n
2) Donor of database - Ronny Kohavi and Barry Becker\n
''')
st.sidebar.info('''
1) 48842 instances, mix of continuous and discrete (train=32561, test=16281)\n
2) 45222 if instances with unknown values are removed (train=30162, test=15060)\n
''')
st.sidebar.warning("not perform Data Modelling Step, So we can predict income now, but I show Data Visualization\
so we can do Data Analysis")
st.sidebar.warning("Not Able to write any observations")
def load_dataset():
df=pd.read_csv("adult.csv",na_values=['?','-','n/a'])
return df
def drop_unn_data(df):
st.header("Treatment of missing value and Uneccessary data ")
df.dropna(axis=0,how='any',inplace=True)
miss_per=(1-len(df.index)/48842)*100
st.write("{}% missing value remove from dataset".format(round(miss_per,2)))
st.write("Two Columns 'fnlwgt','educational-num' remove from datset")
df.drop(['fnlwgt','educational-num'],axis=1,inplace=True)
return df
def stat_desc(df):
st.header("Statistcal Analysis of Data After Removing Missing Values")
st.subheader("Show Upper 5 row and bottom 5 row data")
choice=st.radio("Select one option: ",('Top','Bottom'))
if choice=='Top':
st.table(df.head())
else:
st.table(df.tail())
st.subheader(" Apply Some Statistcal Functions")
select=st.selectbox("Select from option below: ",('describe','info','shape','rows','columns'))
if select=='describe':
ch=st.radio("describe one of them: ",('numerical','categorial'))
if ch=='numerical':
st.write(df.describe(include='number'))
else:
st.write(df.describe(include='object'))
elif select=='info':
st.write(df.info())
elif select=='shape':
st.write(df.shape)
elif select=='rows':
st.write("Number of rows in dataset is: ",df.shape[0])
elif select=='columns':
st.write("Number of columns in dataset is: ",df.shape[1])
def data_viz(df):
st.header("Data Visualization")
choice=st.radio("Types of Analysis: ",("Univariant","Bivariant"))
if choice=='Univariant':
select=st.radio("Select any of them: ",('Numerical','Categorial'))
if select=='Numerical':
st.text("Histogram For Numerical Data")
num_df=df.select_dtypes(include='number')
num_df.hist(figsize=(10,10))
st.pyplot()
elif select=='Categorial':
st.text("Countplot for categorial Data")
cat_df=df.select_dtypes(include='object')
plt.figure(figsize=(12,24))
plt.subplots_adjust(hspace=1,wspace=1)
plt.subplot(411)
sns.countplot(x='workclass', hue='income', data = cat_df)
plt.title('Income vs Work Class')
plt.subplot(412)
sns.countplot(x='occupation', hue='income', data = cat_df)
plt.xticks(rotation=90)
plt.title('Income vs Occupation')
plt.subplot(413)
sns.countplot(x='education', hue='income', data=cat_df)
plt.xticks(rotation=90)
plt.title('Income vs Education')
plt.subplot(414)
sns.countplot(x='marital-status', hue='income', data=cat_df)
plt.xticks(rotation=90)
plt.title('Income vs Marital Status')
st.pyplot()
st.subheader("Observations 1.0")
if(st.checkbox("Observations of Univariant Analysis: ")):
st.write('''
1) Most of age lie blw 30-50\n
2) Majority of Capital gain lie blw 0-10000\n
3) Majority of Capital loss lie blw 0-5000\n
4) averge working hours per week is in range 35-40\n
5) Most of the people are belong to private sector\n
6) Most people having salary less than 50K are HS graduate\n
7) People who earn income greater than 50K are married-civ-spouse\n
''')
elif choice=='Bivariant':
ch=st.selectbox("Different Representation: ",('Graphical','Tabular'))
if ch=='Graphical':
st.text("Income v/s Age")
sns.boxplot(data=df,x='income',y='age',hue='gender')
st.pyplot()
st.text("Income v/s Hours-per-week")
sns.boxplot(data=df,x='income',y='hours-per-week',hue='gender')
st.pyplot()
plt.figure(figsize=(12,12))
st.text("Age v/s Occupation")
sns.boxplot(data=df,x='occupation',y='age',hue='income')
plt.xticks(rotation=90)
st.pyplot()
elif ch=='Tabular':
df['income_category'] = "null"
df.loc[df['income'] == '>50K', ['income_category']] = 'high income'
df.loc[df['income'] == '<=50K', ['income_category']] = 'low income'
st.text("Income v/s Race Pivot Table Representation")
racewise_income_dist = df.pivot_table(values=['income_category'],index=['income', 'race'],aggfunc = 'count')
st.table(racewise_income_dist)
st.text("Income v/s Gender Pivot Table Representation")
gender_income_dist = df.pivot_table(values=['income_category'],index=['income', 'gender'],aggfunc = 'count')
st.table(gender_income_dist)
st.text("Income v/s Relationship Pivot Table Representation")
rels_income_dist = df.pivot_table(values=['income_category'],index=['income', 'relationship'],aggfunc = 'count')
st.table(rels_income_dist)
st.text("Income v/s Occupation Pivot Table Representation")
occs_income_dist = df.pivot_table(values=['income_category'],index=['income', 'occupation'],aggfunc = 'count')
st.table(occs_income_dist)
def main():
st.header("Adult Dataset project: Predict Income of Person using his/her data \n\n")
load_sidebar()
df=load_dataset()
st.write(df.head())
new_df=drop_unn_data(df)
stat_desc(new_df)
data_viz(new_df)
if(__name__=='__main__'):
main() |
5e6c18ff67bdeaf57d24e8b1b2a83461dd486d0c | jesusble/project | /bb.py | 170 | 3.546875 | 4 | s=input()
b=0
a=0
for w in s:
if(w.isalpha()==True):
a=a+1
elif(w.isdigit()==True):
b=b+1
if(a>0 and b>0):
print("Yes")
else:
print("No")
|
7746a64ff6372e44a08d656c8bd8796a481b4ecd | werellel/Algorithm | /hackerrank/warm_up_challenges/counting_valleys.py | 2,380 | 3.734375 | 4 | #!/bin/python3
import math
import os
import random
import re
import sys
# Complete the countingValleys function below.
def countingValleys(n, s):
if s[0] == 'U':
result_list = [(0, '_')]
compare_pos = -1
else:
result_list = [(1, '_')]
compare_pos = 0
position = 0
change = '-'
p_max = 0
p_min = 0
valley_count = 0
for i in s:
if i == 'U':
if i == change:
position += 1
else:
change = i
if position == compare_pos:
valley_count += 1
result_list.append((position, '/'))
else:
if i == change:
position -= 1
else:
change = i
result_list.append((position, '\\'))
if position > p_max:
p_max = position
if position < p_min:
p_min = position
return valley_count
if __name__ == '__main__':
n = 8
s = 'UDDDUDUU'
result = countingValleys(n, s)
print(result)
# Visualize the countingValleys
def visualize_countingValleys(n, s):
if s[0] == 'U':
result_list = [(0, '_')]
compare_pos = -1
else:
result_list = [(1, '_')]
compare_pos = 0
position = 0
change = '-'
p_max = 0
p_min = 0
valley_count = 0
for i in s:
if i == 'U':
if i == change:
position += 1
else:
change = i
if position == compare_pos:
valley_count += 1
result_list.append((position, '/'))
else:
if i == change:
position -= 1
else:
change = i
result_list.append((position, '\\'))
if position > p_max:
p_max = position
if position < p_min:
p_min = position
if s[-1] == 'U':
result_list.append((0, '_'))
else:
result_list.append((1, '_'))
str_list = [' '*(n+2) for i in range(p_max-p_min+1)]
for index, row in enumerate(result_list):
str_list[p_max - row[0]] = str_list[p_max - row[0]][:index] + row[1] + str_list[p_max - row[0]][index+1:]
result = ''
for i in str_list:
result = result + i + '\n'
return result
|
393012f0ea721e755bb07b750c7a51c497ddd601 | snufkinpl/public_glowing_star | /Countdown app/Countdown app_in_1_file/Countdown app.py | 1,097 | 3.953125 | 4 | #Wytyczne projektu
#Użytkownik wprowadza nazwę celu oraz czas na jego osiągnięcie poprzez podanie daty w postaci:yyyy-mm-dd
#Na ekranie pojawia się informacja, ile czasu pozostało na osiągnięcie celu (w dniach)
import datetime
def information_from_user():
user_input = input("Wprowadź nazwę celu oraz jego końcową datę w postaci yyyy-mm-dd. Nazwę celu oraz datę oddziel dwukropkiem.\n")
list_of_user_input = user_input.split(":")
goal = list_of_user_input[0]
deadline = list_of_user_input[1]
user_date = datetime.date(int(deadline[0:4]), int(deadline[5:7]), int(deadline[8:10]))
return user_date, goal
def time_manipulation_and_execute(user_data):
user_date = user_data[0]
goal = user_data[1]
date_difference = user_date - datetime.date.today()
date_difference = date_difference.days
print(f"Użytkowniku, do osiągnięcia Twojego celu: {goal}, zostało Ci {date_difference} dni.")
def main():
#information_from_user()
time_manipulation_and_execute(user_data=information_from_user())
main()
|
f51dd563efe2f74b53bf6bbf09dff3db13be00f1 | Amiao-miao/all-codes | /month01/day11/homework01.py | 1,636 | 4.34375 | 4 | """
以面向对象的思想,描述下列情景.
划分原则:
数据不同使用对象区分——小王
行为不同使用类区分——手机/卫星电话
"""
# (1)需求:小明使用手机打电话
# 识别对象:人类 手机
# 分配职责:打电话 通话
# 建立交互:人类 调用 手机
"""
class People:
def __init__(self, name=""):
self.name=name
def use(self,phone):
print(self.name,"使用")
phone.call()
class Phone:
def call(self):
print("打电话")
xiaoming=People("小明")
phone=Phone()
xiaoming.use(Phone())
"""
# (2)小明一次请多个保洁打扫卫生
# 效果:调用一次小明通知方法,可以有多个保洁在打扫卫生.
class People:
def __init__(self, name=""):
self.name=name
def engage(self,*args):
print(self.name,"雇佣")
for cleaner in args:
cleaner.cleaning()
class Cleaner:
def cleaning(self):
print("打扫卫生")
xiaoming=People("小明")
xiaoming.engage(Cleaner(),
Cleaner(),
Cleaner() )
# (3)张无忌教赵敏九阳神功
# 赵敏教张无忌玉女心经
# 张无忌工作挣了5000元
# 赵敏工作挣了10000元
"""
class Person:
def __init__(self,name=""):
self.name=name
def teach(self,other,skill):
print(self.name,"在教",other.name,skill)
def work(self,money):
print(self.name,"上班赚了",money,"元")
zm=Person("赵敏")
zwj=Person("张无忌")
zwj.teach(zm,"九阳神功")
zm.teach(zwj,"玉女心经")
zwj.work(5000)
zm.work(10000)
"""
|
adeac0244ac4850d573159353f9efb0e2ea6a928 | jinhongtan/calculator3 | /src/StatisticsCalc.py | 1,945 | 3.78125 | 4 | from Calculator import *
import collections
import sys
import math
class StatisticCalculator(Calculator):
#check the list is valid
# 1. not string
# 2. not empty
@staticmethod
def check(data):
if not all(isinstance(item,int) for item in data) or len(data)==0:
print("Your data include string type or is empty,please give valid data")
sys.exit()
# calculate mean of the list
@staticmethod
def mean(data):
StatisticCalculator.check(data)
Calc1=Calculator()
sum = 0
for x in data:
sum= Calc1.addition(x,sum)
return float(sum/len(data))
# calculate median of the list
@staticmethod
def median(data):
StatisticCalculator.check(data)
num_sorted = sorted(data)
length = len(num_sorted)
if length % 2 != 0:
return num_sorted[int(length/2)]
else:
return (num_sorted[int(length/2)]+num_sorted[int((length/2)-1)])/2
# calculate mode of the list
@staticmethod
def mode(data):
StatisticCalculator.check(data)
num = []
tuple = collections.Counter(data).most_common()
num.append(tuple[0][0])
for i in range(len(tuple) - 1):
if tuple[i][1] == tuple[i + 1][1]:
num.append(tuple[i + 1][0])
else:
break
return num
# calculate variance of the list
@staticmethod
def variance(data):
StatisticCalculator.check(data)
average=StatisticCalculator.mean(data)
res = sum((i - average) ** 2 for i in data) / (len(data)-1)
return res
# calculate standard variation of the list
@staticmethod
def stdvar(data):
StatisticCalculator.check(data)
average = StatisticCalculator.mean(data)
res = sum((i - average) ** 2 for i in data) / (len(data)-1)
return math.sqrt(res)
|
9cfef1268648f1a5fdbabec4776d900793dd8a77 | dexterchan/DailyChallenge | /Jan2020/LongestConsecutiveSequence.py | 3,183 | 3.921875 | 4 | #You are given an array of integers. Return the length of the longest consecutive elements sequence in the array.
#For example, the input array [100, 4, 200, 1, 3, 2] has the longest consecutive sequence 1, 2, 3, 4, and thus, you should return its length, 4.
#Can you do this in linear time?
#Anaysis
#Sorting costs O(NlogN) , no good
# to archieve linear time, we need a linked list. creating double linked list on-the-fly of sorted number when scanning the array
# iterate the array
# create prev dict and next dict
# for each element, create a double linked node, say number 100
# insert 99->(node 100) into next dict
# insert 101 -> (node 100) into pre dict
# for next element, say 99 , find (node 100) in next dict,
# (node 99).next = (node 100), (node 99).prev = (node 100).prev, (node 99).prev.next = (node 99) , assign (node 100).prev to (node 99)
# also check 98 in prev dict, if not found , insert 98 -> (node 99) into prev dict
# in the end, we iterate double linked list, to find the longest consecutive sequence by O(N)
class dbNode:
def __init__(self, val=None, prev=None, next=None ):
self.val = val
self.prev = prev
self.next = next
def insert(self, node1, node2):
tmpNode = node1.next
node1.next = node2
node2.prev = node1
if tmpNode is not None:
tmpNode.prev = node2
node2.next = tmpNode
def __str__(self):
s = ""
n = self
while n is not None:
s = s + "," + str(n.val)
n = n.next
return str
class Solution:
def longest_consecutive(self, nums):
prevDict = {}
nextDict = {}
anchor = []
for n in nums:
node = dbNode(n)
if n in prevDict:
pNode = prevDict[n]
dbNode().insert(pNode, node)
else:
dummy = dbNode(None)
dbNode().insert(dummy, node)
anchor.append(dummy)
self.__insertNextDict(nextDict, node)
if n in nextDict:
nNode = nextDict[n]
if nNode.prev.val != None:
dbNode().insert(nNode.prev, node)
else:
dbNode().insert(node, nNode)
else:
self.__insertPrevDict(prevDict, node)
maxLength = 0
maxSeq = None
for lt in anchor:
ptr = lt.next
l = 0
s = []
while ptr is not None:
l += 1
s.append(str(ptr.val))
ptr = ptr.next
if l > maxLength:
maxLength = l
maxSeq = ",".join(s)
return maxLength, maxSeq
def __insertPrevDict(self, prevDict, node):
prevDict[node.val + 1] = node
def __insertNextDict(self, nextDict, node):
nextDict[node.val - 1] = node
def longest_consecutive(nums):
# Fill this in.
solu = Solution()
return solu.longest_consecutive(nums)
if __name__ == "__main__":
print (longest_consecutive([100, 4, 200, 1, 3, 2]))
# 4
print(longest_consecutive([5, 100, 4, 200, 7, 1, 3, 2, 6])) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.