blob_id
stringlengths 40
40
| repo_name
stringlengths 6
108
| path
stringlengths 3
244
| length_bytes
int64 36
870k
| score
float64 3.5
5.16
| int_score
int64 4
5
| text
stringlengths 36
870k
|
---|---|---|---|---|---|---|
bbe45526e78a6c149ba67881a2b55243721b9d24 | Danilo-mr/Python-Exercicios | /Exercícios/ex041.py | 275 | 3.828125 | 4 | ano = int(input('Ano de Nascimento: '))
idade = 2020 - ano
print(f'{"CATEGORIA":=^20}')
if idade < 10:
print('MIRIM')
elif idade < 14:
print('INFANTIL')
elif idade < 19:
print('JUNIOR')
elif idade < 20:
print('SÊNIOR')
else:
print('MASTER')
|
ceb0b9e762fadd6d2931fe9e0f572f4df4f3e355 | rafael-larrazolo/ml-keras | /sesion_1/ej7-lineales.py | 254 | 3.578125 | 4 | #-*- coding: utf-8 -*-
import numpy as np
# A x = b
A = np.array([
[2, 3, 12],
[1, 1, 2],
[2, 0, 3]
])
b = np.array([
31,
9,
7
])
# x = A^-1 b
Ainv = np.linalg.inv(A)
x = np.matmul(Ainv, b)
print(x)
print(np.matmul(A, x)) |
83eeb25bd083c8470d2c68cca6879629122c2666 | keegangunkel/SoftwareTestingLab2 | /problem6.py | 893 | 4.3125 | 4 | ####################################################
#
# Keegan Gunkel
#
# Purpose to find the area of a trapezoid
#
####################################################
import math
def main():
print("-------------------------------------------------------------")
print("PYTHON PROGRAM TO FIND THE AREA OF A TRAPEZOID")
print("-------------------------------------------------------------")
base1 = eval(input("Please Enter the base1 :"))
base2 = eval(input("Please Enter the the base2 :"))
height = eval(input("Please Enter the height :"))
median = (base1 + base2) / 2
area = (median) * height
print()
print(" Area of a Trapezoid = ", round(area, 2))
print(" Median of a trapezoid = ", round(median, 2))
print("--------------------------------------------------------------")
if __name__ == '__main__':
main() |
e91fd58bb7b69c5db7ee1a3669cdb0c456decbf0 | meghakashyap/dictionary | /odd_and_even.py | 194 | 4.1875 | 4 | Input = {"a": 1, "b": 2, "c": 3, "d": 4, "e": 5}
for value in Input.values():
print(value)
if value%2==0:
print("even", value)
else:
print("odd")
#find even and odd
|
b2370a0114613876290ac4776210884920462eb9 | pcuste1/ProjectEuler | /prob5.py | 466 | 3.65625 | 4 | import math
def smallest(number):
for i in range(2, number):
if number % i == 0:
return smallest(number // i)
return number
def patvisor(list, total):
for i in list:
if(total % i != 0):
return patvisor(list, total * smallest(i))
return total
def main():
list = []
list.extend(range(1,int(input("Please enter the roof: "))))
total = patvisor(list,2)
print(total)
main()
|
950ee33e52e62a940861334f1a405c8156e9ca00 | justsolo-smith/-trie | /113.路径总和-ii.py | 981 | 3.625 | 4 | # @before-stub-for-debug-begin
from python3problem113 import *
from typing import *
# @before-stub-for-debug-end
#
# @lc app=leetcode.cn id=113 lang=python3
#
# [113] 路径总和 II
#
# @lc code=start
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def __init__(self):
self.res = 0
self.a = []
self.b = []
def pathSum(self, root: TreeNode, sum: int) -> List[List[int]]:
if not root:
return []
val = root.val
self.a.append(val)
self.res +=val
if sum==self.res and not root.left and not root.right:
self.b.append(self.a[:])
else:
self.pathSum(root.left,sum)
self.pathSum(root.right,sum)
self.res -= self.a[-1]
self.a.pop()
return self.b
# @lc code=end
|
fafe4f8a60a3ac26cffce2fbbca8df430470078e | juanoyarceg/Python-Ejercicios | /Python_EjerciciosCiclos/cuenta_regresiva.py | 470 | 3.578125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Mon May 13 19:43:56 2019
@author: JUAN
"""
"""cuenta_regresiva = int(input("Ingrese un numero para comenzar la cuenta\n"))
for i in range(cuenta_regresiva):
tmp = cuenta_regresiva
print("Iteracion {}".format(tmp - i))"""
cuenta_regresiva = int(input("Ingrese un numero para comenzar la cuenta\n"))
i=0
while i < cuenta_regresiva:
tmp = cuenta_regresiva
print("Iteracion {}".format(tmp - i))
i+=1 |
f70b4a24ed5e02a7cf3c7ffca5559bb134a54287 | amanchourasiya/leetcode | /algoexpert/singleCycleCheck.py | 626 | 3.5625 | 4 | # Space O(1) | time O(n)
def hasCycle(arr):
n = len(arr)
startIndex = 0
currIndex = 0
for i in range(n-1):
index = getIndex(currIndex, arr[currIndex], n)
print(currIndex, index)
if index == startIndex:
return False
currIndex = index
if getIndex(currIndex, arr[currIndex],n) != startIndex:
return False
return True
def getIndex(currIndex, move, n):
print('getIndex', currIndex, move)
m = currIndex + move
if m < 0:
m = 0- (abs(m)%n)
return n+m
return m % n
arr = [2,3,1,-4,-4,2]
print(hasCycle(arr)) |
29b71cdacb117580a9b0f27f014db5233f8b4c9b | jtrain/supapowa | /textentry.py | 7,100 | 3.5 | 4 | import pygame
from pygame.locals import *
from string import maketrans
from constants import *
from font import *
from button import *
from textgrab import TextGrab
__all__ = ['Textentry', 'PermaText']
class Textentry(pygame.sprite.Sprite):
def __init__(self, pos, containers, callback, heading='Enter Text..',
num_chars=10, background=None):
""" A text entry widget.
Args:
pos - tuple describing position (can be None and set later).
containers - pygame groups that this text module will join.
callback - a function to call with the string return value or None.
[heading] - an optional argument to specify a string to prompt user.
[num_chars] - the number of characters to allow user to enter.
[background] - set the background colour.
Return:
a string if save or enter is hit, None if cancelled.
"""
if background is None:
background = BUTTON_INNER_BASE
pygame.sprite.Sprite.__init__(self, containers)
self._heading = small_font(heading, WHITE, background)
# allow for one extra character the prompt pipe.
num_chars += 1
self._charwidth = small_font('A' * num_chars, WHITE, background)
# maximum amount of characters allowed.
self._maximum = num_chars
# call on saving text.
self._callback = callback
self._containers = containers
# make close\save button.
self._buttons = pygame.sprite.Group()
# set the button's position relative to this panel.
button_posx = self._charwidth.get_width() + 2
button_posy = self._heading.get_height()
button_pos = (button_posx, button_posy)
button = Exit_button(button_pos, containers=[self._buttons],
left_click=self.save, obj='save', padding=(4,0))
self._button = button
self.pos = pos
# create a readonly background panel, and our writeable image.
image, self.rect = self._make_panel(background)
self.image = pygame.Surface(self.rect.size)
self.image.blit(image, (0,0))
self.text = "|"
self.displayed_text = ""
#translation between key and SHIFT + key
self.translate = maketrans("0123456789,./'-=;", ')!@#$%^&*(<>?"_+:')
self.events = {"backspace": self.del_char, "return": self.save,\
"left shift": self.__set_shift, "right shift": self.__set_shift}
self.allowable = 'abcdefghijklmnopqrstuvwxyz0123456789!@$%&()<>.,?\'"+-=_:; '
self.shift = False
self.kill()
def _make_panel(self, background):
# make textentry surface.
self.textentry = pygame.Surface(self._charwidth.get_size())
self.textentry.fill(BUTTON_BACK)
# define the inner surface, a different colour to outer.
self.inner = pygame.Surface(
(
self._charwidth.get_width() - 2,
self._charwidth.get_height() - 2
)
)
self.inner.fill(TEXT_ENTRY_INNER)
self.textentry.blit(self.inner, (1,1))
self.textentry_posy = self.textentry.get_height()
# make overall surface.
sizex = self._charwidth.get_width() + self._button.image.get_width() + 2
sizey = self._heading.get_height() + self._charwidth.get_height()
box = pygame.Surface((sizex, sizey))
box.fill(background)
box.blit(self._heading, (2,0))
box.blit(self.textentry, (2, self.textentry_posy))
self.panel = box
rect = pygame.Rect(self.pos, box.get_size())
return box, rect
def show(self, containers=None):
txtmarshal = TextGrab()
txtmarshal.register(self.get_char)
if containers:
self.add(containers)
else:
self.add(self._containers)
self._button.show()
def set_pos(self, pos):
self.pos = pos
self.rect.topleft = pos
def get_char(self, keycode):
char = pygame.key.name(keycode)
try:
function = self.events[char]
return function()
except KeyError:
pass
if char == 'space': #manually set space
char = ' '
if self.shift:
char = char.upper()
char = char.translate(self.translate)
if char.lower() in self.allowable:
if len(self.text) < self._maximum:
self.text = self.text.strip('|')
self.text += char + '|'
self.shift = False
def del_char(self):
self.text = self.text[:len(self.text) - 2] + '|'
def save(self):
self._callback(self.displayed_text.strip('|'))
self.close()
def update(self, *args):
mouse = self._mouseevent(args[0])
self._buttons.clear(self.image, self.panel)
self._buttons.update(mouse)
self._buttons.draw(self.image)
if self.text == self.displayed_text:
return
text = small_font(self.text, BLACK, TEXT_ENTRY_INNER)
self.textentry.blit(self.inner, (1,1))
self.textentry.blit(text, (1,0))
self.image.blit(self.textentry, (2,self.textentry_posy))
self.displayed_text = self.text
def _mouseevent(self, mouse):
"""
mouse object:
tuple(tuple(x,y), tuple(m1,m2.m3))
"""
rawpos, button_state = mouse
left, middle, right = button_state
# get pos relative to this panel.
pos = self._relativepos(rawpos)
if not (rawpos in self):
self._mousedown(left, right, pos)
return (pos, button_state)
if not self._mousedown(left, right, pos):
self._mouseover(pos)
return (pos, button_state)
def _mousedown(self, left, right, pos):
if left:
index = 1
elif right:
index = 3
else:
return False
for button in self._buttons:
if button.get_state():
click = button.click(index)
return True
def _mouseover(self, pos):
for button in self._buttons:
if pos in button:
button.mouse_over(1)
else:
button.mouse_over(0)
def _relativepos(self, pos):
pos_x = pos[0] - self.pos[0]
pos_y = pos[1] - self.pos[1]
return (pos_x, pos_y)
def close(self):
txtmarshal = TextGrab()
txtmarshal.deregister()
self._button.kill()
self.kill()
def __set_shift(self):
self.shift = True
def __contains__(self, pos):
if self.alive():
return self.rect.collidepoint(pos)
return True
class PermaText(Textentry):
"""A permanent text entry, only closes when explicitly told."""
def save(self):
self._callback(self.displayed_text.strip('|'))
self.text = '|'
|
a9de2b04d609e101941429a2606185ea637c6f59 | Maxim-Krivobokov/python-practice | /Book_automation/ch6/pw.py | 568 | 3.6875 | 4 | #! python3
#pw.py - program for unsecure password keeping
PASSWORDS = {'email': 'po4ta_po4ta_pe4kin',
'blog': 'blogblogblog123321',
'luggage': '12345' }
import sys, pyperclip
if len(sys.argv) < 2:
print('You should enter an argument - name of your credential/login')
sys.exit()
account = sys.argv[1] # first argument is the login name
if account in PASSWORDS:
pyperclip.copy(PASSWORDS[account])
print('Password for '+ account + ' is copied to buffer.')
else:
print('Credentials for ' + account + ' are not presented in database.')
|
584f43aeec954d11a60c4903f60b69a3cc7e1a4a | Rohan2015/fsdse-python-assignment-103 | /build.py | 644 | 3.578125 | 4 | def compress(user_string):
op_string = ""
count = 1
if user_string == None:
return None
elif user_string == '':
return ''
op_string += user_string[0]
for i in range(len(user_string)-1):
if(user_string[i] == user_string[i+1]):
count+=1
else:
if(count > 1):
op_string += str(count)
op_string += user_string[i+1]
count = 1
if(count > 1):
op_string += str(count)
if len(op_string) == len(user_string):
return user_string
return op_string
user_string = "AAABCCDDD"
compress(user_string)
|
5ab2826b77989f189afc263f460b65c8f8d1e263 | mychristopher/test | /pyfirstweek/第一课时/通用装饰器.py | 396 | 4 | 4 | #!/usr/bin/python
# -*- coding: utf-8 -*-
#通用装饰器
def outer(func):
def inner(*args, **kwargs):
#添加修改的功能
print("&&&&&&&&&&&&&&&&&&&&&")
func(*args, **kwargs)
return inner
@outer
#函数的参数理论上无限制,但最好不要超过6-7个
def say(name,age):
print("my name is %s, I am %d years old" %(name ,age))
say("sunck", 18) |
a5605ddad0ed34de3b1d878ff4b02fa94793bd6d | Ashish9426/Python-Pattern-Printing | /Pattern_15.py | 173 | 3.515625 | 4 | def fun15():
for i in range(5, 0, -1):
for j in range(i, 0, -1):
print(j, end=' ')
print()
'''
5 4 3 2 1
4 3 2 1
3 2 1
2 1
1
'''
fun15() |
ebba6bafd11d8ad4bf73d6b76b7e92b142f03443 | lwoiceshyn/leetcode | /unique-paths.py | 2,822 | 4.15625 | 4 | '''
https://leetcode.com/problems/unique-paths/
'''
class Solution:
'''
Top-down dynamic programming (recursion + memoization). Every time we move down or right, we are solving a subproblem of the same type,
just on a slighty smaller grid (optimal substructure property). Thus, we have a recursion tree with two children from each node,
one for the subproblem where we move down, and one for the subproblem where we move right. First, we simply need to check for two
base cases. One in which our movement took us off the grid, which is not a valid path. In this case, m or n becomes zero, and we
return 0. The other base case is one in which we reached the final tile, where m and n are both 1. In this case, we return 1.
Otherwise, call the function recursively on both subproblems, in which we just need to subtract one for either argument,
and then sum up the values that they return, which indicate how many valid paths can be reached from that branch.
We use a memoization table to ensure that we don't recalculate overlapping subproblems.
We use a nested list for our memo table and a separate function for the recursion so that we can initialize it. Also,
need to make the dimensions m+1 x n+1 so that when we call memo[m][n] we are still in-bounds, due to zero-indexing.
Time Complexity: O(n^2)
Space Complexity: O(n^2)
'''
def uniquePaths(self, m: int, n: int) -> int:
self.memo = [[0 for _ in range(n+1)] for _ in range(m+1)] #Note that the second index is the inner index
return self.recurse(m, n)
def recurse(self, m, n):
if m == 0 or n == 0:
return 0
if m == 1 and n == 1:
return 1
if not self.memo[m][n]:
right = self.recurse(m-1, n)
down = self.recurse(m, n-1)
self.memo[m][n] = right + down
return self.memo[m][n]
class Solution2:
'''
Bottom-up dynamic programming solution. We will use a 2D m x n DP array, in which the value at each index signifies the
number of valid paths that end at that tile, with the starting tile having a initial value of 1. Then, we simply iterate through
all the tiles, adding the number of valid paths from the tile above and the tile to the left of the current tile, with an if
statement to handle the case where we are in the top row or left column of the grid, ensuring we don't try to index outside of
our array.
Time Complexity: O(n^2)
Space Complexity: O(n^2)
'''
def uniquePaths(self, m: int, n: int) -> int:
dp = [[0 for _ in range(n)] for _ in range(m)]
dp[0][0] = 1
for i in range(m):
for j in range(n):
if i > 0:
dp[i][j] += dp[i-1][j]
if j > 0:
dp[i][j] += dp[i][j-1]
return dp[m-1][n-1]
|
11e9603e6a0f67b36cba31bc6852302a79e79eaa | zackhsw/myTest_flask | /advance_apply/chapter08/getattr.py | 711 | 3.890625 | 4 | # __getattr__ 、__getattribute__
# __getattr__ 在查找不到属性的时候调用
from datetime import date, datetime
class User:
def __init__(self, name, birthday, info={}):
self.name = name
self.birthday = birthday
self.info = info
def __getattr__(self, item):
return self.info[item]
def __getattribute__(self, item):
return "bobo"
if __name__ == '__main__':
user = User("jack", date(year=2000, month=1, day=11), info={"company": "iBMM","address":"usa.xxx"})
# print(user.age) # 找不到age ,会调用__getattr__ 方法
# print(user.address) # 从__getattr__ 中找item 对应值
print(user.test) # 总先调用__getattribute__ |
8100be0d070adbf1a747ae44a96a197a89133c0a | RaffaeleMarchisio/SISTEMI_E_RETI | /esercizi_vacanze/es1/main.py | 959 | 3.515625 | 4 | import random
alfabeto = {0: "a", 1: "b", 2: "c", 3: "d", 4: "e", 5: "f", 6: "g", 7: "h", 8: "i", 9: "j", 10: "k", 11: "l", 12: "m",
13: "n", 14: "o", 15: "p", 16: "q", 17: "r", 18: "s", 19: "t", 20: "u", 21: "v", 22: "w", 23: "x", 24: "y",
25: "z", 26: 1, 27: 2, 28: 3, 29: 4, 30: 5, 31: 6, 32: 7, 33: 8, 34: 9, 35: 0}
lung = 0
risp=0
def password8():
cont = 0
while cont < 8:
num = random.randint(0, 35)
print(alfabeto[num], end="")
cont = cont + 1
def password20():
cont = 0
while cont < 20:
num = random.randint(0, 35)
print(alfabeto[num], end="")
cont = cont + 1
while risp != 3:
risp = int(input("1-password_semplice(8 caratteri)\n2-password_complicata\n3-esci\nscegliere tra una delle opzioni:"))
if risp == 1:
password8()
print("\n")
elif risp == 2:
password20()
print("\n")
|
b803f4b936c9b20dc33d90faa7abc26a654662a0 | sympy/sympy | /sympy/printing/conventions.py | 2,580 | 3.71875 | 4 | """
A few practical conventions common to all printers.
"""
import re
from collections.abc import Iterable
from sympy.core.function import Derivative
_name_with_digits_p = re.compile(r'^([^\W\d_]+)(\d+)$', re.U)
def split_super_sub(text):
"""Split a symbol name into a name, superscripts and subscripts
The first part of the symbol name is considered to be its actual
'name', followed by super- and subscripts. Each superscript is
preceded with a "^" character or by "__". Each subscript is preceded
by a "_" character. The three return values are the actual name, a
list with superscripts and a list with subscripts.
Examples
========
>>> from sympy.printing.conventions import split_super_sub
>>> split_super_sub('a_x^1')
('a', ['1'], ['x'])
>>> split_super_sub('var_sub1__sup_sub2')
('var', ['sup'], ['sub1', 'sub2'])
"""
if not text:
return text, [], []
pos = 0
name = None
supers = []
subs = []
while pos < len(text):
start = pos + 1
if text[pos:pos + 2] == "__":
start += 1
pos_hat = text.find("^", start)
if pos_hat < 0:
pos_hat = len(text)
pos_usc = text.find("_", start)
if pos_usc < 0:
pos_usc = len(text)
pos_next = min(pos_hat, pos_usc)
part = text[pos:pos_next]
pos = pos_next
if name is None:
name = part
elif part.startswith("^"):
supers.append(part[1:])
elif part.startswith("__"):
supers.append(part[2:])
elif part.startswith("_"):
subs.append(part[1:])
else:
raise RuntimeError("This should never happen.")
# Make a little exception when a name ends with digits, i.e. treat them
# as a subscript too.
m = _name_with_digits_p.match(name)
if m:
name, sub = m.groups()
subs.insert(0, sub)
return name, supers, subs
def requires_partial(expr):
"""Return whether a partial derivative symbol is required for printing
This requires checking how many free variables there are,
filtering out the ones that are integers. Some expressions do not have
free variables. In that case, check its variable list explicitly to
get the context of the expression.
"""
if isinstance(expr, Derivative):
return requires_partial(expr.expr)
if not isinstance(expr.free_symbols, Iterable):
return len(set(expr.variables)) > 1
return sum(not s.is_integer for s in expr.free_symbols) > 1
|
b36283dcf18ce454c8630d25248c38712c582de0 | zhy19950705/python | /1.py | 113 | 3.59375 | 4 | def normalize(name):
return name.capitalize()
L1=['adam','lisa','bart']
L2=list(map(normalize,L1))
print(L2) |
43f34c7509bf297cf3c0d00bcaae9d0548017c2e | BrettMZig/PythonFun | /primes.py | 454 | 3.765625 | 4 |
def composite_gen(prime, first, last):
c = prime + prime
while c < last:
if c > first:
yield c
c = c + prime
def find_primes(first, last):
if first < 2: first = 2
mSet = set(xrange(first, last))
primes = []
for x in xrange(2, last):
if x in mSet:
primes.append(x)
mSet = mSet - set(composite_gen(x, first, last))
return primes
if __name__ == "__main__":
first = 200
last = 10000
print find_primes(first, last)
|
0e4d12155d53a4ced32fa56f7ef0c8e169b6dc0e | benjaminner/python-scripts | /food.py | 201 | 3.984375 | 4 | food = {"hamburger" : "delicious", "cheeseburger" : "even more delicious", "anchovies" : "no thanks", "pizza" : "yum"}
what_did_you_eat = raw_input ("what did you eat? ")
print food[what_did_you_eat] |
5a3af94ebd384cf529efe8000ddd9c97aab35af2 | serpherino/python | /Projects/Notepad/notepad-gui.py | 1,061 | 3.546875 | 4 | from tkinter import *
import pyperclip
from tkinter import filedialog
root=Tk()
root.title("Notepad")
def copy_to_clipboard():
pyperclip.copy(text.get("1.0","end-1c"))
def clear():
text.delete(1.0,'end')
def save():
opf=filedialog.asksaveasfile(mode='w',defaultextension='.txt')
if opf is None:
return
entry=str(text.get(1.0,END))
opf.write(entry)
opf.close()
def openF():
f=filedialog.askopenfile(mode='r')
if f is not None:
cont=f.read()
text.insert(INSERT,cont)
text=Text(root,width=200,height=50)
button1=Button(root,text="Copy",command=copy_to_clipboard)
button2=Button(root,text="Clear",command=clear)
button3=Button(root,text="Quit",command=root.destroy)
button4=Button(root,text="Open",command=openF)
button5=Button(root,text="Save",command=save)
text.grid(row=2,columnspan=5,sticky=W+E+N+S)
button1.grid(row=1,column=1,sticky=W+E+N+S)
button2.grid(row=1,column=2,sticky=W+E+N+S)
button3.grid(row=1,column=4,sticky=W+E+N+S)
button4.grid(row=1,column=0,sticky=W+E+N+S)
button5.grid(row=1,column=3,sticky=W+E+N+S)
root.mainloop()
|
79b436e880cd21b6d5ccf5fd2a1c0dd00aa16018 | zhengw060024/pythoncookbookpractice | /exCookbook3.3.1.py | 471 | 3.984375 | 4 | #对数值做格式化输出使用format
x = 1234.56789
print(format(x,'0.2f'))
#当需要限制数值位数时,数值会根据round()函数规则来进行取整
print(format(x,'>10.1f'))
print(format(x,'<10.1f'))
print(format(x,'^10.1f'))
#千位分割
print(format(x,','))
print(format(x,'0,.1f'))
#如果要采用科学计数法只要将f改成e或者E即可
print(format(x,'e'))
print(format(x,'0.2e'))
#指定宽度和精度格式一般为[<>^]?width[,]?(.digits)? |
7b4ab424c64f5cb31c2bca5244eaf3e2a4594d74 | gholhak/Information_extraction | /misc/second_largest_element.py | 2,017 | 3.734375 | 4 | '''
Your desired array is here
Example = [2, 4, 9, 10]
'''
import random
import time
ARRAY = [random.randint(1, 100000) for _ in range(100000)]
class SecondLargestElement:
def __init__(self):
pass
@staticmethod
def check_for_identical_elements(args):
temp = []
for e in args:
if e not in temp:
temp.append(e)
if len(temp) == 1:
out = True
else:
out = False
return out
'''
detect the second largest element by sorting the array ascendingly.
'''
@staticmethod
def solution1(args):
sle = sorted(args)
return sle[-2]
'''
Detect the second largest element by finding the difference between the largest element
in the array with remaining elements. The smallest number is the index of the second largest element.
'''
@staticmethod
def solution2(args):
diff_holder = []
arr = []
for e in args:
if e != max(args):
diff_holder.append(max(args) - e)
arr.append(e)
return arr[diff_holder.index(min(diff_holder))]
def main():
sle_obj = SecondLargestElement()
# check_identical = sle_obj.check_for_identical_elements(ARRAY)
if len(ARRAY) == 0:
print('There is no element in your array:' + str(None))
elif len(ARRAY) == 1:
print('The largest element is:' + str(ARRAY[0]))
# elif check_identical:
# print('please provide an array with diverse elements')
else:
start_time = time.time()
s1 = sle_obj.solution1(ARRAY)
print('The second largest element using solution 1 is:' + str(s1))
print("-----%s seconds ----" % (time.time() - start_time))
start_time = time.time()
s2 = sle_obj.solution2(ARRAY)
print('The second largest element using solution 2 is:' + str(s2))
print("-----%s seconds ----" % (time.time() - start_time))
if __name__ == '__main__':
main()
|
835f467304f690e8cfdcb898d8bb0060e953b912 | Arxtage/leetcode | /detect-capital/detect-capital.py | 587 | 3.65625 | 4 | class Solution:
def detectCapitalUse(self, word: str) -> bool:
# O(n)
if len(word) <= 1:
return True
first_letter = word[0].isupper()
second_letter = word[1].isupper()
if not first_letter and second_letter:
return False
for i in range(2, len(word)):
if first_letter and (word[i].isupper() != second_letter):
return False
elif not first_letter and word[i].isupper():
return False
return True
|
78acd9f5b7d19697af10010c1e19b249bfa23730 | fraboniface/fbml | /optimization/base_optimizer.py | 1,576 | 3.5 | 4 | import numpy as np
class Optimizer:
"""Optimizer base class. Much slower than scikit-learn implementation."""
def __init__(self, gamma, epsilon):
self.gamma = gamma
self.epsilon = epsilon
def gradient_check(self, func, grad, points):
"""Checks wether or not the given gradient is correct."""
def base_vector(size, index):
e = np.zeros(size)
e[index] = 1.0
return e
h = 1e-8
mean, cnt = 0, 0
dim = points.shape[1]-1 # the bias is added at the beginning so the dimension is that of the weight vector plus one
for point in points:
b, w = point[0], point[1:]
if not np.isnan(func(b,w)):
bias_partial_derivative = (func(b+h, w) - func(b-h, w)) / (2*h)
numeric_grad = [bias_partial_derivative]
for i in range(dim):
e = base_vector(dim, i)
weight_partial_derivative = (func(b, w+h*e) - func(b, w-h*e)) / (2*h)
numeric_grad.append(weight_partial_derivative)
numeric_grad = np.array(numeric_grad)
relative_error = np.absolute(grad(b,w) - numeric_grad)/(np.maximum(np.absolute(grad(b,w)), np.absolute(numeric_grad))+1e-8)
mean += relative_error.max()
cnt += 1
mean /= cnt
if mean < 1e-4*w.shape[0] : # this threshold is rather arbitrary, see http://cs231n.github.io/neural-networks-3/
return 1
else:
return 0
def minimize(self, func, grad, b0, w0):
"""Finds the parameters which minimize the objective function."""
points = 10*np.random.random_sample((10, w0.shape[0]+1)) - 5 # we pick 10 points in [-5,5]
assert self.gradient_check(func, grad, points), "Gradient check has failed" |
7360c010b554800c22b8577f90a6b3b0cbc53bcd | kmineg144/AccountModule | /python_scripts/scripts/sfdc_account.py | 2,605 | 3.53125 | 4 | import pandas as pd
import numpy as np
from utility_scripts.account_winner import EstablishWinner
def merge_accounts(opportunity, accounts, subset_opp_columns=None):
"""
Nested function where the inner function loads the df
and the outer function merges the two df
Parameters
----------
accounts : str
filepath of the accounts pickled file
summary : str
filepath of the summary csv file
Returns
-------
df : DataFrame
merged dataframe object
"""
def load_opportunity():
"""
returns a df from a pickled file
"""
df = pd.read_pickle(opportunity)
df = df.reset_index()
if 'index' in df.columns:
del df['index']
return df
def load_accounts():
"""
returns a df from csv file file
"""
df = pd.read_csv(accounts)
return df
#if third argument is None, display all columns
if subset_opp_columns is None:
subset_opp_columns = (load_opportunity()
.columns
.to_list())
#only merge certain columns from the accounts df
df = pd.merge(load_accounts()
,load_opportunity()[subset_opp_columns]
,how = 'left'
,left_on = ['ACCOUNT__C']
,right_on =['AccountId'])
df = df.rename(columns={'Owner_Title_Role__c': 'Opportunity_Owner_Role'
,'Owner_Name__c': 'Opportunity_Owner_Name'})
return df
def account_main(opportunity, accounts, output):
subset_opp_columns = ['AccountId'
, 'Opportunity_Number__c'
, 'CreatedDate'
, 'OPPORTUNITY_EXCL_IND'
, 'Owner_Title_Role__c'
, 'Owner_Name__c']
df = merge_accounts(opportunity, accounts, subset_opp_columns=subset_opp_columns)
winning_df = EstablishWinner(df)
winning_df.new_columns()
winning_df.module_accounts()
df_union = pd.concat([winning_df.module_accounts(), winning_df.other_accounts()])
df_union.columns = map(str.upper, df_union.columns)
df_union = df_union.drop(['CSG2'
, 'SV_EXCL_IND'
, 'CSG_EXCL_IND'
, 'SFDC_ACCOUNT_TYPE'
, 'SFDC_OBJECT_TYPE' ],1)
df_union.to_pickle(output)
|
723e76fb7faefb0d4d4f5705b61ca559c7298bd7 | ChantalMP/FoobarChallenge | /challenge3_2.py | 7,832 | 3.8125 | 4 | import fractions
from fractions import Fraction
'''
Making fuel for the LAMBCHOP's reactor core is a tricky process because of the exotic matter involved. It starts as raw ore, then during processing,
begins randomly changing between forms, eventually reaching a stable form. There may be multiple stable forms that a sample could ultimately reach,
not all of which are useful as fuel.
Commander Lambda has tasked you to help the scientists increase fuel creation efficiency by predicting the end state of a given ore sample.
You have carefully studied the different structures that the ore can take and which transitions it undergoes. It appears that, while random,
the probability of each structure transforming is fixed. That is, each time the ore is in 1 state, it has the same probabilities of entering the next state
(which might be the same state). You have recorded the observed transitions in a matrix. The others in the lab have hypothesized more exotic forms that the
ore can become, but you haven't seen all of them.
Write a function solution(m) that takes an array of array of nonnegative ints representing how many times that state has gone to the next state and
return an array of ints for each terminal state giving the exact probabilities of each terminal state, represented as the numerator for each state,
then the denominator for all of them at the end and in simplest form. The matrix is at most 10 by 10. It is guaranteed that no matter which state the
ore is in, there is a path from that state to a terminal state. That is, the processing will always eventually end in a stable state.
The ore starts in state 0. The denominator will fit within a signed 32-bit integer during the calculation, as long as the fraction is simplified regularly.
For example, consider the matrix m:
[
[0,1,0,0,0,1], # s0, the initial state, goes to s1 and s5 with equal probability
[4,0,0,3,2,0], # s1 can become s0, s3, or s4, but with different probabilities
[0,0,0,0,0,0], # s2 is terminal, and unreachable (never observed in practice)
[0,0,0,0,0,0], # s3 is terminal
[0,0,0,0,0,0], # s4 is terminal
[0,0,0,0,0,0], # s5 is terminal
]
So, we can consider different paths to terminal states, such as:
s0 -> s1 -> s3
s0 -> s1 -> s0 -> s1 -> s0 -> s1 -> s4
s0 -> s1 -> s0 -> s5
Tracing the probabilities of each, we find that
s2 has probability 0
s3 has probability 3/14
s4 has probability 1/7
s5 has probability 9/14
So, putting that together, and making a common denominator, gives an answer in the form of
[s2.numerator, s3.numerator, s4.numerator, s5.numerator, denominator] which is
[0, 3, 2, 9, 14].
'''
'''
Input:
solution.solution([[0, 2, 1, 0, 0], [0, 0, 0, 3, 4], [0, 0, 0, 0, 0], [0, 0, 0, 0,0], [0, 0, 0, 0, 0]])
Output:
[7, 6, 8, 21]
Input:
solution.solution([[0, 1, 0, 0, 0, 1], [4, 0, 0, 3, 2, 0], [0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0]])
Output:
[0, 3, 2, 9, 14]
'''
def compute_prob_matrix_parts(m, terminal_states, non_terminal_states):
#transform to probs
last_transient_state = 0
for i in range(len(m)):
row = m[i]
row_sum = sum(row)
if row_sum != 0:
for j in range(len(row)):
m[i][j] = Fraction(row[j],row_sum)
last_transient_state +=1
else:
m[i][i] = Fraction(1,1)
# get Q and R
Q = []
R = []
for row in non_terminal_states:
new_row_Q = []
new_row_R = []
for column_Q in non_terminal_states:
new_row_Q.append(m[row][column_Q])
for column_R in terminal_states:
new_row_R.append(m[row][column_R])
Q.append(new_row_Q)
R.append(new_row_R)
return m, Q, R
def identity_matrix(n):
IdM = [([0]*n) for _ in range(n)]
for idx in range(n):
IdM[idx][idx] = Fraction(1,1)
return IdM
def matrix_diff(m1, m2):
for i in range(len(m1)):
for j in range(len(m1[0])):
m1[i][j] = m1[i][j] - m2[i][j]
return m1
def zeros_matrix(rows, cols):
A = []
for i in range(rows):
A.append([])
for j in range(cols):
A[-1].append(Fraction(0,1))
return A
def matrix_multiply(A,B):
rowsA = len(A)
colsA = len(A[0])
rowsB = len(B)
colsB = len(B[0])
if colsA != rowsB:
print('Number of A columns must equal number of B rows.')
C = zeros_matrix(rowsA, colsB)
for i in range(rowsA):
for j in range(colsB):
total = 0
for ii in range(colsA):
total += A[i][ii] * B[ii][j]
C[i][j] = total
return C
def copy_matrix(M):
rows = len(M)
cols = len(M[0])
MC = zeros_matrix(rows, cols)
for i in range(rows):
for j in range(rows):
MC[i][j] = M[i][j]
return MC
def invert_matrix(A):
n = len(A)
AM = copy_matrix(A)
I = identity_matrix(n)
IM = copy_matrix(I)
# Section 3: Perform row operations
indices = list(range(n)) # to allow flexible row referencing ***
for fd in range(n): # fd stands for focus diagonal
fdScaler = Fraction(1,1) / AM[fd][fd]
# FIRST: scale fd row with fd inverse.
for j in range(n): # Use j to indicate column looping.
AM[fd][j] *= fdScaler
IM[fd][j] *= fdScaler
# SECOND: operate on all rows except fd row as follows:
for i in indices[0:fd] + indices[fd + 1:]:
# *** skip row with fd in it.
crScaler = AM[i][fd] # cr stands for "current row".
for j in range(n):
# cr - crScaler * fdRow, but one element at a time.
AM[i][j] = AM[i][j] - crScaler * AM[fd][j]
IM[i][j] = IM[i][j] - crScaler * IM[fd][j]
return IM
def compute_fundamental_matrix(Q):
id_matrix = identity_matrix(len(Q))
diff = matrix_diff(id_matrix, Q)
N = invert_matrix(diff)
return N
def reduce_fractions(numerators, denominators):
numerators_new = []
denominators_new = []
for numerator, denominator in zip(numerators, denominators):
a = numerator
b = denominator
while a!=b and a!=1 and b!=1:
a, b = min(a, b), abs(a-b)
if a==b:
numerator = numerator//a
denominator = denominator//a
numerators_new.append(numerator)
denominators_new.append(denominator)
return numerators_new, denominators_new
def get_lcm_fractions(rationals):
numerators = [r.numerator for r in rationals]
denominators = [r.denominator for r in rationals]
numerators, denominators = reduce_fractions(numerators, denominators)
lcm = denominators[0]
for d in denominators[1:]:
lcm = lcm // fractions.gcd(lcm, d) * d
result = []
for i in range(len(denominators)):
ratio = lcm / denominators[i]
numerator = numerators[i]*ratio
result.append(int(numerator))
result.append(lcm)
return result
def solution(m):
terminal_states = []
non_terminal_states = []
for idx, row in enumerate(m):
if sum(row) == 0:
terminal_states.append(idx)
else:
non_terminal_states.append(idx)
if len(terminal_states) == 1:
return [1, 1]
m,Q,R = compute_prob_matrix_parts(m, terminal_states, non_terminal_states)
#(I -q)-1
N = compute_fundamental_matrix(Q)
B = matrix_multiply(N, R)
result_probs = [B[0][end] for end in range(len(B[0]))]
result = get_lcm_fractions(result_probs)
return result
if __name__ == '__main__':
print(solution([
[0, 0, 0],
[1, 0, 1],
[0, 0, 0]
]))
print(solution([[0, 1, 0, 0, 0, 1], [4, 0, 0, 3, 2, 0], [0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0]]))
|
1f5ed4f1416a31eaffc12a4f61e2cc03f1c5de2b | Jen456/Examen_Fund_Programacion- | /PythonApplication1.py | 482 | 3.75 | 4 | numero= int(input('Ingrese numero:\n'))
contador =0
lista_mul= []
lista_sum=[]
mul=1
suma=0
while ():
numero= numero /10
if contador==1 or contador ==3:
lista_mul.append(numero)
contador= contador+1
else:
lista_sum.append(numero)
contador= contador+1
for i in lista_mul:
mul= mul*i
for j in lista_sum:
suma+=j
result= mul+suma
result= result%10
print ("Codigo valido\n")
print(result)
|
b86774ac2d76ac1a1074609a3c0559633dfcced0 | scotttct/tamuk | /Python/Python_Abs_Begin/Mod4_Nested/4_1_2-Birds.py | 706 | 4.0625 | 4 | # Found answer on: https://www.codeproject.com/Questions/1247399/Calling-function-in-nested-IF-in-Python
bird_names=('crow', 'parrot', 'eagle')
def bird_guess():
bird_guess1=input('Enter the bird guess :')
return bird_guess1
guess = bird_guess()
if(guess not in bird_names):
print('1st try fail, do 2nd try')
guess = bird_guess()
if(guess not in bird_names):
print('2nd try fail, please do 3rd try')
guess = bird_guess()
if(guess not in bird_names):
print('Sorry, exhausted tries')
else:
print('corect on 3rd try')
else:
print('good work! correct on 2nd try')
else:
print('great work!, correct on 1st try itself') |
b95933bb910c31c20795b77af93db09cdda490af | codeswhite/get_cover_art | /get_cover_art/deromanizer.py | 851 | 3.796875 | 4 | import re
# based on https://www.tutorialspoint.com/roman-to-integer-in-python
class DeRomanizer(object):
def __init__(self):
self.romans = {'I':1,'V':5,'X':10,'L':50,'C':100,'D':500,'M':1000,'IV':4,'IX':9,'XL':40,'XC':90,'CD':400,'CM':900}
def convert_word(self, word):
if not re.match(r"^[I|V|X|L|C|D|M]+$", word, flags=re.IGNORECASE):
return word
i = 0
num = 0
word = word.upper()
while i < len(word):
if i+1<len(word) and word[i:i+2] in self.romans:
num+=self.romans[word[i:i+2]]
i+=2
else:
num+=self.romans[word[i]]
i+=1
return str(num)
def convert_all(self, field):
converted = [self.convert_word(word) for word in field.split()]
return ' '.join(converted)
|
c346457c13e00ddbd637b46f6d147df20fdb1e65 | yarbroughjm/Python | /strings2.py | 271 | 3.828125 | 4 | message = "welcome to Python! Thanks for taking my class!"
message2 = "mark"
message3 = "768345345"
print(message.find('for'))
print(message.find('xx'))
if message.find('xx') == -1:
print("Not found in message")
print(message2.isalpha())
print(message3.isdigit())
|
132459a9a43dac4fee3dbcbf190bdbb121dcc727 | nidhi99verma/Exercies-Python | /o7.py | 208 | 3.78125 | 4 | # *
# ***
# ***** print
def print_t(n):
x = '*'
y = ' '
z = n-1
for i in range(1,n+1):
print(f"{y*(z)}{x}{y*(z)}")
z-=1
x += "**"
return
print_t(3)
|
2b791161de81aa867a7f251e9c32c46da9a787fd | ahartz1/project-euler | /python/e028number_spiral_diagonals.py | 1,860 | 4.03125 | 4 | """
Project Euler #28: Number Spiral Diagonals
From the description:
Starting with the number 1 and moving to the right in a clockwise direction
a 5 by 5 spiral is formed as follows:
21 22 23 24 25
20 7 8 9 10
19 6 1 2 11
18 5 4 3 12
17 16 15 14 13
It can be verified that the sum of the numbers on the diagonals is 101.
What is the sum of the numbers on the diagonals in a 1001 by 1001 spiral
formed in the same way?
"""
from __future__ import (absolute_import, print_function)
from ensure_integer import ensure_integer
class NonOddInputError(Exception):
pass
def spiral_diagonals_sum(edge_length=1001):
"""
Return sum of spiral diagonals
Args:
edge_length (int): The length of the outside edge of the spiral (odd).
Returns:
Sum of spiral diagonals.
"""
ensure_integer(edge_length, var_name='edge_length')
if edge_length % 2 == 0:
raise NonOddInputError('edge_length must be odd')
spiral_edge = 1
spiral_corners = [1, ]
while spiral_edge < edge_length:
# Next odd edge length
spiral_edge += 2
# Top right corner is square of spiral_edge
temp_corner = spiral_edge ** 2
spiral_corners.append(temp_corner)
for _ in range(3):
# Other corners can be calculated by subtracting spiral_edge - 1
# from the previous corner value
temp_corner -= (spiral_edge - 1)
spiral_corners.append(temp_corner)
return sum(spiral_corners)
if __name__ == '__main__':
edge_length = 1001
print('Spiral Diagonal Sum for spiral of edge length'
' {}: {}'.format(edge_length, spiral_diagonals_sum(edge_length)))
|
1e84b0e9be671d586c76f57555e25cd548474bf9 | Palombredun/miniscript | /calcul_integral/left_rectangle.py | 332 | 3.765625 | 4 | from math import cos, pi
def f(x):
return cos(x)
def left_rectangle(f, a, b, n):
total = 0
step = (b - a)/n
x = a
for i in range(0, n):
total += f(x)
x += step
print("Nombre de pas :", n)
print("Longueur d'un pas :", step)
print("Valeur de l'intégrale :", total*step)
return total*step
left_rectangle(f, 0, pi, 100) |
a2746e963cc4c32a24d5e743ee5abf0a0748c373 | jiinso/In_Class_Exercises | /IP4CS_Exercise12.py | 991 | 4.21875 | 4 | # In Class Exercise 12
# Classes - object oriented programming
# author: jiinso
# date: 10/23/2014
# create a class "Animal"
class Animal:
# define attributes
country = "Kenya"
label = "Animals Found in Kenyan Safari"
# define attributes that should be input initially with an instance
def __init__(self, name, age, weight, species):
self.name = name
self.age = age
self.weight = weight
self.species = species
class Dogs(Animal):
type = "mammal"
order = "Carnivora"
suborder = "Caniformia"
family = "Canidae"
hippo = Animal("Hippo", "12", "1500", "Hippopotamus amphibius")
girrafe = Animal("Girrafe", "3", "800", "Giraffa camelopardalis")
elephant = Animal("Elephant", "50", "6000", "Loxodonta africana")
rhino = Animal("Rhinoceros", "20", "1200", "Diceros bicornis")
jackal = Dogs("Golden jackel", "9", "30", "Canis aureus")
wilddog = Dogs("African wild dog", "2", "18", "Lycaon pictus")
print wilddog
|
49bf83ab3eb645a06f83d2ecc1eb74545f3e6038 | evinpinar/competitive_python | /leetcode/7.py | 867 | 3.890625 | 4 |
import unittest
class Solution:
def reverse(self, x: int) -> int:
'''
divmod divides the element and returns the remainder as mod.
'''
k = 0
n = [1, -1][x<0]
x = abs(x)
while x != 0:
x, mod = divmod(x, 10)
k = k*10 + mod
return n * k if -pow(2, 31) <= n * k <= pow(2, 31) - 1 else 0
def reverse2(self, x: int) -> int:
'''
This one uses the python's list reversing function [::-1].
'''
s = (x > 0) - (x < 0)
r = int(str(x * s)[::-1])
return s * r * (r < 2 ** 31)
class Testing(unittest.TestCase):
def test_reverse(self):
sol = Solution()
cases = [
[123, 321],
[-123, -321],
[120, 21]
]
f1 = sol.reverse
for i, x in enumerate(cases):
self.assertEqual(f1(x[0]), x[1])
f2 = sol.reverse2
for i, x in enumerate(cases):
self.assertEqual(f2(x[0]), x[1])
if __name__ == '__main__':
unittest.main() |
5a945c4a0c8ce71a06b057442a7678340832814f | synthetic-data/synthesis | /regression/generator_make_regression.py | 3,213 | 4.46875 | 4 | """
Generating data with datasets.make_regression function
It creates a linear model y = w*X + b, then generates
'outputs' y and adds noise to X.
https://scikit-learn.org/stable/modules/generated/sklearn.datasets.make_regression.html#sklearn.datasets.make_regression
https://github.com/scikit-learn/scikit-learn/tree/master/sklearn/datasets
"""
#import numpy as np
# print('NumPy:{}'.format(np.__version__))
# np.random.seed(123)
import matplotlib.pyplot as plt
import sklearn as sk
# print('Scikit Learn:{}'.format(sk.__version__))
from sklearn import datasets as skds
# the function make_regression returns a tuple
# the _generated_ X matrix is called 'inputs'
# the _generated_ y matrix is called 'targets'
X, y, C = skds.make_regression(
n_samples=10, # integer, default = 100
n_features=1, # integer, default = 100
n_informative=1, # integer, default = 10
# the number of features used to build the linear
# model used to generate the output.
n_targets=1, # integer, default = 1
# The number of regression targets, i.e., the
# dimension of the y output vector associated
# with a sample. By default, a scalar.
bias=0.0, # float, optional (default=0.0) in units of y
# The bias term in the underlying linear model.
effective_rank=None,# the 'approximate effective' rank of the input
# matrix. If None the input set is 'well
# conditioned, centered and Gaussian with unit
# variance.
tail_strength=0.5, # float between 0.0 and 1.0, optional (default=0.5)
# The relative importance of the fat noisy tail
# of the singular values profile if
# effective_rank is not None.
noise=0.0, # the standard deviation of Gaussian noise, added
# to the output - y.
coef=True, # boolean, optional (default=False)
# If True, the coefficients of the underlying
# linear model are returned.
random_state=789) # the seed-like integer for reproducibility
print(X, "\n")
print(y, "\n")
print(C, "\n")
# reshape?
if (y.ndim == 1):
y = y.reshape(-1, 1) # Transposes y which originally is a line (not column).
print(y, "\n")
# plot the points
plt.figure(figsize=(14,8))
plt.plot(X,y,'b.')
plt.title('The Synthetic Dataset')
plt.show()
"""
Now I understand.
the "features" are generated to be Gaussian and "centered" (around zero)
and having a standard deviation of 1, which means that they can be positive,
negative and are potentially unlimited. This fake 'input' is put through
a linear model generated in a way that a standart deviation of 1 would
transform into a 'target' with value C . The 'bias' is the "b" term
of the linear model so it shifts the picture by the same number of units
What I don't understand is: why not define the coefficients of the linear
model? Why not let scale the output?
Caught the constant of the linear model, finally.
""" |
b385e0cc54df27d9c60aa82b5f59c1d2403e1381 | devashish89/PluralsightPythonIntermediate | /Numeric.py | 2,474 | 3.859375 | 4 | import sys
print(sys.float_info)
print(sys.int_info)
####### IMP. ######################
print("0.8-0.7", 0.8-0.7)
### fix for above ############
from decimal import Decimal
print(Decimal(Decimal(0.8)-Decimal(0.7))) ##same problem with float
print(Decimal('0.8')-Decimal('0.7')) ##correct
###### IMP. ###############################
print(Decimal('Infinity'))
print(Decimal('-Infinity'))
print(Decimal('NaN'))
######## IMP.###############
print("'-7 % 3 = -1'",-7 % 3)
print("'-7 % 3 = -1'", Decimal('-7') % Decimal('3'))
print("'-7 // 3 = -2'", -7 //3)
print("'-7 // 3 = -2'", Decimal('-7') // Decimal('3'))
import math
print(math.sqrt(Decimal('.81')))
################# Fractions #################################
from fractions import Fraction
print(Fraction(2,3))
print(Fraction(0.75))
print(Fraction(0.1)) #problem because => 3602879701896397/36028797018963968
print(Fraction(Decimal('0.1')))
print(Fraction('2/3') + Fraction('4/5'))
print(Fraction(2,3)+Fraction(4,5))
print(Fraction('2/3') % Fraction('4/5'))
print(Fraction(2,3) % Fraction(4,5))
print(math.sqrt(Fraction(2,3)))
print(math.sqrt(0.666666666666))
######### Complex Nos. ##################
print(type(3+4j))
print(complex(3,4))
print(complex('3+4j'))
c = -2 -5j
print("real part of complex", c.real)
print("imaginary part of complex", c.imag)
print("conjugate", c.conjugate())
try:
math.sqrt(-1)
except ValueError as e:
print(e)
import cmath
print(cmath.sqrt(-1))
phase = cmath.phase(complex(1,1)) #hypotunese
print(phase)
print(abs(complex(1,1)))
print(cmath.polar(complex(1,1)))
absolute , phase = cmath.polar(complex(1,1))
print("abs:{} and phase: {}".format(absolute, phase))
################################################################
def inductance(val):
return complex(0, +val)
def capacitance(val):
return complex(0, -val)
def resistance(val):
return complex(val,0)
def impedance(components):
z = sum(components)
return z
z = impedance([inductance(10), capacitance(5), resistance(20)])
print(z)
print(cmath.phase(z), "radians")
print(math.degrees(cmath.phase(z)), "degrees")
####### round()################################
print(round(0.67854, 3))
## IMP.###############
print(round(1.5)) # 2 rounding is towards even no for .5 values
print(round(2.5)) # 2 rounding towards even no. for .5 values
print(round(2.6)) #3
print(round(2.4)) #2
print("issue it should be 2.68:", round(2.675,2))
print("issue fix:", round(Decimal('2.675'),2)) |
144c70d1fbf089310211b95fd16a81aa5247a69c | santiago-1999-dev/Programaci-n-Ing-Bio- | /examenes/covid19.py | 2,611 | 3.984375 | 4 | #--------MENSAJES-------
MENSAJE__BIENVENIDO ="Bienvenido a la clinica"
presion = 0.0
#-----------CODIGO----------------
print (MENSAJE__BIENVENIDO)
_decision = int (input("""
ingrese :
1- para mostrar en pantalla el peso y el valor de la presion calculada
2- para añadir peso de pacientes
3- para ver informacion de las presiones
4- salir
"""))
while (_decision != 4):
if (_decision == 1):
def mostrar_dos_listas ( lista_1 , lista_2):
if ( len ( lista_1 ) == len ( lista_2 )):
print ("peso -" , "presion -")
for i in range ( len ( lista_1 )):
print ( lista_1 [ i ] , lista_2 [ i ])
pesosPacientes = [32,64,74,85,98,115,122,127,137,148]
presiones=[]
for peso in pesosPacientes:
presiones.append(peso*6)
print(presiones)
mostrar_dos_listas (pesosPacientes, presiones)
elif (_decision == 2):
def mostrar_lista (lista_1):
if ( len ( lista_1 )):
print ("Esta es la lista de los pesos nuevas ingresados")
for i in range ( len ( lista_1 )):
print (lista_1[i])
def llenarlista ():
lista = []
decision = input ("ingrese s--> para agregar mas pesos n--> para no agregar mas pesos : ")
while (decision == "s"):
lista.append (input("Ingrese el peso del paciente a la lista : "))
decision = input ("ingrese s--> para agregar mas pesos n--> para no agregar mas pesos : ")
return lista
print ("desea inngresar el peso de los pacientes? : ")
pesos = llenarlista ()
mostrar_lista (pesos)
elif (_decision == 3):
print ("la presion mas alta en la lista de nuevos {} es el {}"
.format(presiones, max (presiones)))
print ("la presion mas baja en la lista de los nuevos {} es el {}"
.format(presiones, min (presiones)))
presiones.sort(reverse=True)
print ("lista de presiones en orden decreciente {}".format(presiones))
print ("esta es la cantidad de pacientes ingresados")
print (len(pesosPacientes))
print (len(pesos))
else:
print("ingrese un valor valido")
_decision = int (input("""
ingrese :
1- para mostrar en pantalla el peso y el valor de la presion calculada
2- para añadir peso de pacientes
3- para ver informacion de las presiones
4- salir
"""))
print ("gracias por utilizar el programa") |
269ede161c74a2603a5d8e11a9ff6cfce5d471e0 | BryanKnightCode/Python-Learning | /Learning/Lessons/Chapter 3/C3_3-8_seeing_the_world.py | 1,616 | 4.78125 | 5 | # Store the locations in a list. Make sure the list is not in alphabetical order.
# Print your list in its original order. Don’t worry about printing the list neatly,
# just print it as a raw Python list.
locations = ['disney', 'australia', 'houston', 'tampa', 'vegas']
print("\nOriginal order")
print(locations)
# Use sorted() to print your list in alphabetical order without modifying the
# actual list.
print("\nAlphabetical")
print(sorted(locations))
# Show that your list is still in its original order by printing it.
print("\nOriginal order")
print(locations)
# Use sorted() to print your list in reverse alphabetical order without changing
# the order of the original list.
print("\nReversed order")
print(sorted(locations, reverse=True))
# Show that your list is still in its original order by printing it again.
print("\nOriginal order")
print(locations)
# Use reverse() to change the order of your list. Print the list to show that its
# order has changed.
print("\nReversed")
locations.reverse()
print(locations)
# Use reverse() to change the order of your list again. Print the list to show
# it’s back to its original order.
print("\nOriginal order")
locations.reverse()
print(locations)
# Use sort() to change your list so it’s stored in alphabetical order. Print the
# list to show that its order has been changed.
print("\nAlphabetical")
locations.sort()
print(locations)
# Use sort() to change your list so it’s stored in reverse alphabetical order.
# Print the list to show that its order has changed.
print("\nReverse Alphabetical")
locations.sort(reverse=True)
print(locations) |
ee8716769c7f9a5b2aad8fbd8033db3f5d5fd255 | oluwatobi1/SCA-tutorial | /Alternative Execution.py | 145 | 4.21875 | 4 | number = int(input("Enter number here: "))
if number%2 == 0:
print("This is an even number")
else:
print("This is an odd number")
|
75935c4843c9f32e1d43602fa23178631512ff15 | sebigher/FMI | /Anul II/Semestrul II/Retele/Laborator2.py | 1,153 | 3.703125 | 4 | l = [1,3,7,10,'s','a']
def functie(lista):
# comment pentru hello world
variabila = 'hello "world"'
print variabila
# int:
x = 1 + 1
# str:
xs = str(x) + ' ' + variabila
# tuplu
tup = (x, xs)
# lista
l = [1, 2, 2, 3, 3, 4, x, xs, tup]
print l[2:]
# set
s = set(l)
print s
print s.intersection(set([4, 4, 4, 1]))
# dict:
d = {'grupa': 123, "nr_studenti": 10}
print d['grupa'], d['nr_studenti']
lista = [1,5,7,8,2,5,2]
for element in lista:
print element
for idx, element in enumerate(lista):
print idx, element
for idx in range(0, len(lista)):
print lista[idx]
idx = 0
while idx < len(lista):
print lista[idx]
idx += 1
'''
comment pe
mai multe
linii
'''
x = 1
y = 2
print x + y
if (x == 1 and y == 2) or (x==2 and y == 1):
print " x e egal cu:", x, ' si y e egal cu: ', y
elif x == y:
print 'sunt la fel'
else:
print "nimic nu e adevarat"
functie(l) |
aaf274551d952a66f71be9a42a6e7ccb71e058d7 | akolzin/AKolzin_1 | /human/Woman.py | 1,322 | 3.734375 | 4 | import random
from .Human import Human
class Woman(Human):
def __init__(self, name='Ivan', soname='Ivanov', age=18, money=0):
super().__init__(name, soname, age, money)
self.sex = 'female'
self.stamina = 100
@staticmethod
def reproduce(fother=None, mother=None):
if fother and mother:
if type(fother) == Human and type(mother) == Woman:
print('можно размножаться')
return Human()
else:
print('Алярма! Ахтунги атакуют!!!')
return None
print('не хватает одного из родителей!')
return None
def eat(self):
if self.money > 0:
self.money -= 1
self.stamina += 5
print(self.name, 'я покушала! (=', self.money, self.stamina)
else:
print(self.name, 'Совсем нету денег на ноготочки! :`(')
def Shopping(self):
i = 5 * random.randint(-10, 10)
self.money = self.money + random.randint(-2, 2)
self.happiness = self.happiness + i
print('По шопилась, денег осталась', self.money, 'Счастливая на', self.happiness, "(прирост " + str(i) + ")") |
1e302f2f558a340823408315b1a036d896e5dea5 | aqing1987/s-app-layer | /python/samples/md5-tools/tidy.py | 405 | 3.546875 | 4 | #!/usr/bin/env python
dict_file = "aa.txt"
out_file = "common-dict.txt1"
def main():
ftw = open(out_file, "w")
with open(dict_file) as fileobj:
for line in fileobj:
line = line.strip()
words = line.split(" ")
for word in words:
word = word.strip()
if word.isdigit() == False:
ftw.write(word + "\n")
ftw.close()
if __name__ == "__main__":
main() |
f4bdbc205e8106b585f1807a8d0a2ce42f40ca2a | LuisTavaresJr/cursoemvideo | /ex07.py | 217 | 3.953125 | 4 | nota1 = float(input('Digite sua primeira nota: '))
nota2 = float(input('Digite sua segunda nota: '))
s = (nota1 + nota2) / 2
print(f'Primeira nota foi {nota1} e sua segunda nota foi {nota2}!\nSua Média foi {s:.1f}')
|
5ca5b29b69d590522c8210d0658299e8067e30ee | lavanyachitra/be | /odd.py | 92 | 3.53125 | 4 | start,end = 4,6
for num in range(start,end+1):
if num%2==0:
print(num,end= " ")
|
bdb805138981a77e9cf6fc00c8c58a46af04733d | agrija9/Python-Fundamentals | /Python OOP Tutorial 5: Special (Magic Dunder) Methods.py | 1,481 | 4.0625 | 4 | # super module runs with Python 3
# Special methods are defined with underscores. Init is first and most common method when working with classes
# Two more common special methods are repr or str
# The three methods: init, repr and str are the most common ones
class Employee:
raise_amt = 1.04
def __init__(self, first, last, pay):
self.first = first
self.last = last
self.pay = pay
self.email = first + '.' + last + '@email.com'
def fullname(self):
return '{} {}'.format(self.first, self.last)
def apply_raise(self):
self.pay = int(self.pay * self.raise_amt)
#repr is meant to be an unambiguous representation of the object and should be used for debugging and logging
def __repr__(self):
return "Employee('{}', '{}', '{}')".format(self.first, self.last, self.pay)
#str is meant to be more of a readable repr of an object. And is used as a display to the end user
def __str__(self):
return '{} - {}'.format(self.fullname(), self.email)
#pass
def __add__(self, other):
return self.pay + other.pay
def __len__(self):
return len(self.fullname())
emp_1 = Employee('Alan', 'Preciado', 500)
emp_2 = Employee('Mickey', 'Mouse', 600)
#print(emp_1)
#print(repr(emp_1)) #In the background, it is calling directly those special methods
#print(str(emp_1))
#print(emp_1.__repr__())
#print(emp_1.__str__())
#print(emp_1 + emp_2) #We have defined in the background our custom add operation. Which takes employee objects
#print(3+2)
print(len(emp_1)) |
e066903d2ae48c4a833a88ccd060e28ecb221024 | sensei98/py | /helloworld.py | 147 | 3.890625 | 4 | a = 1
b = 4
if(a+b==3):
print("you are def right but ... sad")
else:
print("hello sir you are not right")
# print (a+b)
#first lesson
|
0103850b6b312638cbf26e9f76a170ffa90b7557 | AlanVek/Proyectos-Viejos-Python | /161.py | 392 | 3.640625 | 4 | cadena=input("Ingrese cadena de palabras: ")
n=int(input("Ingrese número entero: "))
suma=1
p=0
for i in range (0,len(cadena)):
if cadena[i]==" ":
subcadena=cadena[p:i]
p=i+1
if len(subcadena)>=n:
suma+=1
if i==(len(cadena)-1):
subsubcadena=cadena[p:i+1]
if len (subsubcadena)>=n:
suma+=1
if suma>1:
print ("Hay palabras largas")
else:
print ("No hay palabras largas.") |
1f0b7a79c7ac78aa2b80644d4f47aad309c20dbc | Krupa092/Data-Structures-And-Algorithms_Python | /Basic_Algorithms/Basic_algorithms/Contains_BS.py | 1,031 | 3.96875 | 4 | def recursive_binary_search(target, source):
if len(source) == 0:
return None
center = (len(source)-1) // 2
if source[center] == target:
return center
elif source[center] < target:
return recursive_binary_search(target, source[center+1:])
else:
return recursive_binary_search(target, source[:center])
def contains(target, source):
return recursive_binary_search(target, source) is not None
letters = ['a', 'c', 'd', 'f', 'g']
print(contains('a', letters)) ## True
print(contains('b', letters)) ## False
"""
def contains1(target,source):
if len(source) == 0:
return False
center = (len(source)-1)//2
if source[center] == target:
return center
elif source[center] < target:
return contains1(target,source[center+1:])
else:
return contains1(target,source[:center])
letters1 = ['a', 'c', 'd', 'f', 'g']
print(contains1('a', letters1)) ## True
print(contains1('b', letters1)) ## False
""" |
f143e4eab41ad6969552897842acec8367ec2906 | miseop25/Back_Jun_Code_Study | /Programmers/기타문제/약수의개수와덧셈/divisor_nums_plus_ver1.py | 868 | 3.796875 | 4 | class Divisor :
def __init__(self,left, right):
self.left = left
self.right = right
self.answer = 0
def getDivisor(self,num) :
result = set()
if num == 1 :
result.add(num)
return result
for i in range(1, int(num//2)+1 ) :
if num % i == 0 :
result.add(i)
result.add(num//i)
return result
def getAnswer(self) :
for i in range(self.left, self.right + 1) :
divisor_Set = self.getDivisor(i)
if len(divisor_Set)%2 == 0 :
self.answer += i
else :
self.answer -= i
return self.answer
def solution(left, right):
d = Divisor(left,right)
answer = d.getAnswer()
return answer
a = int(input())
b = int(input())
print(solution(a,b)) |
61bcff6bfa670a40fc3466ec995dffab391d534c | georgelzh/Cracking-the-Code-Interview-Solutions | /recursionAndDynamicProgramming/towersOfHanoi.py | 1,673 | 4.125 | 4 | """
Towers of Hanoi: In the classic problem of the Towers of Hanoi, you have 3 towers and N disks of
different sizes which can slide onto any tower. The puzzle starts with disks sorted in ascending order
of size from top to bottom (i.e., each disk sits on top of an even larger one). You have the following
constraints:
(1) Only one disk can be moved at a time.
(2) A disk is slid off the top of one tower onto another tower.
(3) A disk cannot be placed on top of a smaller disk.
Write a program to move the disks from the first tower to the last using stacks.
Hints: #144, #224, #250, #272, #318
"""
class Tower:
def __init__(self, index):
self.index = index
self.disks = []
def add(self, d):
print(d)
if self.disks and self.disks[len(self.disks) - 1] <= d:
print("error")
else:
self.disks.append(d)
def moveTopTo(self, dest):
top = self.disks.pop()
dest.add(top)
def moveDisks(self, n, dest, buffer):
if n > 0:
self.moveDisks(n - 1, buffer, dest) # pay attention here, we are moving all n-1 to buffer,
self.moveTopTo(dest)
buffer.moveDisks(n - 1, dest, self) # then we move from buffer back to destination.
# move n - 1 from buffer to dest. destination to buffer.
# bc line 31 here we are using dest as buffer, and we
def towersOfHanoi(n):
towers = []
for i in range(n):
towers.append(Tower(i))
for i in range(n, 0, -1):
towers[0].add(i)
towers[0].moveDisks(n, towers[2], towers[1])
return towers[2]
a = towersOfHanoi(10)
print(a.disks) |
f25d53f3aecb31c1fea490b50a61df95f6f203d3 | dexbol/bomb | /bomb/utils.py | 1,082 | 3.5 | 4 | # coding=utf-8
import os
import logging
import re
logger = logging.getLogger('bomb')
def normalize_path(*path):
'''Normally a path. If the path is a direcotry the last character is
path separate.
'''
path = os.path.normcase(''.join(path))
dirname, basename = os.path.split(path)
# is it a direcotry?
basename = os.sep if basename == '' else (os.sep if dirname != '' else '')\
+ basename
return (dirname if dirname == '' else os.path.normpath(dirname))\
+ basename
def filename(path):
'''Parse a file path return file name, base name and extension name.
'''
pattern = re.compile(r'[/\\]([^/\\]+\.\w+$)')
matchObj = re.search(pattern, path)
if matchObj:
filename = matchObj.group(1)
else:
filename = path
pattern = re.compile(r'^(.+)\.(\w+)$')
matchObj = re.search(pattern, filename)
if matchObj:
# (filename, name, extend name)
return (filename, matchObj.group(1), matchObj.group(2))
else:
return (filename)
|
5949ee5ecb91c69dd3d8fa7b1b78c7991f521fa1 | cVidalSP/pythonBasics | /src/listas.py | 376 | 3.84375 | 4 | lista = [1,4,7,"caina",23,14]
print(lista)
lista.append("python")
print(lista)
lista.append(20)
print(lista)
print(lista.index("caina"))
print(lista.count(4))
lista.append(4)
print(lista.count(4))
print(lista)
lista.remove("python")
lista.remove(4)
print(lista)
lista.reverse()
print(lista)
lista2 = [1,2,9,10,45,3]
print(lista2)
lista2.sort()
print(lista2)
|
7ea531ba8473b93fc09951dc4d7fc5f3c50c2e4b | huiyi999/leetcode_python | /Can Place Flowers.py | 1,574 | 3.875 | 4 | '''
You have a long flowerbed in which some of the plots are planted, and some are not.
However, flowers cannot be planted in adjacent plots.
Given an integer array flowerbed containing 0's and 1's,
where 0 means empty and 1 means not empty, and an integer n,
return if n new flowers can be planted in the flowerbed without violating the no-adjacent-flowers rule.
Constraints:
1 <= flowerbed.length <= 2 * 104
flowerbed[i] is 0 or 1.
There are no two adjacent flowers in flowerbed.
0 <= n <= flowerbed.length
'''
from typing import List
class Solution:
def canPlaceFlowers(self, flowerbed: List[int], n: int) -> bool:
# flowerbed = [0] + flowerbed + [0]
for i in range(len(flowerbed)):
if flowerbed[i] == 0 and (i == 0 or flowerbed[i - 1] == 0) and (
i == len(flowerbed) - 1 or flowerbed[i + 1] == 0):
flowerbed[i] = 1
n -= 1
print(n)
return n <= 0
def canPlaceFlowers2(self, flowerbed: List[int], n: int) -> bool:
count=0
flowerbed=[0]+flowerbed+[0]
for i in range(1,len(flowerbed)-1):
if flowerbed[i]==0 and flowerbed[i-1]==0 and flowerbed[i+1]==0:
flowerbed[i]=1
count+=1
return count>=n
solution = Solution()
solution.canPlaceFlowers([1, 0, 0, 0, 1], 1)
solution.canPlaceFlowers([1, 0, 0, 0, 1], 2)
solution.canPlaceFlowers([0, 0, 1, 0, 1], 1)
'''
Example 1:
Input: flowerbed = [1,0,0,0,1], n = 1
Output: true
Example 2:
Input: flowerbed = [1,0,0,0,1], n = 2
Output: false
'''
|
5f1f408e9714a8da3e9af4eb7996047db5632d68 | kmwestmi/Recitation1 | /Recitation 1.py | 292 | 3.765625 | 4 | bunny=10.4
print(bunny*5)
my_string='hi,how are you'
print(my_string)
print(type(bunny))
points_obtained=40
total_points=50
percentage=(points_obtained/total_points)*100
print(percentage)
x='I am a UB Student','Krissy','Bunny'
print(x[0])
print(x[1])
print(x[-1])
y='Turtle'
print(y[3])
|
e2af476495bbb77224169d16e8127084c9201fe3 | leo96tush/python-programs | /Weighted Graph.py | 253 | 3.546875 | 4 | n = int(input())
a = [ [ 0 for i in range(n)] for j in range(n)]
for i in range(n):
for j in range(n):
if(i==j):
a[i][j]==0
else:
i,j,a[i][j] = int(input()),int(input()),int(input())
print(a)
|
e22f71e0f80dfa579d31d46d0cdce5443ac4c873 | orkunkarag/py-oop-tutorial | /oop-py-code/class-attributes-oop.py | 287 | 4.09375 | 4 | #Class Attributes - attributes attached to classes that don't change from obj to obj
class Person:
number_of_people = 0 #class attribute
def __init__(self, name):
self.name = name
Person.number_of_people += 1
p1 = Person("tim")
p2 = Person("jill")
print(p2.number_of_people)
|
234acfd8c30ae25b679d5f9dfcf63fe15426e0b4 | quarkgluant/boot-camp-python | /day01/ex00/book.py | 2,528 | 3.890625 | 4 | #!/usr/bin/env python3
# -*-coding:utf-8 -*
from datetime import datetime
class Book:
def __init__(self, name, recipe_list):
self._name = name
self._last_update = datetime.now()
self._creation_date = datetime.now()
self._recipe_list = recipe_list
@property
def name(self):
return self._name
@name.setter
def name(self, new_name):
if not new_name:
raise Exception("name cannot be empty")
self._name = new_name
@property
def last_update(self):
return self._last_update
@last_update.setter
def last_update(self, new_time):
if type(new_time) is not datetime:
raise Exception("last update must be of type datetime")
self._last_update = new_time
@property
def creation_date(self):
return self._creation_date
#
# @creation_date.setter
# def creation_date(self, new_time):
# if new_time < 0:
# raise Exception("creation_date must be of type datetime")
# self._creation_date = new_time
@property
def recipe_list(self):
return self._recipe_list
@recipe_list.setter
def recipe_list(self, new_list):
if new_list.keys not in ["starter", "lunch", "dessert"]:
raise Exception("recipe_list must be starter, lunch or dessert")
self._recipe_list = new_list
def get_recipe_by_name(self, name):
"""Print a recipe with the name `name` and return the instance"""
for _, recipe in self.recipe_list.items():
if recipe.name == name:
print(recipe)
return recipe
def get_recipes_by_types(self, recipe_type):
"""Get all recipe names for a given recipe_type """
return [recipe for recipe in self.recipe_list[recipe_type]]
def add_recipe(self, recipe):
"""Add a recipe to the book and update last_update"""
if type(recipe) is Recipe:
self.recipe_list[recipe.recipe_type].append(recipe)
self.last_update = datetime.now()
else:
print(f"{recipe} is not a Recipe")
return
def __str__(self):
"""Return the string to print with the book info"""
txt = f"""
the recipe's book {self.name}, with {', '.join([name[0] for name in [[recipe.name for recipe in recipes] for recipes in self.recipe_list.values()]])}, was made at {self.creation_date}
and updated at {self.last_update}
"""
return txt
|
de6f293720663f6f122908926f914d81a3a0cfd4 | magedu-python22/homework | /homework/02/P22034-beijing-guanpenghui/homework-1.py | 546 | 3.84375 | 4 | #get number
from random import randint
ansnumber = randint(0,999)
print('The answernumber is',ansnumber)
#compare number
while True:
gusnumber = int(input('Pls input a number to compare:'))
if gusnumber > ansnumber:
print('You input number is larger than ansnumber,pls input again')
continue
elif gusnumber < ansnumber:
print('You input number is smaller than ansnumber,pls input again')
continue
else:
print('Congratuation,the number you input is right')
break
# 不用continue的 |
1ba50d3f7574aeef98069df5ce459e94b6ff545d | Ali-Parandeh/Data_Science_Playground | /Datacamp Assignments/Data Engineer Track/7. Command Line Automation in Python/30_readlines_script.py | 1,172 | 4.46875 | 4 | # Backwards day
# A colleague has written a Python script that reverse all lines in a
# file and prints them out one by one. This is an integration tool for
# some NLP (Natural Language Processing) work your department is involved in.
# You want to call their script, reverseit.py from a python program you
# are writing so you can use it as well. Use your knowledge of sys.argv
# and subprocess to write a file, then pass that file to the script that processes it.
import subprocess
# Write a file
with open("input.txt", "w") as input_file:
input_file.write("Reverse this string\n")
input_file.write("Reverse this too!")
# runs python script that reverse strings in a file line by line
run_script = subprocess.Popen(
["/usr/bin/python3", "reverseit.py", "input.txt"], stdout=subprocess.PIPE)
# print out the script output
for line in run_script.stdout.readlines():
print(line)
# <script.py> output:
# b'\n'
# b'gnirts siht esreveR\n'
# b'!oot siht esreveR\n'
# Great work at reusing your colleagues code!
# You were able to write a file then pass that file into the input of an existing Python script which processed your text file.
|
a1e2fc8b4ff11289ce72e8ac6572a6756c38b5fd | L200180088/Algostruk_D | /modul8.py | 4,259 | 3.875 | 4 | ##nomer1
class Stack(object):
def __init__(self):
self.items=[]
def isEmpty(self):
return len(self)==0
def __len__(self):
return len(self.items)
def peek(self):
assert not self.isEmpty()
return self.items[-1]
def pop(self):
assert not self.isEmpty()
return self.items.pop()
def push(self,data):
self.items.append(data)
def cetakHexa(data):
a = Stack()
hx = "0123456789ABCDEF"
while data != 0:
sisa = data%16
data = data//16
a.push(hx[sisa])
st=""
for i in range(len(a)):
st = st + str(a.pop())
return st
##nomer2
class Stack(object):
def __init__(self):
self.items=[]
def isEmpty(self):
return len(self)==0
def __len__(self):
return len(self.items)
def peek(self):
assert not self.isEmpty()
return self.items[-1]
def pop(self):
assert not self.isEmpty()
return self.items.pop()
def push(self,data):
self.items.append(data)
nilai = Stack() #membuat sebuah objek dari kelas Stack yang disimpan di variabel "nilai"
for i in range(16): #untuk i dalam range 16
if i % 3 == 0: #jika i habis dibagi 3, maka:
nilai.push(i) #meletakkan i di variabel "nilai"
print(nilai.items)
##nomer3
class Stack(object):
def __init__(self):
self.items=[]
def isEmpty(self):
return len(self)==0
def __len__(self):
return len(self.items)
def peek(self):
assert not self.isEmpty()
return self.items[-1]
def pop(self):
assert not self.isEmpty()
return self.items.pop()
def push(self,data):
self.items.append(data)
nilai1 = Stack() #membuat sebuah objek dari kelas Stack yang disimpan di variabel "nilai1"
for i in range (16) : #untuk i dalam range 16
if i % 3 == 0: #jika i habis dibagi 3, maka:
nilai1.push(i) #meletakkan i di variabel "nilai1"
elif i % 4 == 0: #dan jika i habis dibagi 4, maka:
nilai1.pop() #mengembalikan nilai dari item posisi paling atas dari variabel
#"nilai" lalu menghapusnya "nilai"
print(nilai1.items)
##nomer4
class Queue(object):
def __init__(self):
self.qlist = []
def isEmpty(self):
return len(self) == 0
def __len__(self):
return len(self.qlist)
def enqueue(self, data):
self.qlist.append(data)
def dequeue(self):
assert not self.isEmpty(), "Antrian sedang kosong."
return self.qlist.pop(0)
def getFrontMost(self): #untuk mengetahui item yang paling depan tanpa menghapusnya
assert not self.isEmpty(), "Antrian sedang kosong."
return self.qlist[0]
def getRearMost(self): #untuk mengetahui item yang paling belakang tanpa menghapusnya
assert not self.isEmpty(), "Antrian sedang kosong."
return self.qlist[-1]
c = Queue()
c.enqueue(28)
c.enqueue(19)
c.enqueue(45)
c.enqueue(13)
c.enqueue(7)
print (c.qlist)
print (c.getFrontMost())
print (c.getRearMost())
print (c.qlist)
##nomer5
class PriorityQueue(object):
def __init__(self):
self.qlist = []
def __len__(self):
return len(self.qlist)
def isEmpty(self):
return len(self) == 0
def enqueue(self, data, priority):
entry = _PriorityQEntry(data, priority) #memanggil object _PriorityQEntry
self.qlist.append(entry)
def dequeue(self):
A = []
for i in self.qlist:
A.append(i)
s = 0
for i in range(1, len(self.qlist)):
if A[i].priority < A[s].priority:
s = i
hasil = self.qlist.pop(s)
return hasil.item
class _PriorityQEntry(object):
def __init__(self, data, priority):
self.item = data
self.priority = priority
d = PriorityQueue()
d.enqueue("Jeruk", 4)
d.enqueue("Tomat", 2)
d.enqueue("Mangga", 0)
d.enqueue("Duku", 5)
d.enqueue("Pepaya", 2)
print (d.dequeue())
print (d.dequeue())
print (d.dequeue())
print (d.dequeue())
print (d.dequeue())
|
fac0c3e3dbefcc4eef16ad6818d7303e7a402f3d | cbohara/automate_the_boring_stuff | /csv/random_students.py | 1,011 | 3.9375 | 4 | import sys
import csv
import random
def main(args):
"""Read in csv file, grab student names, and choose random student names."""
try:
number_of_winners = int(sys.argv[1])
except IndexError:
print('python3 name_generator.py [number of winners]')
else:
with open('/Users/cbohara/code/automate/data/dg2017.csv', 'r') as f:
f_reader = csv.reader(f)
# create list of students from csv file
students = [line[3] for line in f_reader]
# delete the csv header
del students[0]
# choose number of winners based on the input number
for i in range(number_of_winners):
# find current winner
current = random.choice(students)
# print current winner
print(current)
# remove current student from the list to avoid repeats
students.remove(current)
if __name__ == "__main__":
sys.exit(main(sys.argv))
|
ce2af217d7b097c3017721007bb5813dbee1ab4a | falondarville/practicePython | /passwordGenerator.py | 811 | 4 | 4 | # Write a password generator in Python. Be creative with how you generate passwords - strong passwords have a mix of lowercase letters, uppercase letters, numbers, and symbols. The passwords should be random, generating a new password every time the user asks for a new password. Include your run-time code in a main method.
import random, string
num_one = str(random.randint(1, 1000))
num_two = str(random.randint(1, 1000))
num_three = str(random.randint(1, 1000))
letter_one = random.choice(string.ascii_letters)
letter_two = random.choice(string.ascii_letters)
letter_three = random.choice(string.ascii_letters)
punctuation = random.choice(string.punctuation)
def generate_password():
return num_one + letter_one + num_two + letter_two + num_three + letter_three + punctuation
print(generate_password())
|
8e0a5df701af2ba80cb749e9bb8f3f80e288de15 | AdamZhouSE/pythonHomework | /Code/CodeRecords/2462/61406/307553.py | 286 | 3.546875 | 4 | source = input().split(',')
flag = False
for a in range(1,len(source)-1):
if int(source[a])>int(source[a-1]):
if int(source[a])>int(source[a+1]):
print(a)
flag = True
break
if not flag:
index=source.index(max(source))
print(index) |
17856c2970b029695481229c09211ecd044c3c68 | sandinocoelho/URI-Online-Judge | /1017.py | 126 | 3.578125 | 4 | # -*- coding: utf-8 -*-
spentTime = int(input())
speed = int(input())
result = (spentTime*speed) / 12
print("%.3f" %result) |
8af06e5994b12c4ac02f9e4d11eb0a690e98e36f | abhisheksingh75/Practice_CS_Problems | /Sorting/Chocolate Distribution.py | 1,111 | 3.53125 | 4 | """
Given an array A of N integers where each value represents number of chocolates in a packet. i-th can have A[i] number of chocolates. There are B number students, the task is to distribute chocolate packets following below conditions:
1. Each student gets one packet.
2. The difference between the number of chocolates in packet with maximum chocolates and packet with minimum chocolates given to the students is minimum.
Return the minimum difference (that can be achieved) between maximum and minimum number of chocolates distributed. CONSTRAINTS
0 <= N <= 10^5
1 <= A[i] <= 10^6
0 <= B <= 10^5
SAMPLE INPUT
A : [3, 4, 1, 9, 56, 7, 9, 12]
B : 5
SAMPLE OUTPUT
6
EXPLANATION
Minimum Difference is 6
The set goes like 3,4,7,9,9 and the output
is 9-3 = 6
"""
class Solution:
# @param A : list of integers
# @param B : integer
# @return an integer
def solve(self, A, B):
A.sort()
if B == 0 or len(A) == 0:
return 0
min_diff = 1<<31
for i in range(len(A)-B+1):
min_diff = min(min_diff, A[i+B-1]-A[i])
return min_diff
|
a365a6c8ffa3a7bf462dfe20ddf414860c21281e | wscnm/PythonScript | /SocketChat/Server.py | 1,227 | 3.625 | 4 | #!/usr/bin/python
# coding=UTF-8
'''Socket TCP服务端'''
import socket
import time, threading
#启动一个socket对象,监听9999端口
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind(('0.0.0.0', 9999))
#调用listen()方法开始监听端口,传入的参数指定等待连接的最大数量:
s.listen(5)
print('Waiting for connection...')
def tcplink(sock, addr):
print('Accept new connection from %s:%s...' % addr)
def tcpSend(sock, addr):
print("Please Input Your Message")
while True:
# 发送数据:
data = input("")
sock.send(b"server:" + data.encode('utf-8'))
def tcpRece(sock, addr):
while True:
#接收传输过来的数据
data = sock.recv(1024)
print(data.decode('utf-8'))
while True:
# 接受TCP连接并返回(sock,address),其中sock是新的套接字对象,可以用来接收和发送数据。address是连接客户端的地址。
sock, addr = s.accept()
# 创建接收线程来处理TCP连接:
receThreading = threading.Thread(target=tcpRece, args=(sock, addr))
receThreading.start()
# 创建发送线程来处理TCP连接:
sendThreading = threading.Thread(target=tcpSend, args=(sock, addr))
sendThreading.start() |
d10b3d51c1b416cc695d9f54c40e215a0980ec01 | kunal121/ALL-Python | /file.py | 397 | 3.578125 | 4 | # file handling
# open a file
fo=open("foo.txt","w+")
fo.write("python is awsome")
fo.close()
# modes in file
a+
r+
rb+
w+
b+
# methods in file
fo.close()
fo.read(10)
fo.tell() #gives position of the pointer
fo.seek(0,0)
fo.closed# file is closed or not
fo.mode
fo.name# give the file name
#os
import os
os.rename('foo.txt',"foo1.txt")
os.remove('foo.txt')
os.mkdir('mkdir_name')
os.getcwd()
|
253e3db4bf00e3c94a99ca55f64d0a3639285713 | allanstone/cursoSemestralPython | /TerceraClase/tareaIMC.py | 587 | 3.984375 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#Calculo del IMC
while True:
peso = float(input("Introduzca su peso"))
altura = float(input ("Introduzca su altura"))
IMC=peso/altura**2
print("IMC:",IMC)
if IMC<=18.0:
print("Peso demasiado bajo")
elif IMC<=24.9:
print("Su peso es normal felicidades")
elif IMC<=29.9:
print("Tiene sobrepeso, vigile su dieta")
elif IMC>29.9:
print("Obesidad grave, consulte su médico")
res=input("Desea salir el programa?: ")
if res=="si" or res=="Si" or res=="yes":
break
print("Fin del programa ")
|
baadfaacf4fa2b9e356f676f7375c4ec885f9f90 | er3456qi/DjangoPolls | /polls/models.py | 1,361 | 3.5 | 4 | import datetime
from django.db import models
from django.utils import timezone
# Create your models here.
class Question(models.Model):
"""
Each field is represented by an instance of a Field class
– e.g., CharField for character fields and DateTimeField for datetime.
This tells Django what type of data each field holds.
The name of each Field instance (e.g. question_text or pub_date) is the field’s name
You can use an optional first positional argument to a Field to designate a human-readable name.
That’s used in a couple of introspective parts of Django, and it doubles as documentation.
If this field isn’t provided, Django will use the machine-readable name.
In this example, we’ve only defined a human-readable name for Question.pub_date.
"""
question_text = models.CharField(max_length=200)
pub_date = models.DateTimeField('date published')
def was_published_recently(self):
now = timezone.now()
return now - datetime.timedelta(days=1) <= self.pub_date <= now
def __str__(self):
return self.question_text
class Choice(models.Model):
question = models.ForeignKey(Question, on_delete=models.CASCADE)
choice_text = models.CharField(max_length=200)
votes = models.IntegerField(default=0)
def __str__(self):
return self.choice_text |
fa6fbc06ad233eca5cafef667450bfc3194ddf2b | nimisha727/python-challenge | /pybank.py | 2,308 | 3.890625 | 4 | import os
import csv
# joining the path:
pybank_csv_path = os.path.join("resources","budget_data.csv")
# Assigning the file name:
file = pybank_csv_path
print(file)
# Now opening a file
with open(file, "r") as jumbled_data:
unjumbled_data = csv.reader(jumbled_data, delimiter=",")
# skip header
next(unjumbled_data, None)
row_count = 0
total_amount = 0
greatest_inc = 0
greatest_dec = 0
monthly_difference = 0
first_row = next(unjumbled_data)
prev_row = int(first_row[1])
total_difference = 0
for row in unjumbled_data:
row_count = row_count + 1
total_amount = total_amount + int(row[1])
monthly_difference = int(row[1]) - prev_row
prev_row = int(row[1])
total_difference = monthly_difference + total_difference
if greatest_inc <= int(row[1]):
greatest_inc = int(row[1])
greatest_date = row[0]
if greatest_dec >= int(row[1]):
greatest_dec = int(row[1])
greatest_dec_date = row[0]
average = round(total_difference/row_count)
print("=======================================")
print(" Financial Analysis ")
print("========================================")
print("Total months: " + str(row_count))
print("Total amount: $" + str(total_amount))
print("total average difference is" + str(average))
print("Greatest increase in Revenue: " + greatest_date + " and ($" + str(greatest_inc) +")")
print("Greatest_dec_date in Revenue: " + greatest_dec_date + " and ($" + str(greatest_dec) +")")
# creating a new file
new_file = open("Resources/analysis.txt", "w")
new_file.write("=======================================\n")
new_file.write(" Financial Analysis \n")
new_file.write("========================================\n")
new_file.write("Total months: " + str(row_count) + "\n")
new_file.write("Total amount: $" + str(total_amount) + "\n")
new_file.write("total average difference is " + str(average) + "\n")
new_file.write("Greatest increase in Revenue: " + greatest_date + " and ($" + str(greatest_inc) +")\n")
new_file.write("Greatest_dec_date in Revenue: " + greatest_dec_date + " and ($" + str(greatest_dec) +")\n") |
68fbe79e78575d44a6c82387fca5a286390d28ab | 08zhangyi/Some-thing-interesting-for-me | /Python生物信息学数据管理/python-for-biologists/05-biopython/19-sequences/transcribe_translate.py | 937 | 3.640625 | 4 | '''
Transcribe & translate a DNA sequence.
-----------------------------------------------------------
(c) 2013 Allegra Via and Kristian Rother
Licensed under the conditions of the Python License
This code appears in section 19.2.2 of the book
"Managing Biological Data with Python".
-----------------------------------------------------------
'''
from Bio import Seq
from Bio.Alphabet import IUPAC
from Bio.SeqRecord import SeqRecord
from Bio import SeqIO
# read the input sequence
dna = open("hemoglobin-gene.txt").read().strip()
dna = Seq.Seq(dna, IUPAC.unambiguous_dna)
# transcribe and translate
mrna = dna.transcribe()
protein = mrna.translate()
# write the protein sequence to a file
protein_record = SeqRecord(protein, id='sp|P69905.2|HBA_HUMAN',
description="Hemoglobin subunit alpha, Homo sapiens")
outfile = open("HBA_HUMAN.fasta", "w")
SeqIO.write(protein_record, outfile,"fasta")
outfile.close()
|
5c2bc6b20655557f027432cdf7ce5e763ae24851 | maples1993/Strike-to-Offer | /q52.py | 968 | 3.78125 | 4 | """
Date: 2018/9/3
"""
class Solution:
def process(self, s, pattern):
if not s and not pattern: # 匹配完成
return True
if s and not pattern: # 有多余字符
return False
# 处理'.'和字符
if len(pattern) == 1 or pattern[1] != '*':
if s and pattern[0] == '.' or s and s[0] == pattern[0]:
return self.process(s[1:], pattern[1:])
# 处理'*'
if len(pattern) > 1 and pattern[1] == '*':
if s and pattern[0] == '.' or s and s[0] == pattern[0]:
return self.process(s[1:], pattern[2:]) \
or self.process(s, pattern[2:]) \
or self.process(s[1:], pattern)
else:
return self.process(s, pattern[2:])
def match(self, s, pattern):
# write code here
s = list(s)
pattern = list(pattern)
return self.process(s, pattern)
|
b9476a58856716fc0ab946c308aac44c891db0c9 | eduardopds/Programming-Lab1 | /tiro/tiro.py | 656 | 3.71875 | 4 | # coding: utf-8
# Aluno: Eduardo Pereira
# Matricula: 117210342
# Atividade: Tiro ao alvo
lista = []
soma = 0
import math
y1 = 0.0
x1 = 0.0
while True:
x2 = float(raw_input())
y2 = float(raw_input())
distancia = math.sqrt((x2 - x1) ** 2 + (y2 -y1) ** 2)
if distancia <= 200.0:
soma += distancia
lista.append(distancia)
if distancia > 200.0:
break
x2 = x1
y2 = y1
melhor_tiro = lista[0]
for i in lista:
if i <= melhor_tiro:
melhor_tiro = i
print'%.2f cm (melhor tiro)' % i
else:
print'%.2f cm' % i
print'--'
print'num tiros: %d' % len(lista)
print'melhor tiro: %.2f cm' % melhor_tiro
print 'distancia media: %.2f cm' % (soma / len(lista))
|
236ea5059a3b27cb774455cd794d3498ed243d16 | pantDevesh/1ProblemEveryday | /Problem_037.py | 1,014 | 3.640625 | 4 | # Search in 2d Matrix
# import numpy as np
class Solution:
def searchMatrix(self, matrix, target):
if not matrix or not matrix[0]:
return False
nrows = len(matrix)
ncols = len(matrix[0])
low = 0
high = nrows * ncols - 1
while low <= high:
mid = low + (high - low) // 2
row, col = divmod(mid, ncols)
if matrix[row][col] == target:
return True
elif matrix[row][col] < target:
low = mid + 1
else:
high = mid - 1
return False
if __name__ == '__main__':
m,n = map(int, input().split())
matrix = [[int(input()) for i in range(n)] for j in range(m)]
# 1 line input separated by space
# matrix = list(map(int, input().split()))
# matrix = np.array(matrix).reshape(m,n)
target = int(input())
obj = Solution()
ans = obj.searchMatrix(matrix, target)
print(ans)
|
d96a9573c935d6a50b5cac51f782e3cd056df0b2 | im876/Python-Codes | /Codes/terms_of_AP.py | 2,877 | 3.734375 | 4 | '''
Problem Statement
Ayush is given a number ‘X’. He has been told that he has to find the first ‘X’ terms of the series 3 * ‘N’ + 2,
which are not multiples of 4. Help Ayush to find it as he has not been able to answer.
Example: Given an ‘X’ = 4. The output array/list which must be passed to Ayush will be [ 5, 11, 14, 17 ].
Input Format:
The first line contains a single integer ‘T’ representing the number of test cases.
The first line of each test case will contain one integer, ‘X’ that denotes the number of terms he has to answer.
Output Format:
For each test case, return a vector with the first ‘X’ integer of the series 3 * ‘N’ + 2, which is not multiple of 4.
Output for every test case will be printed in a separate line.
Note:
You don’t need to print anything; It has already been taken care of.
Constraints:
1 <= T <= 10^2
1 <= X <= 10^5
Time Limit: 1 sec
Sample Input 1:
2
2
5
Sample Output 1:
5 11
5 11 14 17 23
Explanation For Sample Input 1:
In the first test case, the first number is 5, while the second number cannot be 8 as it is divisible by 4, and so, the next number
is directly 11 as it is not divisible by 4.
In the second test case, the first two numbers are 5 and 11. While following three numbers are 14, 17 and 23 for ‘N’ = 4, 5 and 7
respectively. 20 is divisible by 4, and thus, 20 cannot be included in the list.
Sample Input 2:
2
7
8
Sample Output 2:
5 11 14 17 23 26 29
5 11 14 17 23 26 29 35
Explanation For Sample Input 2:
In the first test case, the first five numbers are 5, 11, 14, 17 and 23. While the following two numbers are 26 and 29 for N = 8 and 9 respectively.
In the second test case, the seven numbers are explained in the above test case and for N = 10, we get the number 32,
which is divisible by 4 and thus, we reject it. For N = 11, the number is 35 and is not divisible by 4.
'''
'''
Time Complexity : O(N)
Space Complexity : O(N)
Where N is the number of elements we have to find of the A.P. series.
'''
def termsOfAP(x):
# Declaring a vector to store all the elements which are to be returned.
ans = [0 for i in range(x)]
# Declaring variable to have a look at number of elements in 'ANS' vector.
got = 0
# Pointing to current number of series 3N + 2.
curr = 5
# Running a loop until total number of elements in 'ANS' is not equal to 'X'.
while(got != x):
# If curr value of series is not divisible by 4 then we will append it at
# the end of 'ANS' vector and increment the value of 'GOT' by 1.
if curr % 4 != 0:
ans[got] = curr
got += 1
# Getting the next value of series by incrementing by 3.
curr += 3
# Finally we will return our 'ANS' vector.
return ans
x = int(input())
print(termsOfAP(x))
|
ec483745fbf43aedfcab1573f9fc85c82265ac7f | roobixkub/Sushi-Stop | /Sushi-Stop/play.py | 5,045 | 3.546875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sun Apr 26 01:40:09 2020
@author: Nate
"""
import random
from deck import deck
from scoring import Scoring
from hands import Hands
def player_reset():
player_set_up = []
player_count = range(0, players)
player_num = 1
for player in player_count:
pile = []
wasabi = 0
chopsticks = 0
player_name = input("Player {}'s name? ".format(player_num))
hand = []
puddings = 0
score = 0
player_state = [player_num, player_name, hand, pile, wasabi, chopsticks, puddings, score]
player_set_up.append(player_state)
player_num += 1
return player_set_up
def deal_hand():
hand = []
while len(hand) < hand_size:
hand.append(game_deck.pop())
return hand
def maki_score():
maki_count_1st = 0
maki_score_1st = None
maki_count_2nd = 0
maki_score_2nd = None
maki_score_1st_tie = []
maki_score_2nd_tie = []
for player in player_set_up:
points = Scoring(player[3])
maki_count = points.total()[1]
if maki_count >= maki_count_1st:
if maki_count > maki_count_1st:
if maki_count_1st >= maki_count_2nd and maki_count_1st != 0:
if maki_count_1st > maki_count_2nd:
maki_count_2nd = maki_count_1st
maki_score_2nd = maki_score_1st
maki_score_2nd_tie = maki_score_1st_tie
elif maki_count == maki_count_2nd:
maki_score_2nd_tie.append(maki_score_1st)
maki_score_2nd_tie.append(maki_score_1st_tie)
maki_count_1st = maki_count
maki_score_1st = player[1]
maki_score_1st_tie = [player[1]]
elif maki_count == maki_count_1st:
maki_score_1st_tie.append(player[1])
maki_score_1st = None
elif maki_count >= maki_count_2nd:
if maki_count > maki_count_2nd:
maki_count_2nd = maki_count
maki_score_2nd = player[1]
maki_score_2nd_tie = [player[1]]
elif maki_count == maki_count_2nd:
maki_score_2nd_tie.append(player[1])
maki_score_2nd = None
maki_scores = (maki_score_1st, maki_score_2nd, maki_score_1st_tie, maki_score_2nd_tie)
return maki_scores
def pudding_score():
pudding_top = 1
pudding_bottom = 0
pudding_champ_tie = []
pudding_loser_tie = []
for player in player_set_up:
if player[6] >= pudding_top:
if player[6] > pudding_top:
if pudding_loser_tie == []:
pudding_bottom = pudding_top
pudding_loser_tie = pudding_champ_tie
pudding_top = player[6]
pudding_champ_tie = [player[1]]
elif player[6] == pudding_top:
pudding_champ_tie.append(player[1])
elif player[6] == pudding_bottom:
pudding_loser_tie.append(player[1])
elif player[6] < pudding_top and pudding_loser_tie == []:
pudding_loser_tie.append(player[1])
elif player[6] < pudding_bottom:
pudding_bottom = player[6]
pudding_loser_tie = [player[1]]
for player in player_set_up:
if player[1] in pudding_champ_tie:
player[7] += int(6 / len(pudding_champ_tie))
elif player[1] in pudding_loser_tie:
player[7] -= int(6 / len(pudding_loser_tie))
def score_it():
for player in player_set_up:
points = Scoring(player[3])
total_score = points.total()[0]
player[6] += points.total()[2]
if player[1] == maki_scores[0]:
total_score += 6
elif player[1] == maki_scores[1]:
total_score += 3
elif player[1] in maki_scores[2]:
total_score += int(6 / len(maki_scores[2]))
elif player[1] in maki_scores[3]:
total_score += int(3 / len(maki_scores[3]))
player[7] += total_score
return
valid = False
while not valid:
try:
players = int(input('How many players(2-5)? '))
if players < 2 or players > 5:
raise ValueError('Sushi-Stop can only be played with 2 to 5 players')
valid = True
except ValueError as ve:
print(ve)
if players == 2:
hand_size = 10
elif players == 3:
hand_size = 9
elif players == 4:
hand_size = 8
elif players == 5:
hand_size = 7
game_deck = list(deck)
shuffled_deck = random.shuffle(game_deck)
player_set_up = player_reset()
turn = 1
while turn < 4:
for player in player_set_up:
player[2] = deal_hand()
player[3] = []
player[4] = 0
player[5] = 0
test = Hands(player_set_up, turn)
test.play()
maki_scores = maki_score()
total_scores = score_it()
turn += 1
pudding_score()
print("\n\n\nFinal Score: \n")
for player in player_set_up:
print("{}: {}".format(player[1], player[7]))
|
dd027bb3616172d19b83a97223393882641af94a | stephen-lazaro/Misc | /py/GeneralField.py | 5,240 | 3.53125 | 4 | def Legendre(top, bottom): #This is defined field independently since the Legendre symbol is a morphism really.
top = top%bottom
if top==1 or top ==0:
return 1
if top%2==0 and top!=2:
return Legendre(2, bottom)*Legendre(top/2, bottom)
if top == bottom-1:
if bottom%4 == 1:
return 1
if bottom%4 == 3:
return -1
if top == 2:
if bottom%8 == 1 or bottom%8 == 7:
return 1
if bottom%8 == 3 or bottom%8 == 5:
return -1
else:
if top%4 == 1 or bottom%4 == 1:
return Legendre(bottom, top)
if top%4 == 3 and bottom%4 == 3:
return -Legendre(bottom, top)
#this should hopefully calculate the legendre symbol for our two numbers
#there appears to be a case missing however. Sometimes we get a null outpout
class GeneralField():
def __init__(self, prime, power):
self.elements = range(0, prime**power)
self.characteristic = prime
self.cardinality = len(self.elements)
def add(self, a, b):
return Element(self, (a+b))
def mult(self, a, b):
return Element(self, (a*b))
def sub(self, a, b):
return Element(self, (a-b))
def is_square(self, number, is_prime = False):
if is_prime:
return self.exponent(number, (self.cardinality - 1) // 2, self.cardinality) == 1
if Legendre(number, field_size)==1:
return True
return False
def exponent(self, number, exponent):
if exponent == 0:
return 1
if number or exponent is float:
try:
number = int(number)
exponent = int(exponent)
except:
print('You\'re number and exponent can\'t be true floats.')
cut = bin(exponent).index('b') #Python nicely gives us 0xb but we don't need that information
binexp = bin(exponent)[cut+1:][::-1] #Take the binary powers and reverse them
exponents = [i for i in range(0, len(binexp)) if int(binexp[i])==1] #make an array of when the power is 1
powers = [number] #Here we make the powers for the square and multiply algorithm
for i in range(1, max(exponents)+1):
powers.append((powers[i-1]**2)%field_size)
r = 1
for j,val in enumerate(powers): #Here we just multiply through the values
if j in exponents:
r = (r*val)%field_size
return Element(self, r%self.cardinality) #one last call to modulus to guarantee, then return
def square_root(self, number):
if not self.is_square(number):
return None
if self.cardinality == 2:
return number,number,number
elif self.cardinality%4 == 3:
r = self.exponent(2 * number, (self.cardinality - 5)//4)
return Element(self, number),Element(self, r),Element(self, field_size-r)
elif self.cardinality % 8 == 5:
v = self.exponent(2 * number, (self.cardinality - 5)//8)
i = (2 * number * v * v) % self.cardinality
r = (number*v*(i - 1)) % self.cardinality
return Element(self, number),Element(self, r),Element(self, self.cardinality-r)
elif self.cardinality % 8 == 1:
r = self.shanks(number) #this needs replacing since having a separate shanks method sucks
return Element(self, number),Element(self, r),Element(self, self.cardinality-r)
return None
def of(self, number):
return Element(self, number)
class Element():
def __init__(self, field, data):
self.data = data%field.cardinality
self.field = field
def __add__(self, other):
if self.field == other.field:
return self.field.add(self.data, other.data)
return None
def __sub__(self, other):
if self.field == other.field:
return self.field.sub(self.data, other.data)
return None
def __mult__(self, other):
if self.field == other.field:
return self.field.mult(self.data, other.data)
return None
__rmult__ = __mult__
__radd__ = __add__
def exp(self, other):
if other == self.field.characteristic:
return Element(self.field, 1)
else:
return self.field.exponent(self, other)
def square_root(self):
return self.field.square_root(self)
#Implement also a __lt__, __gt__, and etc
'''
#The following method can be severely generalized by passing it a method as its final argument, this being the polynomial relation to be raised to the higher power of the prime. As written, we require that there be implemented an element class which the arithmetic is operating on
The idea is to take things that are defined mod p**n and raise them mod p**n+1
This shouldn't be hard using Hensel's Lemma
'''
#Tests:
field_5 = GeneralField(5, 1)
print(field_5.cardinality)
print([i for i in field_5.elements])
print(field_5.characteristic)
print(field_5.add(3, 7))
print(field_5.add(3, 7).data)
print(field_5.sub(3, 7))
print(field_5.sub(3, 7).data)
print(field_5.of(77))
a, b = field_5.of(77), field_5.of(89)
print(a + b)
print((a + b).data)
|
69e750b1ad5799d01511ce0cc4acc0a842560def | vash050/start_python | /lesson_1/shcherbatykh_vasiliy/z_4.py | 566 | 4.03125 | 4 | # 4) Пользователь вводит целое положительное число.
# Найдите самую большую цифру в числе.
# Для решения используйте цикл while и арифметические операции.
# num = int(input('введите положительное число: '))
num = int('12459785')
number_big = 0
while num > 0:
number = num % 10
if number > number_big:
number_big = number
num //= 10
print(f'Самая большая цифра: {number_big}')
|
c7a83bf76bbc725472daf23b4d525c4a362d0dd3 | Audarya07/Daily-Flash-Codes | /Week12/Day4/Solutions/Python/prog5.py | 281 | 4.03125 | 4 | n = int(input("Enter n:"))
r = int(input("Enter r:"))
def fact(num):
fact = 1
for i in range(num,0,-1):
fact *= i
return fact
combi = fact(n) / (fact(r) * fact(n-r))
print("There are",int(combi),"combinations to distribute",r,"medals amongst",n,"employees")
|
86ecede60f7577c87af7b9147930c34bddb3ecc6 | cklein/magick | /examples.py | 7,165 | 3.78125 | 4 |
# Examples from the PythonMagick tutorial
# In general, ImageMagick commands that altered the images in place
# are implemented as methods on the image object.
# While commands that returned a new image are methods of magick
# and can take any object that can be converted to an image as
# the image argument.
import magick
from Numeric import *
import Numeric
def load_save():
img = magick.image('logo:')
img.write('newfile.png')
img.filename='anotherway.png'
img.write()
def test_resize():
half = magick.minify('logo:') #reduce by factor of 2
double = magick.magnify(half) # back to the same size (blurred image)
# resize also accepts a blur factor and a filter type argument.
newsize = magick.resize('logo:',(200,200)) # change aspect ratio
shrink = magick.resize('logo:',(200,-1)) # keep aspect ratio
expand = magick.resize('logo:',(-1,1.3)) # expand 1.3 times
# I could also use sample, scale, or thumbnail which use different
# arguments and use different methods to do the resizing.
# Thumbnail is similar to resize, but without blur and method arguments
# Sample and scale do not understand floating point values as
# resizing factors.
#b = magick.image("testimages/input.m2v") # a movie sequence.
#len(b) # should be 6
#element = b[0] # extract a piece
def effects():
img = magick.image('testimages/original.jpg')
new = magick.blur(img,3,1.5)
new = magick.blur('testimages/original.jpg',3,1.5) #also works
new = magick.rotate(img,20)
new = img.copy()
new.contrast(10)
out = magick.border(img,6,6,bordercolor='red')
out = magick.charcoal(img,1,0.5)
out = magick.colorize(img, 'red', 0.30)
def composition():
img = magick.image('testimages/original.jpg')
small = magick.minify(img)
small.opacity = 0.3 * magick.iMaxRGB
img.composite(small, 5, 5, 'over')
return img
# Animations are simply image sequences with more than one
def animate1():
img = magick.scale('testimages/original.jpg',(100,-1))
img2 = magick.blur(img, 5, 1.5)
imgs = magick.image(img, img2)
imgs.write('ani1.gif')
return
def createFrame(val):
val2 = 2.0*pi*val/360
radius = 26
x = cos(val2)*radius
y = sin(val2)*radius
# uses the savespace property of Numeric arrays to be sure
# that the output of multiplication by maxRGB stays the same type.
# MaxRGB is actually a rank-0 Numeric savespace array of the
# quantum type.
img = magick.image(Numeric.ones((60,60,3)) * magick.MaxRGB)
dc = magick.newdc()
dc.fill = 'white'
dc.stroke = 'red'
dc.stroke_width = 3
dc.circle(30,30,radius)
img.draw(dc)
dc.stroke = 'blue'
dc.line(30,30,30+x,30+y)
img.draw(dc)
return img
def animate2():
images = magick.image(*[createFrame(x) for x in range(0,360,10)])
images.write('clock.gif')
return images
def draw_shapes():
img = magick.image('xc:#ffffffff',size='150x100') # 'xc:transparent' should also work
dc = magick.newdc() # new "Drawing context with ImageMagick defaults"
#dc.text(10,10,'some drawings ...')
#img.draw(dc)
dc.stroke='blue'
dc.fill='none'
dc.stroke_width = 3
dc.circle(50,50,10) # radius of 10
img.draw(dc) # draw the primitives and clear them (keeps the state)
dc.stroke='red'
dc.rect(140,90,110,60)
dc.line(110,60,125,40)
dc.line(140,60,125,40)
img.draw(dc)
coords = [[10,90],[120,90],[70,20],[140,10]] # can also be 1-D
dc.bezier(coords)
dc.stroke='green'
img.draw(dc)
return img
def draw_bar():
data = [('red',30),('blue',80),('green',60)]
img = magick.image('xc:white',size='100x150')
dc = magick.newdc()
dc.stroke = 'black'
dc.stroke_width = 1
left = 10
bottom = 90
size = 20
for color,height in data:
dc.fill = color
dc.rect(left,bottom,left+size,bottom-height)
img.draw(dc)
left += size+2
return img;
# Inspiration for the following examples taken from Rmagick site:
# in the Drawing Demonstration.
def make_hatch(width, height, background='white', color='lightcyan2', sp=10):
hatch = Numeric.ones((height, width,3)) * magick.MaxRGB
val = magick.name2color(color)
hatch[:,:,:] = magick.name2color(background)[:-1]
hatch[sp::sp,:,:] = val[:-1]
hatch[:,sp::sp,:] = val[:-1]
img = magick.border(hatch, sp, sp, bordercolor=background)
return img
def draw_graph():
img = make_hatch(240,300)
gc = magick.newdc()
gc.stroke='red'
gc.stroke_width = 3
gc.fill='none'
gc.ellipse(120,150,80,120,0,270)
img.draw(gc)
gc.stroke='gray50'
gc.stroke_width=1
gc.circle(120,150,4)
gc.circle(200,150,4)
gc.circle(120,30,4)
gc.line(120,150,200,150)
gc.line(120,150,120,30)
img.draw(gc)
gc.stroke='transparent'
gc.fill = 'black'
#gc.set_font('/Users/cklein/Library/Fonts/Topaz-8.ttf')
#gc.text(130,35,"End")
#gc.text(188, 135, "Start")
#gc.text(130, 95, "Height=120")
#gc.text(55,155, "Width=80")
img.draw(gc)
return img
def draw_bezier():
img = make_hatch(240,300)
gc = magick.newdc()
# Draw curve
gc.stroke='blue'
gc.stroke_width = 3
gc.fill = 'none'
gc.bezier([45,150, 45,20, 195,280, 195,150])
img.draw(gc)
# Draw endpoints
gc.stroke='gray50'
gc.stroke_width=1
gc.circle(45,150,4)
gc.circle(195,150,4)
img.draw(gc)
# Draw control points
gc.fill = 'gray50'
gc.circle(45,17,4)
gc.circle(195,280,4)
# Connect the points
gc.line(45,150, 45,17)
gc.line(195,280, 195,150)
img.draw(gc)
# Annotate
gc.stroke='transparent'
gc.fill= 'black'
#gc.text(27, 175, "45,150")
#gc.text(175,138, "195,150")
#gc.text(55,22, "45,20")
#gc.text(143,285, "195,280")
img.draw(gc)
return img
def draw_svgpath():
img = make_hatch(240,300)
gc = magick.newdc()
gc.fill = 'red'
gc.stroke = 'blue'
gc.stroke_width = 2
gc.path("M120,150 h-75 a75,75 0 1, 0 75, -75 z")
img.draw(gc)
gc.fill = 'yellow'
gc.path("M108.5,138.5 v-75 a75, 75 0 0,0 -75, 75 z")
img.draw(gc)
return img
def draw_poly():
img = make_hatch(240,300)
gc = magick.newdc()
gc.stroke = "#001aff"
gc.stroke_width = 3
gc.fill = "#00ff00"
x = 120
y = 32.5
gc.polygon([[x,y],
[x+29,y+86],
[x+109,y+86],
[x+47, y+140],
[x+73, y+226],
[x, y+175],
[x-73, y+226],
[x-47, y+140],
[x-109, y+86],
[x-29, y+86]])
img.draw(gc)
return img
if __name__ == "__main__":
load_save()
test_resize()
effects()
composition() #.display()
animate1()
animate2() #.animate()
draw_shapes() #.display()
draw_bar() #.display()
img = draw_graph() #.display()
img.write("draw_graph.png")
draw_bezier() #.display()
draw_svgpath() #.display()
draw_poly() #.display()
|
b4d8662148961205066e5250974ebaf09df17ae2 | Sreejakk/python_basics | /Projects/ITC558assignment3YourName.py | 12,723 | 3.890625 | 4 | def menu():
student_file = 'students.txt'
try:
stu_file = open(student_file, 'r') #reads students.txt file
except IOError:
stu_file = open(student_file, 'w') #creates students.txt file if not exists
assessment_file = 'assessments.txt'
try:
marks_file = open(assessment_file, 'r') #reads assessments.txt file
except IOError:
marks_file = open(assessment_file, 'w') #creates assessments.txt file if not exists
option = None #sets option none
print("\n------------------------------------\nWelcome to the Student and Assessment Management System \n")
print("select operation from below options...")
print(" <A>add details of a student. \n <I>insert assignment marks of a student. \n <S>search assessment marks for a student. \n <Q>quit.\n------------------------------------\n")
while option is None:
option = input("Enter Option : ") #gets option from user
option = option.lower() #converts option to lower
if option == "a":
add_student() #calls add_student fuction for adding student
elif option == "i":
insert_marks() #calls insert_marks fuction for adding student marks
elif option == "s":
search_student() #call search_student fuction for searching student
elif option == "q":
quit() #exists the program
else:
print("Invalid Option! Try again")
option = None
def add_student():
student_id = 0
while student_id is 0: #loops until student_id is not 0
student_id = input("Please Enter Student ID: ")
try:
student_id = int(student_id)
if student_id > 0:
if len(str(student_id)) > 8 or len(str(student_id)) < 8: #checks student_id length
print("Student Id lenght should be 8 digits...")
student_id = 0
else:
print("Invalid Input,try again..! (ex:11111111)")
student_id = 0
if str(student_id) in open("students.txt", 'rt').read(): #checks student_id exists in students.txt file
print("Student Id already exist")
student_id = 0
except:
print("Invalid Input,try again..! (ex:12345678)")
student_id = 0
valid_name = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ '
student_name = None
while student_name is None:
student_name = input("Please Enter Student Name: ")
if all(let in valid_name for let in student_name): #checks name is valid or not
break
else:
print("Invalid input...! (ex: Tony Stark)")
student_name = None
valid_course = 'IMT0123456789'
course = None
while course is None:
course = input("Please Course Code: ")
course = course.upper()
if all(let in valid_course for let in course): #checks couse is valid or not
if len(course) > 5 or len(course) < 5:
print("Course lenght should be 5 letters")
course = None
else:
if course[0:3] == "MIT" and course[4:5].isdigit(): #checks first 3 letter and last 3 letters
break
else:
print(
"Couse code should start with MIT and end with numbers (ex: MIT01)")
course = None
else:
print("Invalid Couse Code...! (ex: MIT01)")
course = None
with open("students.txt", "a+") as students: #writes student data to students.txt file
students.write("{} {} {}\n".format(
student_id, student_name, course))
print("Thank You")
print("The details of the student you entered are as follows:\n------------------------------------")
students_data = get_students() #gets students data
new_student = (students_data[-1]).split() #gets last recordfrom students.txt file
print("Student Id: {}".format(new_student[0]))
print("Student name: {}".format(' '.join(new_student[1:-1])))
print("Course : {}".format(new_student[-1]))
print("------------------------------------")
another_student = None
while another_student is None:
another_student = input("Do you want to enter details for another student (Y/N)?") #gets user input for another student
another_student = another_student.lower()
if another_student == "y":
add_student() #calls add_student function
elif another_student == "n":
menu() #class menu function
else:
print("Invalid input,Please try again!")
another_student = None
#inserts marks
def insert_marks():
student_id = 0
while student_id is 0:
student_id = input("Please Enter Student ID: ")
try:
student_id = int(student_id)
if len(str(student_id)) > 8 or len(str(student_id)) < 8: #checks for valid length
print("Student Id lenght should be 8 digits...")
student_id = 0
except:
print("Invalid Input,try again..! (ex:12345678)")
student_id = 0
#checks valid student or not
if valid_student(student_id):
student_id = student_id
else:
print("\n*** Student Id does not exist,insert valid id *** \n")
insert_marks()
valid_subjectCode = 'CIT0123456789'
subject_code = None
while subject_code is None:
subject_code = input("Please Subject Code: ")
subject_code = subject_code.upper()
if all(let in valid_subjectCode for let in subject_code):
if len(subject_code) > 6 or len(subject_code) < 6: #checks for subject_code length
print("Subject Code lenght should be 6 letter")
subject_code = None
else:
#checks first 3 and last 3 letters
if subject_code[:3] == "ITC" and subject_code[-3:].isdigit() and int(subject_code[-3:]) > 0:
break
else:
print(
"Subject code should start with ITC and end with numbers (ex: ITC001)")
subject_code = None
else:
print("Invalid Subject Code...! (ex: ITC001)")
subject_code = None
assessment_number = 0
assessment_data = get_assessment() #gets assessments from assessments.txt file
while assessment_number is 0:
assessment_number = input("Please enter the assessment number: ")
try:
assessment_number = int(assessment_number)
#checks assessment_number valid or not
if assessment_number == 1 or assessment_number == 2 or assessment_number == 3:
for assessment in assessment_data:
assessment = (assessment).split()
#checks valid assessments already or not
if assessment[0] == str(student_id) and assessment[1] == subject_code and assessment[2] == str(assessment_number):
print(
"The student Assessment marks already exist.Try again!")
assessment_number =0
else:
print("Invalid Assessment Number ex(1,2,3)")
assessment_number = 0
except:
print("Invalid Assessment Number ex(1,2,3)")
assessment_number = 0
marks = None
while marks is None:
marks = input("Please enter assessment marks:") #gets marks from user
try:
marks = int(marks)
if marks > 100 or marks < 0: #cheks marks between 0 to 100
print("Marks should between 0 to 100,Try Again!")
marks = None
except:
print("Invaild marks,Try Again!")
marks = None
#inserts marks to assessments.txt file
with open("assessments.txt", "a+") as assessments:
assessments.write("{} {} {} {}\n".format(
student_id, subject_code, assessment_number, marks))
print("Thank You")
print("------------------------------------\nThe details of the student you entered are as follows:\n")
new_assessment = (get_assessment()[-1]).split() #gets last record from assements.txt file
#prints students marks
print("Student Id: {}".format(new_assessment[0]))
print("Subject Code: {}".format(new_assessment[1]))
print("Assessment Number: {}".format(new_assessment[2]))
print("Marks: {}".format(new_assessment[3]))
print("------------------------------------")
option = None
while option is None:
temp_data = input(
"Do you want to insert another student marks(Y/N)?") #gets user input
option = temp_data.lower()
if option == "y":
insert_marks() #calls insert marks function
elif option == "n":
menu() #calls menu function
else:
print("Invalid input,Please try again!")
option = None
#search student
def search_student():
student_id = 0
while student_id is 0: #loops until student_id is not 0
student_id = input("Please Enter Student ID: ")
try:
student_id = int(student_id) #converts student_id to int
if len(str(student_id)) > 8 or len(str(student_id)) < 8: #checks for student_id length
print("Student Id lenght should be 8 digits...")
student_id = 0
if valid_student(student_id) == False: #checks student_id exists or not
print("\n*** Student Id does not exist,insert valid id *** \n")
student_id = 0
except:
print("Invalid Input,try again..! (ex:12345678)")
student_id = 0
assessment_marks = get_assessment() #gets assements
students = get_students() #gets students
for student in students:
student = (student).split()
if student[0] == str(student_id): #orints marks if student_id matches
print("\n+++ Student Found +++\n")
print("Student Id: {}".format(student[0]))
print("Student name: {}".format(' '.join(student[1:-1])))
print("Course : {}".format(student[-1]))
print("---------------")
print("\nSubject Code Assessment Number Marks\n-----------------------------------------")
for marks in assessment_marks: #loops through marks
marks = (marks).split()
if marks[0] == str(student_id):
print(marks[1]+" "+marks[2] +
" "+marks[3]) #prints marks
print("\n")
new_search = None
while new_search is None: #loop until new_search not None
temp_data = input(
"Do you want to search another student marks(Y/N)?") #user input for search another student or not
new_search = temp_data.lower() #convert input data to lower case
if new_search == "y":
search_student() #calls search_students function
elif new_search == "n":
menu() #calls menu
else:
print("Invalid input,Please try again!")
new_search = None
#quits the programs
def quit():
exit()
#gets assessment from assessments.txt file
def get_assessment():
assessment_data = []
with open('assessments.txt') as assessments:
for assessment in assessments: #loops through assessments
assessment_data.append(assessment) #appends current marks
return assessment_data #returns available student marks
#gets available students in students.txt file
def get_students():
students_data = []
with open('students.txt') as students: #reads file as students
for student in students:
students_data.append(student) #appedns stduent current student data
return students_data #returns available students
def valid_student(student_id):
#checks student id exists in students.txt file
if str(student_id) in open("students.txt", 'rt').read():
return True #returns True
else:
return False # returns False
menu() |
83f140736044d75b4a7237213bee8d5fbffaa8ca | vishwanath79/PythonMisc | /Algorithms/dijkstras.py | 1,537 | 3.875 | 4 | # breadthfirst is the shortest segment
# dijkstras algorithm path with smallest total weight
graph = {}
graph["start"] = {}
graph["start"]["a"] = 6
graph["start"]["b"] = 2
#nodes and neighbors to the graph
graph["a"] = {}
graph["a"]["fin"] = 1
graph["b"] = {}
graph["b"]["a"] = 3
graph["b"]["fin"] = 5
graph["fin"] = {}
infinity = float("inf")
# costs table
costs = {}
costs["a"] = 6
costs["b"] = 2
costs["fin"] = infinity
#hashtable
parents = {}
parents["a"] = "start"
parents["b"] = "start"
parents["fin"] = None
processed = []
def find_lowest_cost_node(costs):
lowest_cost = float("inf")
lowest_cost_node = None
for node in costs:
cost = costs[node]
if cost < lowest_cost and node not in processed:
lowest_cost = cost
lowest_cost_node = node
return lowest_cost_node
node = find_lowest_cost_node(costs) # find lowest cost node that you have not processed yet
while node is not None: # until processing all the nodes
cost = costs[node]
neighbors = graph[node]
for n in neighbors.keys(): # go through all the neighbors of this node
new_cost = cost + neighbors[n] # if its cheaper to get to this neighbor
if costs[n] > new_cost: # by going through this node
costs[n] = new_cost # update the cost for this node
parents[n] = node # this node becomes the new parent for tis neighbor
processed.append(node) # mark the node as processed
node = find_lowest_cost_node(costs) # find the next node to process and stop
|
09ef091416d170c23881e1ee102787a8626ffecd | Mauzzz0/study-projects | /python/lab2_python/12.1.py | 152 | 3.515625 | 4 | white = list()
for _ in range(int(input())):
white.append(input())
for _ in range(int(input())):
g = input()
if g in white:
print(g) |
c6d44231d50ef32d7cd9d04e69ceda6cbff435dc | NishanthMHegde/DataStructuresInPython | /BST/bst.py | 3,629 | 3.9375 | 4 | class Node(object):
def __init__(self, data):
self.data = data
self.leftChild = None
self.rightChild = None
class BST(object):
def __init__(self):
self.root = None
def insert(self, data):
if self.root:
self.insertNode(data, self.root)
else:
new_node = Node(data)
self.root = new_node
def insertNode(self, data, node):
if data < node.data:
if node.leftChild:
self.insertNode(data, node.leftChild)
else:
node.leftChild = Node(data)
else:
if node.rightChild:
self.insertNode(data, node.rightChild)
else:
node.rightChild = Node(data)
def inorder(self):
if self.root:
self.inorder_traversal(self.root)
def inorder_traversal(self, node):
if node.leftChild:
self.inorder_traversal(node.leftChild)
print(node.data)
if node.rightChild:
self.inorder_traversal(node.rightChild)
def getMax(self):
if self.root:
return self.getMaxValue(self.root)
else:
return None
def getMaxValue(self, node):
if node.rightChild:
return self.getMaxValue(node.rightChild)
return node.data
def getMin(self):
if self.root:
return self.getMinValue(self.root)
else:
return None
def getMinValue(self, node):
if node.leftChild:
return self.getMinValue(node.leftChild)
return node.data
def remove(self, data):
if not self.root:
return None
if self.root:
self.root = self.remove_node(data, self.root)
def remove_node(self, data, node):
if not node:
return None
if data < node.data:
node.leftChild = self.remove_node(data, node.leftChild)
elif data > node.data:
node.rightChild = self.remove_node(data, node.rightChild)
else:
#we found the node we are looking for
#node is a leaf node
if (node.leftChild == None) and (node.rightChild == None):
del node
return None
#it has right child only
if node.leftChild == None:
temp = node.rightChild
del node
return temp
#it has left child only
elif node.rightChild == None:
temp = node.leftChild
del node
return temp
#has both left and right children: get the predecessory of the node from left sub tree
tempNode = self.get_predecessor(node.leftChild)
node.data = tempNode.data
node.leftChild = self.remove_node(tempNode.data, node.leftChild)
return node
def get_predecessor(self, node):
if node.leftChild:
return self.get_predecessor(node.leftChild)
return node
bst = BST()
bst.insert(12)
bst.insert(11)
bst.insert(10)
bst.insert(14)
bst.insert(24)
bst.insert(19)
bst.insert(17)
bst.insert(45)
bst.insert(67)
bst.insert(56)
bst.insert(34)
print("Inorder traverse result")
bst.inorder()
print("Minimum value in the tree %s" % (bst.getMin()))
print("Maximum value in the tree %s" % (bst.getMax()))
print("Deleting 24 and 56")
bst.remove(24)
bst.remove(56)
#printing again
print("Inorder traverse result")
bst.inorder()
print("Minimum value in the tree %s" % (bst.getMin()))
print("Maximum value in the tree %s" % (bst.getMax())) |
3a4a26d5f6e02f93257758f012ee593054cedfdb | ZhangNing777/LeetCode_Python | /215_findLthLargest.py | 832 | 3.5 | 4 | '''
在未排序的数组中找到第 k 个最大的元素。请注意,你需要找的是数组排序后的第 k 个最大的元素,而不是第 k 个不同的元素。
示例 1:
输入: [3,2,1,5,6,4] 和 k = 2
输出: 5
示例 2:
输入: [3,2,3,1,2,4,5,5,6] 和 k = 4
输出: 4
说明:
你可以假设 k 总是有效的,且 1 ≤ k ≤ 数组的长度。
'''
class Solution:
def findKthLargest(self, nums: List[int], k: int) -> int:
n = len(nums)
index = 0
for i in range(0,n):
for j in range(0,n-i-1):
if nums[j+1] < nums[j]:
temp = nums[j+1]
nums[j+1] = nums[j]
nums[j] = temp
index += 1
if index == k:
return nums[-k] |
5971590ef5c68729c4d3d7bd8c00a66a9a123272 | Nilsonsantos-s/Python-Studies | /Mundo 1 by Curso em Video/Exercicios Python 3/ex033.py | 524 | 3.90625 | 4 | # leia 3 numeros e verifique o maior e o menor
n1 = float(input('Digite um numero:'))
n2 = float(input('Digite um numero:'))
n3 = float(input('Digite um numero:'))
p1, p2, p3 = 0, 0, 0
if n1 > (n3 and n2):
p1 = n1
if n2 < n3:
p2 = n2
else:
p2 = n3
elif n2 > (n1 and n3):
p1 = n2
if n1 < n3:
p2 = n1
else:
p2 = n3
else:
p1 = n3
if n1 < n2:
p2 = n1
else:
p2 = n2
print(f'O Maior Valor digitado foi : {p1}\nO Menor valor digitado foi: {p2}')
|
5eb6f6e36a05ab4a56c5f7ffa39dc44433020a03 | szyymek/Python | /print_formatting.py | 348 | 3.828125 | 4 | #Formatting with the .format() method
print("This is first string {}, and second {}".format('inside1', 'inside2'))
print("This is first string {0}, and first again {0}".format('inside1', 'inside2'))
#Formatting floats with specific precision
wynik = 100/33
print("Result is: {w:1.2f}".format(w=wynik))
print("Result is: {w:1.5f}".format(w=wynik))
|
0bb6cd9eed86e44cbddbd0f151a733c8e8aac7d9 | Zhenjunwen/mohu_testcase | /TruncateDecimal.py | 250 | 3.828125 | 4 | def truncateDecimal(num,digits=0):
num = str(float(num))
nummian = num.split(".")[0]
numsub = num.split(".")[1]
numsub = numsub[:digits]
num = nummian+"."+numsub
# print(num)
return num
if __name__ == "__main__":
pass |
805154b5c74ed26b90cd781b73550b179e5d7445 | standeren/FileMeToTheMoon | /wordCounter.py | 908 | 3.53125 | 4 | import collections
def countWords(filename):
unique_words = {}
textfile = open('static/' + filename, 'r')
text_list = [line.replace(',', '').replace(
'?', '').split(" ") for line in textfile]
total_words = 0
for line in text_list:
for word in line:
word = word.lower()
total_words += 1
if word not in unique_words:
unique_words[word] = 1
else:
unique_words[word] += 1
unique_words = {key: val for key, val in unique_words.items() if val != 1}
sorted_dict = sorted(
unique_words.items(), key=lambda kv: kv[1], reverse=True)
sorted_unique_words = collections.OrderedDict(sorted_dict)
words = sorted_unique_words.keys()
values = sorted_unique_words.values()
total_unique_words = len(unique_words)
return total_words, total_unique_words, words, values
|
d2bae640179b8fc29a5abbfa81095b5bff6ed67d | arnoldza/Euchre_April_2019 | /players2.py | 26,048 | 3.828125 | 4 |
import random
import cards
class AmazingPlayer():
""" Model a player that often makes decisions based on a better strategy. """
trump_clubs = [cards.Card(9,1),cards.Card(10,1),cards.Card(12,1
),cards.Card(13,1),cards.Card(1,1),cards.Card(11,4),cards.Card(11,1)]
trump_diamonds = [cards.Card(9,2),cards.Card(10,2),cards.Card(12,2
),cards.Card(13,2),cards.Card(1,2),cards.Card(11,3),cards.Card(11,2)]
trump_hearts = [cards.Card(9,3),cards.Card(10,3),cards.Card(12,3
),cards.Card(13,3),cards.Card(1,3),cards.Card(11,2),cards.Card(11,3)]
trump_spades = [cards.Card(9,4),cards.Card(10,4),cards.Card(12,4
),cards.Card(13,4),cards.Card(1,4),cards.Card(11,1),cards.Card(11,4)]
list_trumps = [trump_clubs, trump_diamonds, trump_hearts, trump_spades]
#Ranking of trump suit based on trump
def __init__(self):
""" Initialize player. """
self.__hand = []
self.__trump = 0
self.__lead_suit = 0
self.__points = 0
self.__is_lead = False
self.__is_dealer = False
self.__is_teammate_dealer = False
self.__is_maker = False
def take_card(self, card):
""" Add card to player's hand. """
self.__hand.append(card)
def show_deck(self):
""" Returns player's current hand. """
return self.__hand
def assign_trump_suit(self, trump):
""" Assigns trump suit to player. """
self.__trump = trump
def remove_card(self): #AMAZING Player Contition A
""" Removes card from player's hand with AMAZING STRATEGY. """
trump_cards = [] #list of cards in player's hand that are trumps
non_trump_cards = [] #list of cards in player's hand that aren't trumps
trump_suit = self.__hand[5].suit() #trump suit based on kitty
lst_clubs = []
lst_diamonds = []
lst_hearts = []
lst_spades = []
lst_suits = [lst_clubs,lst_diamonds,lst_hearts,lst_spades]
lst_ranks = []
for card in self.__hand:
if card in self.list_trumps[trump_suit - 1]:
trump_cards.append(card) #adds to trumps
else:
non_trump_cards.append(card) #adds to non trumps
for card in non_trump_cards:
if card.rank() == 9:
self.__hand.remove(card) #if card in non trumps is 9, discard
return None
for card in non_trump_cards:
if card.rank() == 10:
self.__hand.remove(card) #if card in non trumps is 10, discard
return None
for card in non_trump_cards:
if card.suit() == 1:
lst_clubs.append(card)
elif card.suit() == 2:
lst_diamonds.append(card)
elif card.suit() == 3:
lst_hearts.append(card)
else:
lst_spades.append(card)
if len(non_trump_cards) == 1 or len(non_trump_cards) == 2:
for card in non_trump_cards:
if card.rank() == 1:
lst_ranks.append(14)
else:
lst_ranks.append(card.rank())
self.__hand.remove(non_trump_cards[lst_ranks.index(min(lst_ranks))]
)
return None
elif len(non_trump_cards) == 3:
for lst in lst_suits:
if len(lst) == 2:
for other in lst_suits:
if len(other) == 1:
self.__hand.remove(other[0])
return None
for card in non_trump_cards:
if card.rank() == 1:
lst_ranks.append(14)
else:
lst_ranks.append(card.rank())
self.__hand.remove(non_trump_cards[lst_ranks.index(min(lst_ranks))]
)
return None
elif len(non_trump_cards) == 4:
for lst in lst_suits:
if len(lst) == 3:
for other in lst_suits:
if len(other) == 1:
self.__hand.remove(other[0])
return None
for lst in lst_suits:
if len(lst) == 2:
for other in lst_suits:
if len(other) == 1:
self.__hand.remove(other[0])
return None
for card in non_trump_cards:
if card.rank() == 1:
lst_ranks.append(14)
else:
lst_ranks.append(card.rank())
self.__hand.remove(non_trump_cards[lst_ranks.index(min(lst_ranks))]
)
return None
elif len(non_trump_cards) == 5:
for lst in lst_suits:
if len(lst) == 4:
for other in lst_suits:
if len(other) == 1:
self.__hand.remove(other[0])
return None
for lst in lst_suits:
if len(lst) == 3:
for other in lst_suits:
if len(other) == 1:
self.__hand.remove(other[0])
return None
for lst in lst_suits:
if len(lst) == 2:
for other in lst_suits:
if len(other) == 1:
self.__hand.remove(other[0])
return None
for card in non_trump_cards:
if card.rank() == 1:
lst_ranks.append(14)
else:
lst_ranks.append(card.rank())
self.__hand.remove(non_trump_cards[lst_ranks.index(min(lst_ranks))]
)
return None
#########
for card in self.list_trumps[trump_suit - 1]:
if card in self.__hand:
self.__hand.remove(card)
return None
def add_point(self):
""" Adds point (Trick) to player. """
self.__points += 1
def return_points(self):
""" Returns points (Tricks) of player. """
return self.__points
def return_maker(self):
""" Returns whether or not player is a maker. """
return self.__is_maker
def play_card_lead(self, Trump): #AMAZING Player Condition B
""" Returns card with AMAZING strategy if player is the lead. """
if self.list_trumps[Trump - 1][5] in self.__hand:
return self.__hand.pop(self.__hand.index(self.list_trumps[Trump - 1
][5]))
elif self.list_trumps[Trump - 1][6] in self.__hand:
return self.__hand.pop(self.__hand.index(self.list_trumps[Trump - 1
][6]))
for card in self.__hand:
if card.rank() == 13 and card.suit() != Trump:
return self.__hand.pop(self.__hand.index(card))
for card in self.__hand:
if card.rank() == 1 and card.suit() != Trump:
return self.__hand.pop(self.__hand.index(card))
return self.__hand.pop(random.randrange(len(self.__hand)))
def play_card_not_lead(self, leadsuit): #AMAZING Player Condition B
""" Returns legal card with AMAZING strategy if player is not lead. """
legal_cards = []
lst_trumps = []
lst_ranks = []
if self.list_trumps[leadsuit - 1][6] in self.__hand:
return self.list_trumps[leadsuit - 1][6] #if jack in hand, play it
if self.__trump == leadsuit:
if self.list_trumps[leadsuit - 1][5] in self.__hand:
legal_cards.append(self.list_trumps[leadsuit - 1][5])
for card in self.__hand:
if card.suit() == leadsuit:
legal_cards.append(card)
for card in self.__hand:
if card in self.list_trumps[self.__trump - 1]:
lst_trumps.append(card)
if len(legal_cards) != 0: #If there are legal cards
if self.__trump != leadsuit or len(lst_trumps) == 0:
for card in legal_cards:
if card.rank() == 1:
lst_ranks.append(14)
else:
lst_ranks.append(card.rank())
return self.__hand.pop(self.__hand.index(legal_cards[
lst_ranks.index(max(lst_ranks))]))
else:
for card in lst_trumps:
lst_ranks.append(self.list_trumps[self.__trump - 1].index(
card))
return self.__hand.pop(self.__hand.index(lst_trumps[
lst_ranks.index(max(lst_ranks))]))
else: #If no legal cards
if len(lst_trumps) == 0:
for card in self.__hand:
if card.rank() == 1:
lst_ranks.append(14)
else:
lst_ranks.append(card.rank())
return self.__hand.pop(lst_ranks.index(min(lst_ranks)))
else:
for card in lst_trumps:
lst_ranks.append(self.list_trumps[self.__trump - 1].index(
card))
return self.__hand.pop(self.__hand.index(lst_trumps[
lst_ranks.index(min(lst_ranks))]))
def play_alone(self, Trump): #AMAZING Player Condition C
""" Returns if to play alone using AMAZING strategy. """
lst_trumps = []
for card in self.__hand:
if card in self.list_trumps[Trump - 1]:
lst_trumps.append(card)
if len(lst_trumps) == 4:
return True
elif self.list_trumps[Trump - 1][6
] in self.__hand and self.list_trumps[Trump - 1][5
] in self.__hand and self.list_trumps[Trump - 1][4] in self.__hand:
return True
elif self.list_trumps[Trump - 1][6
] in self.__hand and self.list_trumps[Trump - 1][5
] in self.__hand and self.list_trumps[Trump - 1][3] in self.__hand:
return True
elif self.list_trumps[Trump - 1][6
] in self.__hand and self.list_trumps[Trump - 1][5
] in self.__hand and self.list_trumps[Trump - 1][2] in self.__hand:
return True
return False
def is_lead(self, boolean):
""" Changes whether or not player is lead based on boolean value. """
self.__is_lead = boolean
def is_dealer(self, boolean):
""" Changes whether or not player is dealer based on boolean value. """
self.__is_dealer = boolean
def is_teammate_dealer(self, boolean):
""" Changes if player's teammate is dealer based on boolean value. """
self.__is_teammate_dealer = boolean
def is_maker(self, boolean):
""" Changes whether or not player is maker based on boolean value. """
self.__is_maker = boolean
def first_round(self, card): #Naming Trump First Round
""" Returns if to assign trump in first round of bidding. """
potential_trump_suit = card.suit()
points = 0
for card in self.__hand:
if card == self.list_trumps[potential_trump_suit - 1][6
] or card == self.list_trumps[potential_trump_suit - 1][5]:
points += 3
elif card == self.list_trumps[potential_trump_suit - 1][4
] or card == self.list_trumps[potential_trump_suit - 1][3
] or card == self.list_trumps[potential_trump_suit - 1][2]:
points += 2
elif card == self.list_trumps[potential_trump_suit - 1][1
] or card == self.list_trumps[potential_trump_suit - 1][0] or card.rank() == 1:
points += 1
if points >= 6:
return True
return False
def second_round(self, suit): #Naming Trump Second Round
""" Returns if to assign trump in second round of bidding. """
points_clubs = 0
points_diamonds = 0
points_hearts = 0
points_spades = 0
points_lst = [points_clubs,points_diamonds,points_hearts,points_spades]
for card in self.__hand:
for i in range(4):
if card == self.list_trumps[i][6] or card == self.list_trumps[i
][5]:
points_lst[i] += 3
elif card == self.list_trumps[i][4
] or card == self.list_trumps[i][3] or card == self.list_trumps[i][2]:
points_lst[i] += 2
elif card == self.list_trumps[i][1
] or card == self.list_trumps[i][0]:
points_lst[i] += 1
for obj in points_lst:
if suit - 1 == points_lst.index(obj):
continue
else:
if obj >= 5:
return points_lst.index(obj) + 1
return False
class StrategyPlayer():
""" Model a player that often makes decisions based on a strategy. """
trump_clubs = [cards.Card(9,1),cards.Card(10,1),cards.Card(12,1
),cards.Card(13,1),cards.Card(1,1),cards.Card(11,4),cards.Card(11,1)]
trump_diamonds = [cards.Card(9,2),cards.Card(10,2),cards.Card(12,2
),cards.Card(13,2),cards.Card(1,2),cards.Card(11,3),cards.Card(11,2)]
trump_hearts = [cards.Card(9,3),cards.Card(10,3),cards.Card(12,3
),cards.Card(13,3),cards.Card(1,3),cards.Card(11,2),cards.Card(11,3)]
trump_spades = [cards.Card(9,4),cards.Card(10,4),cards.Card(12,4
),cards.Card(13,4),cards.Card(1,4),cards.Card(11,1),cards.Card(11,4)]
list_trumps = [trump_clubs, trump_diamonds, trump_hearts, trump_spades]
#Ranking of trump suit based on trump
def __init__(self):
""" Initialize player. """
self.__hand = []
self.__trump = 0
self.__lead_suit = 0
self.__points = 0
self.__is_lead = False
self.__is_dealer = False
self.__is_teammate_dealer = False
self.__is_maker = False
def take_card(self, card):
""" Add card to player's hand. """
self.__hand.append(card)
def show_deck(self):
""" Returns player's current hand. """
return self.__hand
def assign_trump_suit(self, trump):
""" Assigns trump suit to player. """
self.__trump = trump
def remove_card(self): #StrategyPlayer Contition A
""" Removes card from player's hand based on strategy. """
number_clubs = []
number_diamonds = []
number_hearts = []
number_spades = []
list_nums = [
number_clubs, number_diamonds, number_hearts, number_spades]
rank_clubs = [cards.Card(9,1),cards.Card(10,1),cards.Card(11,1
),cards.Card(12,1),cards.Card(13,1),cards.Card(1,1)]
rank_diamonds = [cards.Card(9,2),cards.Card(10,2),cards.Card(11,2
),cards.Card(12,2),cards.Card(13,2),cards.Card(1,2)]
rank_hearts = [cards.Card(9,3),cards.Card(10,3),cards.Card(11,3
),cards.Card(12,3),cards.Card(13,3),cards.Card(1,3)]
rank_spades = [cards.Card(9,4),cards.Card(10,4),cards.Card(11,4
),cards.Card(12,4),cards.Card(13,4),cards.Card(1,4)]
list_ranks = [rank_clubs, rank_diamonds, rank_hearts, rank_spades]
#Ranks of cards based on not trump
ranking = [cards.Card(9,1),cards.Card(9,2),cards.Card(9,3
),cards.Card(9,4),cards.Card(10,1),cards.Card(10,2),cards.Card(10,3
),cards.Card(10,4),cards.Card(11,1),cards.Card(11,2),cards.Card(11,3
),cards.Card(11,4),cards.Card(12,1),cards.Card(12,2),cards.Card(12,3
),cards.Card(12,4),cards.Card(13,1),cards.Card(13,2),cards.Card(13,3
),cards.Card(13,4),cards.Card(1,1),cards.Card(1,2),cards.Card(1,3
),cards.Card(1,4)]
#Ranks of cards based on not trump
for k in range(4):
for i in list_ranks[k]:
if i in self.__hand:
list_nums[k].append(i)
for j in list_nums:
if len(j) >= 3:
self.__hand.pop(self.__hand.index(j[0]))
return None
if len(self.__hand) == 6:
for i in ranking:
if i in self.__hand:
self.__hand.pop(self.__hand.index(i))
return None
def add_point(self):
""" Adds point (Trick) to player. """
self.__points += 1
def return_points(self):
""" Returns points (Tricks) of player. """
return self.__points
def return_maker(self):
""" Returns whether or not player is a maker. """
return self.__is_maker
def play_card_lead(self, Trump): #StrategyPlayer Condition B
""" Returns card based on strategy if player is the lead. """
trump_list = []
for i in self.__hand:
if i in self.list_trumps[Trump - 1]:
trump_list.append(i)
if len(trump_list) > 0:
x = trump_list.pop(random.randrange(len(trump_list)))
return self.__hand.pop(self.__hand.index(x))
else:
return self.__hand.pop(random.randrange(len(self.__hand)))
def play_card_not_lead(self, leadsuit): #StrategyPlayer Condition B
""" Returns legal card based on strategy if player is not the lead. """
legal_cards = []
if self.list_trumps[leadsuit - 1][6] in self.__hand:
return self.list_trumps[leadsuit - 1][6]
else:
if leadsuit == self.__trump: #If the leading card's suit is a trump
for i in range(7):
if self.list_trumps[leadsuit - 1][i] in self.__hand:
legal_cards.append(self.list_trumps[leadsuit - 1][i])
#Counts how many of lead suit are available
if len(legal_cards) == 0:
return self.__hand.pop(random.randrange(len(self.__hand)))
#Play random card from hand
else:
x = legal_cards.pop(random.randrange(len(legal_cards)))
self.__hand.remove(x) #Play random card from legal options
return x
else: #If the leading card's suit is not the trump suit
for i in range(5):
if self.list_trumps[leadsuit - 1][i] in self.__hand:
legal_cards.append(self.list_trumps[leadsuit - 1][i])
if self.list_trumps[leadsuit - 1][6] in self.__hand:
legal_cards.append(self.list_trumps[leadsuit - 1][6])
#Counts how many of lead suit are available
if len(legal_cards) == 0:
return self.__hand.pop(random.randrange(len(self.__hand)))
#Play random card from hand
else:
x = legal_cards.pop(random.randrange(len(legal_cards)))
self.__hand.remove(x) #Play random card from legal options
return x
def play_alone(self, Trump): #StrategyPlayer Condition C
""" Returns if player will play alone based on strategy. """
trump_cards = []
non_cards = []
for i in self.__hand:
if i in self.list_trumps[Trump - 1]:
trump_cards.append(i)
else:
non_cards.append(i)
if len(trump_cards) == 5:
return True
elif len(trump_cards) == 4:
if non_cards[0].rank() == 1:
return True
elif len(trump_cards) == 3:
if self.list_trumps[Trump - 1][5
] in trump_cards or self.list_trumps[Trump - 1][6] in trump_cards:
if non_cards[0].suit() == non_cards[1].suit():
return True
if non_cards[0].rank() == 1:
if non_cards[1].rank() == 1 or non_cards[1].rank() == 13:
return True
if non_cards[1].rank() == 1:
if non_cards[0].rank() == 1 or non_cards[0].rank() == 13:
return True
if self.list_trumps[Trump - 1][2
] in trump_cards and self.list_trumps[Trump - 1][3
] in trump_cards and self.list_trumps[Trump - 1][4] in trump_cards:
if non_cards[0].rank() == 1:
if non_cards[1].rank() == 13:
return True
elif non_cards[1].rank() == 1:
if non_cards[0].rank() == 13:
return True
elif len(trump_cards) == 2:
if self.list_trumps[Trump - 1][5
] in trump_cards and self.list_trumps[Trump - 1][6] in trump_cards:
if non_cards[0].suit() == non_cards[1].suit() == non_cards[2
].suit():
if non_cards[0].rank() == 1:
if non_cards[1].rank() == 13 or non_cards[2
].rank == 13:
return True
elif non_cards[1].rank() == 1:
if non_cards[0].rank() == 13 or non_cards[2
].rank == 13:
return True
elif non_cards[2].rank() == 1:
if non_cards[0].rank() == 13 or non_cards[1
].rank == 13:
return True
return False
def is_lead(self, boolean):
""" Changes whether or not player is lead based on boolean value. """
self.__is_lead = boolean
def is_dealer(self, boolean):
""" Changes whether or not player is dealer based on boolean value. """
self.__is_dealer = boolean
def is_teammate_dealer(self, boolean):
""" Changes if player's teammate is dealer based on boolean value. """
self.__is_teammate_dealer = boolean
def is_maker(self, boolean):
""" Changes whether or not player is maker based on boolean value. """
self.__is_maker = boolean
def first_round(self, card): #Naming Trump First Round
""" Returns if to assign trump in first round of bidding. """
n = 0
not_n = [1,2,3,4,5]
list_index = 0
for i in range(5):
if self.list_trumps[card.suit()-1][i] in self.__hand:
n += 1
for p in range(5):
if self.__hand[p].suit() != card.suit():
not_n[list_index] = self.__hand[p]
list_index += 1 #Adds to list of non-lead cards
if self.__is_dealer == False and self.__is_teammate_dealer == False:
#NOT the dealer
if self.list_trumps[card.suit()-1][5
] in self.__hand and self.list_trumps[card.suit()-1][6] in self.__hand:
if n >= 2:
return True #Two Bowers and 2 other Trumps
elif self.list_trumps[card.suit()-1][5
] in self.__hand or self.list_trumps[card.suit()-1][6] in self.__hand:
if n >= 3:
return True #One Bower and 3 other Trumps
elif n >= 5:
return True #5 Trumps
try:
x = not_n[0].suit()
y = not_n[1].suit()
if n >= 3 and x == y:
return True #2 Suited and 3 Trumps
except:
pass
else: #IS the dealer
if self.list_trumps[card.suit()-1][5
] in self.__hand and self.list_trumps[card.suit()-1][6] in self.__hand:
return True #Both Bowers
elif self.list_trumps[card.suit()-1][5
] in self.__hand or self.list_trumps[card.suit()-1][6] in self.__hand:
if n >= 2:
return True #One Bower and 2 other Trumps
elif n >= 4:
return True #Four or Five Trumps
try:
x = not_n[0].suit()
y = not_n[1].suit()
if n >= 3 and x == y:
return True #2 Suited and 3 Trumps
except:
pass
return False
def second_round(self, suit): #Naming Trump Second Round
""" Returns if to assign trump in second round of bidding. """
for i in range(4):
if i + 1 == suit:
continue
else:
if self.list_trumps[i][5] in self.__hand and self.list_trumps[i
][6] in self.__hand:
return i + 1 #Both Bowers of that class
for i in range(4):
n = 0
if i + 1 == suit:
continue
else:
for p in range(5):
if self.list_trumps[i][p] in self.__hand:
n += 1
if self.list_trumps[i][5] in self.__hand or self.list_trumps[i
][6] in self.__hand:
if n >= 2:
return i + 1 #One Bower and two of same class
for i in range(4):
n = 0
if i + 1 == suit:
continue
else:
for p in range(5):
if self.list_trumps[i][p] in self.__hand:
n += 1
if n >= 4:
return i + 1 #Four or more of the same class
return False
|
000e1349b700292ead80959f2782fc15870c247a | OliverDevon/pythonGAme | /PROPERGAME.PY.py | 3,419 | 3.765625 | 4 | import random
from time import sleep
def playAgansitAI():
#list start
#player one list start
player1 = {}
player1['name'] = 'oliver'
player1Heath = 100
player1Power = 10
player1['health'] = player1Heath
player1['power'] = player1Power
print(player1)
#AI list start/player one list end
AI = {}
aiHealth = 100
aiPower = random.randint(1,10)
AI['name'] = 'AI'
AI['heatlh'] = aiHealth
AI['power'] = aiPower
print(AI)
#list end
#game loop start
while aiHealth != 0 or player1heath != 0 or aiHealth > 0 or player1Heath > 0:
aiPower = random.randint(1,10)
aiAttack = random.randint(1,3)
if aiAttack == 1:
player1Heath -= aiPower
if aiAttack == 2:
player1Heath -= aiPower + 2
if aiAttack == 3:
aiPower = random.randint(1,10)
print('your helath = ', player1Heath)
sleep(1)
PlayerAttack = input('what attack would you like to do (slap, kick)?: ')
if PlayerAttack == 'slap':
aiHealth = aiHealth - player1Power
player1Power += 1
if PlayerAttack == 'kick':
aiHealth = aiHealth - player1Power
player1Power += 1
print('ai helth = ', aiHealth)
if aiHealth == 0 or player1Heath == 0 or player1Heath < 0 or aiHealth < 0 or player1Heath < 9:
break
if player1Heath == 0 or player1Heath < 0:
print('you lose')
if aiHealth == 0 or aiHealth < 0:
print('YOU WIN!!!!!!!!!')
def play2Player():
player1 = {}
askPlayer1 = input('what is your name player1?: ')
player1['name'] = askPlayer1
player1Health = 100
player1Power = 10
player2 = {}
askPlayer2 = input('what is your name player2?: ')
player2['name'] = askPlayer1
player2Health = 100
player2Power = 10
while player1Health != 0 or player2Health != 0 or player1Health < 0 or player2Health < 0:
player1Attack = input('what attack would player1 like to do (slap, kick, punch)?: ')
if player1Attack == 'slap':
player2Health = player2Health - player1Power
if player1Attack == 'kick':
player2Health = player2Health - 20
if player1Attack == 'punch':
player2Health = player2Health - 5
print('player2\'s health =', player2Health)
sleep(1)
player2Attack = input('what attack would player2 like to do (slap, kick, punch)?: ')
if player2Attack == 'slap':
player1Health = player1Health - player2Power
if player2Attack == 'kick':
player1Health = player1Health - 20
if player2Attack == 'punch':
player1Health = player1Health - 5
print('player1\'s health =', player1Health)
if player2Health == 0 or player1Health == 0 or player1Health < 0 or player2Health < 0 or player1Health < 9:
break
if player1Health == 0 or player1Health < 0:
print(askPlayer1, 'lost')
print(askPlayer2, 'WINS')
if player2Health == 0 or player2Health < 0:
print(askPlayer2, 'lost')
print(askPlayer1, 'WINS')
playGame = input('would you like to play agaisnt the ai or play with a freind (1/2)?: ')
if playGame == '1':
playAgansitAI()
if playGame == '2':
play2Player()
|
1c75afe5de459fb8bd94c9c61b926779fb3a36a2 | rafaelperazzo/programacao-web | /moodledata/vpl_data/88/usersdata/165/55971/submittedfiles/listas.py | 451 | 3.625 | 4 | # -*- coding: utf-8 -*-
def degrau(a):
b=[]
for i in range(0,len(a)-1,1):
x=abs(a[i]-a[i+1])
b.append(x)
return(b)
def maior(a):
c=degrau(a)
maior=c[0]
for i in range(0,len(c),1):
if c[i]>maior:
maior=c[i]
return(maior)
n=int(input('digite n:'))
a=[]
for i in range(1,n+1,1):
valor=int(input('digite um valor:'))
a.append(valor)
print(maior(a))
|
7d6035edd8f702a5d5378cf46ba59b743a77e977 | Jiang765/Hadoop_MapReduce | /temperature_reducer.py | 675 | 3.53125 | 4 | #!/usr/bin/env python
import sys
current_date = None
current_temperature = 0
date = None
for line in sys.stdin:
line = line.strip()
date, temperature = line.split('\t', 1)
try:
temperature = int(temperature)
except ValueError:
continue
if current_date == date:
if temperature > current_temperature:
current_temperature = temperature
else:
if current_date:
print('%s\t%d' % (current_date, current_temperature))
current_temperature = temperature
current_date = date
if current_date == date:
print('%s\t%d' % (current_date, current_temperature))
|
fd0924a724fe2c2b6c5c3a9a2f0d61f4f9784cbd | rohan-khurana/MyProgs-1 | /RunningTime&ComplexityHR.py | 1,345 | 4.25 | 4 | """
Task
A prime is a natural number greater than that has no positive divisors other than and itself. Given a number, , determine and print whether it's or .
Note: If possible, try to come up with a primality algorithm, or see what sort of optimizations you come up with for an algorithm. Be sure to check out the Editorial after submitting your code!
Input Format
The first line contains an integer, , the number of test cases.
Each of the subsequent lines contains an integer, , to be tested for primality.
Constraints
Output Format
For each test case, print whether is or on a new line.
Sample Input
3
12
5
7
Sample Output
Not prime
Prime
Prime
Explanation
Test Case 0: .
is divisible by numbers other than and itself (i.e.: , , ), so we print on a new line.
Test Case 1: .
is only divisible and itself, so we print on a new line.
Test Case 2: .
is only divisible and itself, so we print on a new line.
"""
# SOLUTION
# Enter your code here. Read input from STDIN. Print output to STDOUT
import math
def isPrime(num) :
if num == 1:
return "Not prime"
for x in range(2,int(math.sqrt(num))+1):
if num%x == 0:
return "Not prime"
break
return "Prime"
n = int(input())
while(n>0):
num = int(input())
result = isPrime(num)
print(result)
n -= 1
|
e016f5fb97b09c403617ae98a5092b9c3f1351fe | thiagogmilani/ACO | /main.py | 1,614 | 3.640625 | 4 | #!/usr/bin/python 3
# coding: utf-8
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
# #
# MESTRADO EM CIENCIAS DA COMPUTACAO #
# DISCIPLINA DE COMPUTACAO INSPIRADA PELA NATUREZA #
# Thiago Giroto Milani - 01/2017 #
# #
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
#Biblioteca
import math
from aco import ACO, Graph
from plot import plot
def distance(city1: dict, city2: dict):
return math.sqrt((city1['x'] - city2['x']) ** 2 + (city1['y'] - city2['y']) ** 2)
def main():
cities = []
points = []
# Le o arquivo do dataset dentro da pasta data.
with open('./data/berlin52.tsp.txt') as f:
for line in f.readlines():
city = line.split(' ')
cities.append(dict(index=float(city[0]), x=float(city[1]), y=float(city[2])))
points.append((float(city[1]), float(city[2])))
cost_matrix = []
rank = len(cities)
for i in range(rank):
row = []
for j in range(rank):
row.append(distance(cities[i], cities[j]))
cost_matrix.append(row)
# Chama o ACO passando os parametros
aco = ACO(10, 100, 1.0, 10.0, 0.5, 10, 2)
graph = Graph(cost_matrix, rank)
path, cost = aco.solve(graph)
print('cost: {}, path: {}'.format(cost, path))
plot(points, path)
if __name__ == '__main__':
main()
|
53ea6cbfb9e69bebd2b7dfa7bd0db3285c244694 | sharathk91/Python-2018 | /LabAssignment1/Source/ValidatePassword.py | 1,493 | 4.375 | 4 | import re #import regular expressions
text = input("Enter the Password to validate: ") #take input password string from user
flag = 0 #assign flag to zero
while True: #loop until the value is false
if (len(text) < 6): #check if the length of password is less than 6 chars
flag = -1
print("Password size should be greater than 6")
break
elif (len(text) > 16): #check if the length of password file is greater than 6 characters
flag = -1
print("Password size should be lesser than or equal to 16")
break
elif not re.search("[a-z]", text): #check if the password contains lower case letter
flag = -1
print("password should have atleast one lower case letter")
break
elif not re.search("[A-Z]", text): #check if password contains atleast one upper case letter
flag = -1
print("password should have atleast one upper case letter")
break
elif not re.search("[0-9]", text): #check if password contains atleast one digit
flag = -1
print("password should have atleast one digit")
break
elif not re.search("[*!@$]", text): #check if password contains atleast one special char
flag = -1
print("password should have atleast one special character")
break
else: #if above one is not true, then it is a valid password
flag = 0
print("Valid Password")
break
if flag == -1:
print("Invalid Password") |
2036b9cf29ed66f54221f18148d344c552ad540b | Nimisha500/Python_Projects | /5.Password_Generator.py | 504 | 4 | 4 | import random
import string
character=string.ascii_letters+string.digits+string.punctuation
print(character)
character=string.ascii_letters+string.digits+string.punctuation
print(character)
pass_length=int(input("Enter length of password : "))
password=""
for i in range(pass_length+1):
password+=random.choice(character)
print("Password ",password)
# or USING JOIN
password1=''.join(random.choice(character)for i in range(pass_length+1))
print("Password ",password1)
|
1246f2f9c9d2be667fd2defce2c54a0355dcfe09 | ctmakro/playground | /qython/skipfun.py | 2,321 | 3.53125 | 4 | class Node:
pass
def dummy(key=None):
n = Node()
n.key = key
n.value = None
n.forwards = []
# n.height=0
return n
inf = float('inf')
minf = float('-inf')
import random
class SkipList:
def __init__(self):
self.head = dummy()
self.tail = dummy(inf)
self.head.forwards.append(self.tail)
self.levels = 1 # number of levels at start
self.updates = [None]*self.levels # reuse
def generate_height(self):
h = 0
while random.randrange(2)==0:
h += 1
if h == self.levels:
break
return h
def insert(self, key, value):
updates = self.updates
x = self.head
# for each level from top to bottom
for level in reversed(range(self.levels)):
# go right if key > rightnode.key
while key > x.forwards[level].key:
x = x.forwards[level]
# key <= rightnode.key
# leftnodes[level] = leftnode
updates[level] = x
# x = rightnode
x = x.forwards[0]
# if key == rightnode.key
if x.key == key:
# that's it
x.value = value
# key < rightnode.key
else:
new_height = self.generate_height()
# increase level of entire skiplist if necessary
if new_height > self.levels - 1:
for i in range(self.levels, new_height + 1):
updates.append(self.head)
self.head.forwards.append(self.tail)
self.levels = new_height+1
node = dummy(key)
node.value = value
# node.height = new_height
# make links in every level <= height
for i in range(new_height+1):
node.forwards.append(updates[i].forwards[i])
updates[i].forwards[i] = node
def traverse(self, limit=100):
n = self.head
while limit>0:
print('k:{} v:{} h:{}'.format(n.key, n.value, len(n.forwards)))
limit -= 1
if n.forwards:
n=n.forwards[0]
else:
break
skl = SkipList()
for i in range(50000):
skl.insert(random.randrange(100000000),random.randrange(100))
skl.traverse(20)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.