blob_id stringlengths 40 40 | repo_name stringlengths 5 119 | path stringlengths 2 424 | length_bytes int64 36 888k | score float64 3.5 5.22 | int_score int64 4 5 | text stringlengths 27 888k |
|---|---|---|---|---|---|---|
390f57d2c837f417e52753f171d749226217a8fa | kaviyasriprabhakaran/python_programming | /player/larger.py | 273 | 4.0625 | 4 | num1=int(input("enter the number"))
num2=int(input("enter the number"))
num3=int(input("enter the number"))
if ((num1>num2)and(num1>num3)):
print("num1 is large")
elif ((num2>num1) and(num2>num3)):
print("num2 is large")
else :
print("num3 is larger")
|
452a5383989ac83702cfbee8c83c1727d74321d6 | zhengwei223/thinkstats | /numpy_case/np_reshape.py | 191 | 4.0625 | 4 | import numpy as np
a = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
print(a)
# 所有的行的第三列,本身组成一个行,reshape成三行一列
ak = a[:, 2].reshape(3, 1)
print(ak)
|
19177899477590cccac4d04e74dc1bcad5b3a0ff | Valery780/lesson_10 | /task_2.py | 233 | 3.734375 | 4 | word = str(input("Enter a word: "))
x = len(word)
i = 0
x = x - 1
k = 0
while x - i >= i:
if word[x - i] == word[i]:
i += 1
else:
k = 1
break
if k == 1:
print("No")
else:
print("Yes") |
aa5107fed1b824eec6d34e7abdb138552ca99fad | minhthangtkqn/PythonWorkSpace | /FirstProject/412FizzBuzz.py | 417 | 3.65625 | 4 | def fizz_buzz(value):
for i in xrange(value):
if (i + 1) % 3 == 0 and (i + 1) % 5 == 0:
print 'FizzBuzz'
else:
if (i + 1) % 3 == 0:
print 'Fizz'
else:
if (i + 1) % 5 == 0:
print 'Buzz'
else:
print i + 1
return 0
if __name__ == '__main__':
n = 19
fizz_buzz(n)
|
da25bb167f6026648eb8759d62757374485c0608 | vip7265/ProgrammingStudy | /leetcode/july_challenge/pow/sjw.py | 458 | 3.625 | 4 | """
Problem URL: https://leetcode.com/explore/challenge/card/july-leetcoding-challenge/546/week-3-july-15th-july-21st/3392/
"""
class Solution:
def myPow(self, x: float, n: int) -> float:
# return self.pow1(x, n) # 60ms
return self.pow2(x, n) # 28ms
def pow1(self, x, n):
# python native operator
return x**n
def pow2(self, x, n):
# python native module
import math
return math.pow(x, n) |
88303e497cd889342e20ab7f27dba5bce5c4b974 | zwcdp/torecsys | /torecsys/layers/ctr/position_embedding.py | 1,727 | 3.578125 | 4 | import torch
import torch.nn as nn
class PositionEmbeddingLayer(nn.Module):
r"""Layer class of Position Embedding
Position Embedding was used in Personalized Re-ranking Model :title:`Changhua Pei et al, 2019`[1],
which is to add a trainable tensors per position to the session-based embedding features
tensor.
:Reference:
`Changhua Pei et al, 2019. Personalized Re-ranking for Recommendation <https://arxiv.org/abs/1904.06813>`_.
"""
def __init__(self, max_num_position: int):
r"""Initialize PositionEmbedding
Args:
max_num_position (int): Maximum number of position in a sequence.
Attributes:
bias (nn.Parameter): Bias variable of position in session.
"""
# refer to parent class
super(PositionEmbeddingLayer, self).__init__()
# initialize bias variables
self.bias = nn.Parameter(torch.Tensor(1, max_num_position, 1))
# initialize bias variables with normalization
nn.init.normal_(self.bias)
def forward(self, session_embed_inputs: torch.Tensor) -> torch.Tensor:
r"""Forward calculation of PositionEmbedding
Args:
session_embed_inputs (T), shape = (B, L, E), dtype = torch.float: Embedded feature tensors of session.
Returns:
T, shape = (B, L, E), dtype = torch.float: Output of PositionEmbedding
"""
# add positional bias to session embedding features
# inputs: session_embed_inputs, shape = (B, L, E)
# inputs: self.bias, shape = (1, L, 1)
# output: output, shape = (B, L, E)
output = session_embed_inputs + self.bias
return output
|
2ace9ec445387837e2f51ad43ca1e119c9483571 | GauravS99/answers | /q5.py | 687 | 3.84375 | 4 | # Time Complexity: O(n)
# Space Complexity: O(1)
def estimate_e(n):
"""
In 2004, using series compression, Brothers proposed
$$ e=\sum_{n=0}^{\infty} \frac{2n+2}{(2n+1)!} $$ (use latex to visualize)
to calculate the value of *e*. Implement a function that performs this estimation given an positive integer *n*, where *n* is a provided parameter, and returns the result as a double.
"""
e = 0.0
fact = 1 # accumulate fact so you don't need to calculate factorial each time
for i in range(n):
doublei = 2 * i
if i != 0:
fact = (doublei + 1) * (doublei) * fact
e += ((2 * i + 2) / fact)
return e
|
67ce9e34783bc34f679ec0bc0f8c48b3c07aad0f | intaschi/Python-course | /Estruturas de repetição/Ex 058.py | 937 | 3.84375 | 4 | import random
cont = 0
print('Acabei de pensar em um número entre 0 e 10. \nSerá que você consegue adivinhar qual foi?')
e = random.randint(1, 10)
acertou = False
while not acertou:
n = int(input('Qual é o seu palpite?'))
cont += 1
if n == e:
acertou = True
else:
if n > e:
print('Menos, tente novamente!')
elif e > n:
print('Mais, tente novamente!')
print('Acertou com {} tentativas. Parabéns!'.format(cont))
import random
cont = 0
print('Acabei de pensar em um número entre 0 e 10. \nSerá que você consegue adivinhar qual foi?')
e = random.randint(1, 10)
n = int(input('Qual é o seu palpite?'))
while n != e:
print('Esse não é o número. O certo seria {}. Tente mais uma vez!'.format(e))
e = random.randint(1, 10)
n = int(input('Qual é o seu palpite?'))
cont += 1
print('ACERTOU com {} tentativas'.format(cont))
|
c2364396548202b5d9d23a2af0f12002db4ecc46 | frankieliu/problems | /leetcode/python/199/sol.py | 1,535 | 3.921875 | 4 |
5-9 Lines Python, 48+ ms
https://leetcode.com/problems/binary-tree-right-side-view/discuss/56064
* Lang: python3
* Author: StefanPochmann
* Votes: 45
Solution 1: **Recursive, combine right and left:** 5 lines, 56 ms
Compute the right view of both right and left left subtree, then combine them. For very unbalanced trees, this can be O(n^2), though.
def rightSideView(self, root):
if not root:
return []
right = self.rightSideView(root.right)
left = self.rightSideView(root.left)
return [root.val] + right + left[len(right):]
---
Solution 2: **Recursive, first come first serve:** 9 lines, 48 ms
DFS-traverse the tree right-to-left, add values to the view whenever we first reach a new record depth. This is O(n).
def rightSideView(self, root):
def collect(node, depth):
if node:
if depth == len(view):
view.append(node.val)
collect(node.right, depth+1)
collect(node.left, depth+1)
view = []
collect(root, 0)
return view
---
Solution 3: **Iterative, level-by-level:** 7 lines, 48 ms
Traverse the tree level by level and add the last value of each level to the view. This is O(n).
def rightSideView(self, root):
view = []
if root:
level = [root]
while level:
view += level[-1].val,
level = [kid for node in level for kid in (node.left, node.right) if kid]
return view
|
376428613d394d17799fa0917df6d3f7c8991b9e | ignaciomartinez96/Primeros_pasos_en_Python | /Hangman.py | 9,538 | 4.34375 | 4 | # -*- coding: utf-8 -*-
"""
Project #2: Hangman
For this assignment, we want to play hangman in 2-player mode.
The game should start by prompting player 1 to pick a word.
Then the screen should clear itself so that player 2 can't see the word.
After the screen is clear, the "gallows" and the empty letter spaces should be drawn,
and player 2 should be allowed to guess letters until they either win, or lose.
As they choose correct letters, the letters should appear on the screen in place of the blank space.
As they choose wrong letters, the "man" himself should come end up being drawn, piece by piece.
Create a large list of dictionary words and embedding them in the application. When the game starts, instead of player 1 choosing the word to play with,
the computer should pick a random word from the dictionary. This will allow you to play against the computer instead of only 2-player mode.
When the game starts, the user should be prompted to choose between 1-player or 2-player mode.
"""
# We import some helpful libraries
import time
import re # this one will help to create some good lists
import getpass # this one will hide the word written by the first player
import random
# I use the same board from the previous project with some little changes for ths version
def Hangman(tablero):
print('_'*8)
for fila in range(6):
#practical_fila=int(fila/2)
for columna in range(8):
#practical_columna=int(columna/2)
if columna!=7:
print(tablero[columna][fila],end='')
else:
print(tablero[columna][fila])
print('^'*8)
tablero = [['|','|','|','|','|','|','|'],[' ',' ',' ',' ',' ',' ',' '],[' ',' ',' ',' ',' ',' ',' '],
[' ',' ',' ',' ',' ',' ',' '],['|',' ',' ',' ',' ',' ',' '],[' ',' ',' ',' ',' ',' ',' '],
[' ',' ',' ',' ',' ',' ',' '],[' ',' ',' ',' ',' ',' ',' ']]
# this function will help us to define whether we win or loose
def Chekeo(a):
if '_' not in a:
print('SALVADO!!')
time.sleep(2)
print('\n Gracias por salvar a nuestro amigo')
time.sleep(2)
new_party=input('¿Jugamos otra vez?: ')
if new_party=='si' or new_party=='sí':
globals()['player']=0
globals()['tablero']=[['|','|','|','|','|','|','|'],[' ',' ',' ',' ',' ',' ',' '],[' ',' ',' ',' ',' ',' ',' '],
[' ',' ',' ',' ',' ',' ',' '],['|',' ',' ',' ',' ',' ',' '],[' ',' ',' ',' ',' ',' ',' '],
[' ',' ',' ',' ',' ',' ',' '],[' ',' ',' ',' ',' ',' ',' ']]
return True
else:
print('\n Hasta pronto!')
globals()['player']=3
return False
else:
if contador==6:
print('AHORCADO!!')
time.sleep(2)
print('PERDISTE :(')
time.sleep(2)
new_party=input('¿Jugamos otra vez?: ')
if new_party=='si' or new_party=='sí':
globals()['player']=0
globals()['tablero']=[['|','|','|','|','|','|','|'],[' ',' ',' ',' ',' ',' ',' '],[' ',' ',' ',' ',' ',' ',' '],
[' ',' ',' ',' ',' ',' ',' '],['|',' ',' ',' ',' ',' ',' '],[' ',' ',' ',' ',' ',' ',' '],
[' ',' ',' ',' ',' ',' ',' '],[' ',' ',' ',' ',' ',' ',' ']]
return
else:
print('\n Hasta pronto!')
globals()['player']=3
return
# this is the only dict in the script. It contains some words to play along if someone choose the single mode
cartas={'fácil':['tonto','flor','mujer','cosa','partido','ciudad','historia','agua','ejemplo','ley','guerra','mano','sociedad',
'gente','problema','información','siglo','derecho','compras','barbijo','cajero','computadora','coche','cama','volar','película'
'reina','cuaderno'],
'medio':['interesate','disciplina','metastasis','alveolar','ideolecto','verbosemantica','parafasia','interestelar'
'conjuncion','subordinada','subjuntivo','astragalo','inmunodeprimido','cardiovascular','gangrena','acincope',
'minimalismo'],
'difícil':['mamporrero','omeprazol','barbian','sapenco','vituperio','nefelibata',
'electroencefalografista','agapachar','zangolotear','ataraxia','cagaprisas'
'euroescepticismo','limerencia','sempiterno','casquivana','sopenco']}
player=0
bienvenida='''
*******************************************
* BIENVENIDXS AL JUEGO DEL AHORCADO *
* *
*******************************************
'''
autor='''
************************
* HECHO CON AMOR POR *
* NACHO *
* **********************
'''
# with this big loop the game stars!!
while player==0:
print(bienvenida)
time.sleep(2)
print(autor)
time.sleep(3)
contador=-1
letras_usadas=[]
hombre= r"O||//\\"
cantidad_de_jugadores=input('¿Cuantxs jugadores van a jugar?\n [unx] [dos] ')
if cantidad_de_jugadores=='2' or cantidad_de_jugadores=='dos':
time.sleep(1)
palabra=getpass.getpass(prompt='Dime la palabra: ')
print(chr(27) + "[2J")
palabra_up=palabra.upper()
palabra_lista=re.findall(r"\w",palabra_up)
guess_lista=[]
for letra in palabra_lista:
guess_lista.append('_')
player=2
print('Salva a nuestro amigo!')
time.sleep(1)
while player==2:
guess=input('\n Dime una letra: ')
guess_up=guess.upper()
if guess_up in palabra_lista:
while guess_up in palabra_lista:
guess_index=palabra_lista.index(guess_up)
guess_lista[guess_index]=guess_up
palabra_lista[guess_index]='_'
Hangman(tablero)
for i in guess_lista:
print(i,end=' ')
print('\n')
print('Estas letras no están en la palabra:',letras_usadas)
Chekeo(guess_lista)
else:
if contador<7:
contador+=1
error=hombre[contador]
if contador==0:
tablero[4][1]=error
if contador==1:
tablero[4][2]=error
if contador==2:
tablero[4][3]=error
if contador==3:
tablero[3][2]=error
if contador==4:
tablero[3][4]=error
if contador==5:
tablero[5][4]=error
if contador==6:
tablero[5][2]=error
letras_usadas.append(guess_up)
Hangman(tablero)
for i in guess_lista:
print(i,end=' ')
print('\n')
print('Estas letras no están en la palabra:',letras_usadas)
Chekeo(guess_lista)
else:
player=1
time.sleep(1)
dificultad=input('¿Qué modo deseas jugar? \n [fácil] [medio] [difícil]: ')
if dificultad=='facil':
dificultad="fácil"
if dificultad=="dificil":
dificultad='difícil'
palabra_pre=cartas[dificultad]
palabra=random.choice(palabra_pre)
palabra_up=palabra.upper()
palabra_lista=re.findall(r"\w",palabra_up)
guess_lista=[]
for letra in palabra_lista:
guess_lista.append('_')
while player==1:
guess=input('Dime una letra: ')
guess_up=guess.upper()
if guess_up in palabra_lista:
while guess_up in palabra_lista:
guess_index=palabra_lista.index(guess_up)
guess_lista[guess_index]=guess_up
palabra_lista[guess_index]='_'
Hangman(tablero)
for i in guess_lista:
print(i,end=' ')
print('\n')
print('Estas letras no están en la palabra:',letras_usadas)
Chekeo(guess_lista)
else:
if contador<7:
contador+=1
error=hombre[contador]
if contador==0:
tablero[4][1]=error
if contador==1:
tablero[4][2]=error
if contador==2:
tablero[4][3]=error
if contador==3:
tablero[3][2]=error
if contador==4:
tablero[3][4]=error
if contador==5:
tablero[5][4]=error
if contador==6:
tablero[5][2]=error
letras_usadas.append(guess_up)
Hangman(tablero)
for i in guess_lista:
print(i,end=' ')
print('\n')
print('Estas letras no están en la palabra:',letras_usadas)
Chekeo(guess_lista)
|
d7d2d09b9a69f965020eac8575c846b0fb85fb2f | gatinueta/FranksRepo | /python/challenge/equality.py | 203 | 3.625 | 4 | import re
import fileinput
for line in fileinput.input():
ms = re.finditer('[A-Z]{3,}[a-z][A-Z]{3,}', line)
for m in ms:
if len(m.group()) == 7:
print(m.group())
|
15a176b3c98828cbcfc84f1c1cc34e4a3d6db5bb | w5802021/leet_niuke | /Linked_list/234.回文链表.py | 893 | 3.96875 | 4 | from Linked_list import linkedlist_operate
class LNode:
def __init__(self, x=None):
self.val = x
self.next = None
def reverseList1(head):
# 初始化res=None代表反转链表的尾结点
p, res = head, None
while p:
p,res,res.next=p.next,p,res
return res
def isPalindrome(head):
if not head or not head.next:
return True
slow = head
fast = head
while fast and fast.next:
slow = slow.next
fast = fast.next.next
# 链表长度为奇数时
if fast:
slow = slow.next
p2 = reverseList1(slow)
p1 = head
while p1 and p2:
if p1.val != p2.val:
return False
p1 = p1.next
p2 = p2.next
return True
if __name__ == '__main__':
l = [1,2,2,1]
llist = linkedlist_operate.LinkList()
cur = llist.initList(l)
print(isPalindrome(cur.next))
|
41d03dddd4eba73900011fec087fb00b2a22ee4f | UWPCE-PythonCert-ClassRepos/Self_Paced-Online | /students/csdotson/lesson02/print_grid.py | 914 | 4.25 | 4 | # Lesson 2 Assignment - Grid Printer
def print_grid(n):
"""Print 2 x 2 grid with cell size n"""
horizontal = ("+ " + ("- " * n)) * 2 + "+"
vertical = ("|" + (" " * (2 * n + 1))) * 2 + "|"
# Do the printing
print(horizontal)
for j in range(2):
for i in range(n):
print(vertical)
if i == (n - 1):
print(horizontal)
else:
continue
def print_grid2(grid_dim, cell_size):
"""Print grid_dim x grid_dim grid with given cell_size"""
horizontal = ("+ " + ("- " * cell_size)) * grid_dim + "+"
vertical = ("|" + (" " * (2 * cell_size + 1))) * grid_dim + "|"
# Do the printing
print(horizontal)
for j in range(grid_dim):
for i in range(cell_size):
print(vertical)
if i == (cell_size - 1):
print(horizontal)
else:
continue
|
1249c8eb97b2c8f8751bb944fa61eefcd91ae559 | luismvargasg/holbertonschool-higher_level_programming | /0x0C-python-almost_a_circle/models/base.py | 5,493 | 3.84375 | 4 | #!/usr/bin/python3
"""Defining the Base class"""
import json
import turtle
class Base:
"""This class will be the base of all other classes in this project."""
__nb_objects = 0
def __init__(self, id=None):
"""class constructor for Base.
Args:
id: is an integer, if id is not None, id with this argument
value is assigned, otherwise __nb_objects is assigned.
"""
if id is not None:
self.id = id
else:
Base.__nb_objects += 1
self.id = Base.__nb_objects
@staticmethod
def to_json_string(list_dictionaries):
"""static method that returns the JSON string representation
of list_dictionaries.
"""
if list_dictionaries is None or not list_dictionaries:
return "[]"
else:
return json.dumps(list_dictionaries)
@classmethod
def save_to_file(cls, list_objs):
"""class method that writes the JSON string representation
of list_objs to a file.
"""
filename = cls.__name__ + ".json"
new_list = []
if list_objs is not None:
for obj in list_objs:
new_list.append(cls.to_dictionary(obj))
with open(filename, mode="w", encoding="utf-8") as myFile:
myFile.write(cls.to_json_string(new_list))
@staticmethod
def from_json_string(json_string):
"""static method that returns the list of the JSON string
representation json_string.
"""
if json_string is None:
return []
return json.loads(json_string)
@classmethod
def create(cls, **dictionary):
"""class method that returns an instance with all attributes
already set.
"""
if cls.__name__ == "Rectangle":
dummy = cls(1, 1)
if cls.__name__ == "Square":
dummy = cls(1)
dummy.update(**dictionary)
return dummy
@classmethod
def load_from_file(cls):
"""class method that returns a list of instances"""
filename = cls.__name__ + ".json"
objs = []
try:
with open(filename, mode="r", encoding="utf-8") as myFile:
objs = cls.from_json_string(myFile.read())
for key, value in enumerate(objs):
objs[key] = cls.create(**objs[key])
except:
pass
return objs
@staticmethod
def draw(list_rectangles, list_squares):
"""static method that opens a window and draws all
the Rectangles and Squares."""
turtle.title("OOP in Python - drawing in GUI")
turtle.setup(width=1000, height=600)
turtle.bgcolor("#29293d")
turtle.pen(pencolor="#8080ff", pensize="4")
turtle.penup()
turtle.goto(x=0, y=300)
turtle.pendown()
turtle.right(90)
turtle.forward(600)
titles = turtle.Turtle()
titles.hideturtle()
titles.penup()
titles.goto(x=-330, y=260)
titles.color("#ffff66")
titles.write("Rectangles", font=("Arial", 28, 'bold'))
titles.goto(x=195, y=260)
titles.color("#ffff66")
titles.write("Squares", font=("Ar#212145ial", 28, 'bold'))
coord_x = -270
coord_y = 100
aux_turtle = turtle.Turtle()
for obj in list_rectangles:
w = obj.width
h = obj.height
x = obj.x
y = obj.y
titles.goto(coord_x - 180, coord_y + 50)
titles.color("white")
titles.write(obj, font=("Arial", 11, 'bold'))
turtle.penup()
aux_turtle.penup()
turtle.goto(coord_x, coord_y)
aux_turtle.goto(coord_x, coord_y)
turtle.pen(pencolor="#ff6666", pensize="2.5", fillcolor="#212145")
aux_turtle.pen(pencolor="gray", pensize="1.5")
aux_turtle.pendown()
aux_turtle.forward(140)
aux_turtle.left(180)
aux_turtle.forward(140)
aux_turtle.right(90)
aux_turtle.forward(140)
turtle.goto(coord_x + x, coord_y + y)
turtle.pendown()
for i in range(2):
turtle.left(90)
turtle.forward(w)
turtle.left(90)
turtle.forward(h)
coord_y -= 190
aux_turtle.right(90)
coord_x = 230
coord_y = 100
for obj in list_squares:
w = obj.width
h = obj.height
x = obj.x
y = obj.y
titles.goto(coord_x - 160, coord_y + 50)
titles.color("white")
titles.write(obj, font=("Arial", 11, 'bold'))
turtle.penup()
aux_turtle.penup()
turtle.goto(coord_x, coord_y)
aux_turtle.goto(coord_x, coord_y)
turtle.pen(pencolor="#ff6666", pensize="2.5", fillcolor="#212145")
aux_turtle.pen(pencolor="gray", pensize="1.5")
aux_turtle.pendown()
aux_turtle.forward(140)
aux_turtle.left(180)
aux_turtle.forward(140)
aux_turtle.right(90)
aux_turtle.forward(140)
turtle.goto(coord_x + x, coord_y + y)
turtle.pendown()
for i in range(4):
turtle.left(90)
turtle.forward(w)
coord_y -= 190
aux_turtle.right(90)
turtle.done()
|
766a58d6b9654ab62fdb1ff60249965919348641 | pvolnuhi/CPE-202 | /lab1/lab1.py | 2,181 | 4.34375 | 4 | #
#Polina Volnuhina
#014302388
#4/07/2019
#
#lab 1
#CPE 202-13
#Practising recursion through finding max number, reversing numbers, and binary search.
def max_list_iter(int_list): # must use iteration not recursion
"""finds the max of a list of numbers and returns the value (not the index)
If int_list is empty, returns None. If list is None, raises ValueError"""
if (int_list == []):
return None
elif (int_list is None):
raise ValueError
else:
curr_max_num = 0
for num in int_list:
if num > curr_max_num:
curr_max_num = num
return (curr_max_num)
def reverse_rec(int_list): # must use recursion
"""recursively reverses a list of numbers and returns the reversed list
If list is None, raises ValueError"""
if (int_list == []):
return None
elif (int_list is None):
raise ValueError
else:
if len(int_list) == 1:
return int_list
else:
return (reverse_rec(int_list[1:]) + [int_list[0]])
def bin_search(target, low, high, int_list): # must use recursion
"""searches for target in int_list[low..high] and returns index if found
If target is not found returns None. If list is None, raises ValueError """
if (int_list == []):
return None
elif (int_list is None): #base case
raise ValueError
elif ((high - low) <= 1): #checks when one element is left
if int_list[low] == target:
return low
else:
return None
elif high >= 1: #checks if greater than len(1)
mid = (low+high)//2 #int(1 + (high)/2)
if int_list[mid] == target: #if target is directly in the middle
return mid
elif int_list[mid] > target: #if target is less than middle check lower bound
return bin_search(target, low, mid-1, int_list)
else:
return bin_search(target, mid+1, high, int_list) #if target is larger than middle check upper bound
# else:
# return None #target is not present in list
# if high<= low and list_val[high]!=target:
# return None
# elif int_list[mid] == target: #switch around the order
# return mid
# elif target > int_list[mid]:
# return bin_search(target,mid+1,high,int_list)
# else:
# if target < int_list[mid]:
# return bin_search(target,low,mid-1,int_list)
|
34205ebc4c7ebad3362efe312530292e7dccb216 | mmore500/hstrat | /hstrat/_auxiliary_lib/_anytree_cardinality.py | 495 | 3.5625 | 4 | import anytree
from ._AnyTreeFastPreOrderIter import AnyTreeFastPreOrderIter
def anytree_cardinality(node: anytree.Node) -> int:
"""Count the number of nodes in an anytree tree rooted at the given node.
Parameters
----------
node : anytree.Node
The root node of the Anytree tree to compute the size of.
Returns
-------
int
The number of nodes in the tree rooted at the given node.
"""
return sum(1 for _ in AnyTreeFastPreOrderIter(node))
|
2dc3d5a4bc4f0a4b74fe460ec404164c97ad6688 | Legoben/DailyProgrammingProblems | /10.py | 1,012 | 3.5 | 4 | # Implement a job scheduler which takes in a function f and an integer n, and calls f after n milliseconds.
from collections import deque
import time
store = deque() # linked list
def hello():
print("hello1")
def hello2():
print("bye")
def add_job(f, n):
i = 0
for t in store:
if t['time'] == n:
t['jobs'].append(f)
break
elif t['time'] > n:
store.insert(i, {"time": n, "jobs": [f]})
break
i += 1
else:
store.insert(i, {"time": n, "jobs": [f]})
def run_scheduler():
start = int(round(time.time() * 1000))
while len(store) > 0:
if store[0]['time'] <= int(round(time.time() * 1000)) - start:
t = store.popleft()
[x() for x in t['jobs']]
if __name__ == "__main__":
add_job(hello, 400)
add_job(hello2, 1000)
add_job(hello, 1400)
add_job(hello2, 5000)
add_job(hello, 5000)
run_scheduler() # In theory, this could be run in diff thread
pass
|
18f3ec1f64bea9739b2c1967e6975d7262ec1bf2 | A0pple/PPNS | /PrimeChecking.py | 698 | 4.25 | 4 | import time
while(True):
print("How many numbers do you want until the machine stops?")
a = input("")
print("How many times do people need to wait to the script to occur again?")
b = input("")
# import time is to make the script slower
for n in range(1,int(a)):
time.sleep(int(b)) #() = the amount of seconds you want to occur the script
if n > 1:
for i in range(2,n):
if (n % i) == 0: #checks the number
print(n,"= Not Prime. explain:") #non-prime explain
print(i,"times",n//i,"is",n)
break
else:
print(n,"Prime.") #prime explain
else:
print(n,"Not Prime.") #non-prime explain
n
|
6c11959063a9717a24cafc3692264d433679092c | johnspiel99/compute | /project marks.py | 380 | 4.21875 | 4 | #= float(input("marks_number: "))
def grade(marks):
if marks < 50:
return "fail"
elif marks >= 60 and marks <= 70:
return "pass"
elif marks >= 61 and marks <= 80:
return "fair"
elif marks >= 81 and marks <= 90:
return "excellent"
else :
return ("distinction")
score= float(input("marks_number: "))
print(grade(score)) |
288791b5773aca165a0e5e028b4104ba9ce46b10 | NkStevo/daily-programmer | /challenge-001/easy/survey.py | 388 | 3.71875 | 4 | import sys
def main():
name = input("Input your name: ")
age = input("Input your age: ")
username = input("Input your reddit username: ")
result = "Your name is " + name + ", you are " + age + " years old, and your username is " + username
print(result)
f = open("easy-result.txt", "w")
f.write(result)
f.close()
if __name__ == "__main__":
main()
|
6efba8e32831926082a41998edc5c70a6b91273d | prachi39/acad | /module asn.py | 767 | 4.40625 | 4 | #1
print("time tuple is the usage of a tuple(list of ordered items/functions) for the ordering and notation of time. "
"the tuple used for time in python based systems can be largerly summarized by year,month,day,hour,minutes,"
"seconds,day of the week,day of the year,and finally a DST(daylight savings time")
#2
import datetime,time
print(time.asctime(time.localtime()))
#3
print(time.strftime("%B"))
#4
print(time.strftime("%A"))
#5
d=datetime.date.today()
print(time.strftime("%d/%m/%Y"))
print(d.day)
#6
print(time.localtime())
#7
import math
x=int(input("enter a number"))
print(math.factorial(x))
#8
import math
x=int(input("enter x"))
y=int(input("enter y"))
print(math.gcd(x,y))
#9
import os
print(os.getcwd())
import os
e=os.environ
print(e)
|
1b60c15e36dffde7562e5e9fbef9677b97e3e971 | spettigrew/cs2-codesignal-practice-tests | /web-logger.py | 3,787 | 3.890625 | 4 | """
Web Logger
"""
"""
Setup
We are building a new website, and we want to know how many visitors we are getting to the website. All we care about is how many visits we've gotten in the past 5 minutes, nothing more. Your job is to build this system, but implementing two functions:
# This function gets called every time the site is visited.
log_visit()
# This function is called whenever I visit an administrator page summarizing the website traffic. It should return the number of visits in the last 5 minutes.
get_visits() -> int
Part I: implement these functions
Please implement log_visit() and get_visits().You can use a function like time.time() in Python to get the current time, if that's useful.
The functions need to work even if the website becomes popular. For example, if we are using a list to store timestamps, that list will need to be pruned periodically so it doesn't become millions of items long (we only need to be able to report the number of visits in the last 5 minutes anyway).
Depending on how you are storing timestamps, you will likely need to implement a prune function that prunes old data from that data structure, and that prune function should be called in the right places in log_visit() and get_visits().
"""
import time
# initialize some data structure to hold each visit in past 5 min (300 seconds)
# TODO reset this to empty array for real case rather than hardcoded times
# for testing
visits = [1610305864.0861466, 1610305865.0863435, 1610305867.087183,
1610306258.0923035, 1610306248.0923035, 1610306238.0923035,
1610306268.0923035]
def log_visit():
# everytime this function is called log the time visited
visits.append(time.time())
# if the first entry in visits is more than 5 min ago we can prune it
if time.time() - visits[0] > 300:
prune_visits()
def get_visits():
# first check if the first entry in visits is more than 5 min ago
if time.time() - visits[0] > 300:
prune_visits()
# return the number of visits by returning the length of visits
return len(visits)
# run this function if the first entry in visits is more than 300 seconds ago
# (5 min)
def prune_visits():
# search visits to find the oldest timestamp within 5 min of time when
# this function is called
# binary search
# init the max idx and the min idx
max_time_idx = 0
min_time_idx = len(visits) - 1
# keep checking while the min time idx is not less than the max time idx
while not min_time_idx < max_time_idx:
# init the check point to be the middle of the list
check = (max_time_idx + min_time_idx) // 2
# init time passed into a variable for reuse in the checks below
# TODO change time_now to equal time.time() for real case rather than
# hardcoded time being used for testing
time_now = 1610306268.0923035
time_passed = time_now - visits[check]
# if the time passed has been more than 5 min
if time_passed > 300:
# check if the next item is not,
# if it is not then we can stop and remove all previous visits
# and return the pruned array
if time_now - visits[check + 1] < 300:
visits[:] = visits[check + 1:]
return visits
# if the next item is also over 5 min ago keep searching
# change the max search idx to 1 more than the check point
max_time_idx = check + 1
# if the time passed was less than 5 min
elif time_passed < 300:
# keep searching and change the min search index to 1 less
# than the check point
min_time_idx = check - 1
log_visit()
print(f'get_visits: {get_visits()}')
|
fcea316a1c4e15eb7533a16cca5dabeaaf2c7581 | 815382636/codebase | /python/foundation_level/my_caculate.py | 558 | 3.734375 | 4 | """
1.使用 and 、 or 时,尽量将每一小部分用()括起来,利于和他人配合工作,防止歧义等
"""
"""
数值之间做逻辑运算
(1)and运算符,只要有一个值为0,则结果为0,否则结果为最后一个非0数字
(2)or运算符,只有所有值为0结果才为0,否则结果为第一个非0数字
"""
print(0 and 1)
print(2 and 3)
print(0 or 0)
print(0 or 1)
print(2 or 3)
"""
算数运算优先级:
混合运算优先级顺序: () 高于 ** 高于 * / // % 高于 + -
""" |
c4160338545d6e0f858bb8669cbab48282fac20f | qchui/qchui | /剑指offer/数组中出现次数超过一半的数字.py | 745 | 3.734375 | 4 | """
数组中有一个数字出现的次数超过数组长度的一半,请找出这个数字。例如输入一个长度为9的数组{1,2,3,2,2,2,5,4,2}。
由于数字2在数组中出现了5次,超过数组长度的一半,因此输出2。如果不存在则输出0。
"""
# -*- coding:utf-8 -*-
class Solution:
def MoreThanHalfNum_Solution(self, numbers):
total_array=len(numbers)
half_array=int((total_array+1)/2)
dict={}
for i in numbers:
if i not in dict:
dict[i]=1
else:
dict[i] +=1
for key in dict:
if dict[key]>=half_array:
return key
return 0
print(Solution().MoreThanHalfNum_Solution([4,2,1,4,2,4])) |
e74e2c02e9b1fbf361c0445929b4dd5d06055a29 | thiagosantos1/AI_Pac_Man | /Classes/bonus.py | 3,167 | 3.53125 | 4 | # Copyright by Thiago Santos
# All rights reserved
import pygame
from tiles import Tile
from random import randint
from maze import Maze
# This Class is used to set and control where the bonus(fruit, coins, etc) is. It's the goal of the survivor to get it
class Bonus(pygame.Rect):
bonus_img = [ pygame.image.load('../Images/Bonus/apple_red.png'),
pygame.image.load('../Images/Bonus/candy_green.png'),
pygame.image.load('../Images/Bonus/candy_red.png'),
pygame.image.load('../Images/Bonus/candy_white.png'),
pygame.image.load('../Images/Bonus/cherry.png'),
pygame.image.load('../Images/Bonus/grape_blue.png'),
pygame.image.load('../Images/Bonus/grape_orange.png'),
pygame.image.load('../Images/Bonus/grape_red.png'),
pygame.image.load('../Images/Bonus/kiwi.png'),
pygame.image.load('../Images/Bonus/orange.png'),
pygame.image.load('../Images/Bonus/pear.png'),
pygame.image.load('../Images/Bonus/pineaple.png'),
pygame.image.load('../Images/Bonus/strawberry.png'),
pygame.image.load('../Images/Bonus/watermelon.png')]
height_bonus = 0
width_bonus = 0
list_bonus = [] # holds all bonus to be draw and catched
bonusTimeGeneration = 0.5 # each 1 second, a new bonus will apear in the screen(after collected the last one)
def __init__(self,tileNum): #each tile you wanna to generate
x_rec = Maze.tilesMaze[tileNum].x
y_rec = Maze.tilesMaze[tileNum].y
self.spawn_sounds = [pygame.mixer.Sound('../Sound_Effects/bonus/bonus1.wav'),
pygame.mixer.Sound('../Sound_Effects/bonus/bonus2.wav'),
pygame.mixer.Sound('../Sound_Effects/bonus/bonus3.wav'),
pygame.mixer.Sound('../Sound_Effects/bonus/bonus4.wav'),
pygame.mixer.Sound('../Sound_Effects/bonus/bonus5.wav'),
pygame.mixer.Sound('../Sound_Effects/bonus/bonus6.wav')]
width = Tile.widthTile
height = Tile.heightTile
self.img = Bonus.bonus_img[randint(0,13)]
self.img = pygame.transform.scale(self.img, (width,height ))
self.poits = 50
self.currenTileNum = tileNum
# not set yet
if Bonus.height_bonus == 0 or Bonus.width_bonus ==0:
Bonus.width_bonus = width
Bonus.height_bonus = height
pygame.Rect.__init__(self,x_rec,y_rec,width, height)
Bonus.list_bonus.append(self)
@staticmethod
def spawn( total_frames, FPS, survivor):
if total_frames % (FPS * Bonus.bonusTimeGeneration) == 0 and total_frames >0:
# create a new one just if there's no one in the screen(for now)
if not Bonus.list_bonus:
randTile = randint(1, len(Maze.tilesMaze))
while randTile == survivor.currenTileNum: # to not generate in the same
randTile = randint(1, len(Maze.tilesMaze))
bonus = Bonus(randTile)
sound = bonus.spawn_sounds[randint(0, len(bonus.spawn_sounds) -1)]
vol = sound.get_volume()
sound.set_volume(min(vol*1,12))
sound.play()
@staticmethod
def update(screen, survivor):
for bonus in Bonus.list_bonus:
screen.blit(bonus.img, (bonus.x, bonus.y))
if bonus.colliderect(survivor):
survivor.score += bonus.poits
survivor.ready_to_set_goal = False # set new path to a new goal
Bonus.list_bonus.remove(bonus)
|
b45a9b5a3e1de5d9bae040f77d8e67ed8a36b4f1 | sebastianrcnt/cshomework | /lab12_2018199061/lab12_p2.py | 328 | 4.03125 | 4 | def moderateDays(mydict):
'''Returns a list [...] of the days for which the average
temperature was between 70 and 79 degrees.
'''
days = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat']
# return list of days whose temperature is between 70 and 79
return [day for day in days if 70 <= mydict[day] <= 79] |
6855c05acc331cfe77c08470854f941042c09ef9 | Gracekanagaraj/positive | /pro40.py | 143 | 3.765625 | 4 | string3='dhoni'
in3=input()
list31=list(in3)
list31.sort()
lst3=list(string3)
lst3.sort()
if(lst3==list31):
print("yes")
else:
print("no")
|
83502c5a8db76a0c08f716657df875596b26aae4 | klistwan/project_euler | /41.py | 715 | 3.6875 | 4 | def is_prime(n):
if n in prime_sieve(n+1):
return True
return False
from math import sqrt
def prime_sieve(limit):
lop = []
cur_num = 2
l2g = range(2,limit)
while cur_num < sqrt(limit):
lop.append(cur_num)
l2g = filter(lambda n: n%cur_num != 0, l2g)
cur_num = l2g[1]
lop.extend(l2g)
return lop
def n_pandigital(n):
n_digit = 0
num = str(n)
while num != "":
n_digit += 1
if len(num.replace(str(n_digit),'') + str(n_digit)) == len(num):
num = num.replace(str(n_digit),'')
else: return 0
return n_digit
for i in prime_sieve(10000000):
if n_pandigital(i) > 0:
print i, "is", n_pandigital(i), "-pandigital"
|
42808ce13d648930741e6be7131b559d6cdb624c | Error57nk/Python-codes | /For_loop#1.py | 168 | 3.890625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sat Jan 12 22:47:03 2019
@author: nkkum
"""
#For loop
print('Printing 1 to 12 ')
for i in range(1,11):
print(i) |
78024de7257eb2c7ab1756a476f251256f45106f | haichao801/learn-python | /7-文件处理/f_read.py | 715 | 3.75 | 4 | """
语法格式:
f = open(file='d:/练习方式.txt', mode='r', encoding='utf-8')
data = f.read()
f.close
* f = open(file='d:/练习方式.txt', mode='r', encoding='utf-8') 表示文件路径
* mode='r'表示只读(可修改为其它)
* encoding='utf-8'表示将硬盘上的010101按照utf-8的规则去断句,再将断句后的每一段010101转换成Unicode的010101,Unicode对照表中有010101和字符的对应关系
* f.read()表示读取所有内容,内容是已经转换完毕的字符串
* f.close()表示关闭文件
"""
# 文件是以GB2312编码,此时以utf-8编码读取,会报错
f = open(file='联系方式.txt', mode='r', encoding='utf-8')
data = f.read()
print(data)
f.close()
|
49be4ac9e3c94dd52bce45b8fcfc929358a81702 | valen280/fundamentos_programacion | /fundamentos de programación/ordenamiento_burbuja_juntas.py | 1,296 | 3.828125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sun May 23 08:34:07 2021
@author: Luz Dary Prada
"""
# FUNCIÓN DESARROLLADA POR EL PROGRAMADOR
# ORDENAMIENTO BURBUJA DESCENDENTE
print("FUNCIÓN DESARROLLADA POR EL PROGRAMADOR")
def ordenamientoBurbuja(unaLista,tipo):
if(tipo=="ascendente"):
for numPasada in range(len(unaLista)-1,0,-1) :#ciclo que recorre la lista
for i in range(numPasada): #ciclo interno que recorre,contadores
if unaLista[i]>unaLista[i+1]: #comparacion con el actual|con siguiente
temp = unaLista[i]
unaLista[i] = unaLista[i+1]
unaLista[i+1] = temp
if(tipo=="descendente"):
for numPasada in range(len(unaLista)-1,0,-1) :#ciclo que recorre la lista
for i in range(numPasada): #ciclo interno que recorre,contadores
if unaLista[i]<unaLista[i+1]: #comparacion con el actual|con siguiente
temp = unaLista[i]
unaLista[i] = unaLista[i+1]
unaLista[i+1] = temp
unaLista = [2,14,93,17,23,31,15,55,4 ]#creando la lista
print("lista original :",unaLista)
tipo="descendente"
ordenamientoBurbuja(unaLista,tipo)
print("Lista Ordenada burbuja descendiente : ", unaLista) |
68c2c00a74cc36c4743cd45c88cfe31ecfbf8828 | stamp465/01204111-Computer-and-Programming | /quiz/20_08_20.py | 1,055 | 3.78125 | 4 |
'''
#1
def printt(ans) :
if len(ans) == 0 :
print("A minus B: empty set")
else :
print(f"A minus B: {ans}")
def minus(a,b) :
Set_Minus = []
lena = len(a)
lenb = len(b)
for i in range(0,lena) :
if a[i] in b :
pass
else :
Set_Minus.append(int(a[i]))
return Set_Minus
a = input("Input set A: ").split()
b = input("Input set B: ").split()
ans = minus(a,b)
printt(ans)
'''
'''
#2
def printt(ans) :
if len(ans) == 0 :
print("A union B: empty set")
else :
print(f"A union B: {ans}")
def sortt(a) :
lena = len(a)
for i in range(0,lena) :
for j in range(i+1,lena) :
if a[i] > a[j] :
a[i],a[j] = a[j],a[i]
return a
def union(a,b) :
Set_union = []
lena = len(a)
lenb = len(b)
for i in range(0,lena) :
if a[i] in b :
pass
else :
Set_union.append(int(a[i]))
for i in range(0,len(b)) :
Set_union.append(int(b[i]))
return sortt(Set_union)
a = input("Input set A: ").split()
b = input("Input set B: ").split()
ans = union(a,b)
printt(ans)
'''
|
8ce40de5bd3b213f6d54ce348862f623f5a75ac1 | chaofan-zheng/tedu-python-demo | /month01/all_code/day12/demo08.py | 691 | 3.8125 | 4 | """
需求:老张开车去东北
变化:飞机/轮船/骑车....
思想:
封装:将需求分解为多个类
人类 汽车 飞机 轮船 自行车 ...
"""
class Person:
def __init__(self, name=""):
self.name = name
def drive(self, pos, vehicle):
print("去", pos)
vehicle.transport()
class Vehicle:
def transport(self):
pass
class Car(Vehicle):
def transport(self):
super().transport()
print("行驶")
class Airplane(Vehicle):
# 重写快捷键:ctrl + o
def transport(self):
print("飞行")
lz = Person("老张")
car = Car()
air = Airplane()
lz.drive("东北", car)
|
8baa1bd56d234cd612bd91097f639d537b79bd13 | theymightbepotatoesafter/School-Work | /CIS 210/p34_sscount_sol_W21.py | 1,585 | 4.34375 | 4 | '''
Find all substrings of a string (CS Circles Unit 8) - two solutions
CIS 210 Winter 2021 Project 3-4
Author: CIS 210
Credits: N/A
'''
import doctest
def sscount0 (needle, haystack):
'''(str, str) -> int
Given a "needle" string to search for in a "haystack" string,
return the count of the number occurrences of the needle in
the haystack. Overlapping substrings are included.
Uses string slice operation (only).
>>> sscount0('sses', 'assesses')
2
>>> sscount0('an', 'trans-Panamanian banana')
6
>>> sscount0('needle', 'haystack')
0
>>> sscount0('!!!', '!!!!!')
3
>>> sscount0('o', 'pneumonoultramicroscopicsilicovolcanoconiosis')
9
'''
ctr = 0
n = len(needle)
for i in range(len(haystack)):
if haystack[i:i+n] == needle:
ctr += 1
return ctr
def sscount1 (needle, haystack):
'''(str, str) -> int
Given a "needle" string to search for in a "haystack" string,
return the count of the number occurrences of the needle in
the haystack. Overlapping substrings are included.
Using string startswith method simplifies code a bit.
>>> sscount1('sses', 'assesses')
2
>>> sscount1('an', 'trans-Panamanian banana')
6
>>> sscount1('needle', 'haystack')
0
>>> sscount1('!!!', '!!!!!')
3
>>> sscount1('o', 'pneumonoultramicroscopicsilicovolcanoconiosis')
9
'''
ctr = 0
for i in range(len(haystack)):
if haystack[i:].startswith(needle):
ctr += 1
return ctr
#print(doctest.testmod())
|
776c834b70ec15c285729b410c5c7e1f25bfa8ce | nefra298/python-base | /lesson03/hw_3_2.py | 1,114 | 3.703125 | 4 | def tonumeric(inp):
try:
val = int(inp)
return val
except ValueError:
try:
val = float(inp)
return val
except ValueError:
val = None
return val
def input_check_int(inp, msg=False, id=""):
x = tonumeric(inp)
if type(x) is int:
return True
else:
if msg:
print("Вы ввели не целое число",id)
return False
def nok (a,b):
i = 1
if a>b:
x=a
while x%b!=0:
i=i+1
x=a*i
else:
x=b
while x%a!=0:
i=i+1
x=b*i
return x
if __name__ == '__main__':
while True:
a = input("Введите целое число А:")
b = input("Введите второе целое число В или q для выхода:")
if (b == "q"):
exit()
elif input_check_int(a, True, "A") and input_check_int(b, True, "B"):
print("Наименьшее общее кратное:", nok(int(a), int(b)))
else:
continue
|
82fc8e4bfb12d79f3caeb48c3b2a45daf03f5827 | kamaleshkumar7/Twitter-Sentiment-Analysis | /sentiment.py | 867 | 3.515625 | 4 | import tweepy
from textblob import TextBlob
import csv
consumer_key= ''
consumer_secret= ''
access_token=''
access_token_secret=''
auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_token, access_token_secret)
api = tweepy.API(auth)
#Step 3 - Retrieve Tweets
keyword = input("Enter Keyword ")
public_tweets = api.search(keyword)
csvFile = open('result.csv', 'a')
csvWriter = csv.writer(csvFile)
for tweet in public_tweets:
print(tweet.text)
csvWriter.writerow([tweet.text.encode('utf-8')])
#Step 4 Perform Sentiment Analysis on Tweets
analysis = TextBlob(tweet.text)
print(analysis.sentiment)
if(analysis.sentiment.polarity < 0):
print("negative")
elif(analysis.sentiment.polarity>0):
print("positive")
else:
print("neutral")
print("")
|
32c3e7fabe277989caf901aac8fcc12623e17a78 | vanishh/python-tutorial | /oop/08debug.py | 593 | 3.671875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Tue Feb 6 23:36:25 2018
@author: Administrator
"""
# 调试程序方式:
# 1.在程序中使用print()打印中间变量值
# 2.使用assert 断言
# 启动解释器时,可以使用-0参数关闭assert
def foo(s):
n = int(s)
assert n != 0, 'n is zero!' # 如果assert为true则继续执行,为false则抛出AssertionError
return 10 / n
def main():
foo('0')
main()
# logging记录
import logging
logging.basicConfig(level=logging.INFO)
def main1():
n = 0
logging.info("n = %d" % n)
print(10 / n)
main1()
|
7d3a40f1c2f5161048769c04f471e84740c9270b | lizKimita/Password-Locker | /user.py | 1,599 | 4.21875 | 4 |
import pyperclip
class User:
'''
Class that generates new instances of the user.
'''
user_list = []
def __init__(self, first_name, last_name, user_name, password):
'''
init__helps us to define our users' properties.
Args:
first_name: New contact first name.
last_name: New contact last name.
user_name: New user's login username.
password: New user's login password
'''
self.first_name = first_name
self.last_name = last_name
self.user_name = user_name
self.password = password
def save_user(self):
'''
Method saves user objects into the user_list
'''
User.user_list.append(self)
@classmethod
def find_by_user_name(cls, user_name):
'''
Method that takes in a user_name and returns the user details that match that user_name
Args:
user_name: User_ name to search for
Returns:
User Details of the person that matches that user_name.
'''
for user in cls.user_list:
if user.user_name == user_name:
return user
@classmethod
def user_exists(cls, user_name):
'''
Method to check if a user exists from the user_list
Args:
user_name: User_name to search if it exists
Returns:
Boolean: True or False depending on if a user exists
'''
for user in cls.user_list:
if user.user_name == user_name:
return True
return False |
ca3c8f89a29855f35102e8972aadf648cd5a4b29 | AdamZhouSE/pythonHomework | /Code/CodeRecords/2444/49823/300149.py | 96 | 3.515625 | 4 | import random
n=int(random.random()*2)
if n==0:
print('true')
elif n==1:
print('false')
|
27091efc6c7aaa7ee488b4ce223df4cb683b4a54 | turo62/exercise | /exercise/codewar/lowest_product.py | 482 | 3.921875 | 4 | def lowest_product(input):
lst_nums = list(input)
prod_lst = []
product = 0
if len(input) < 4:
return "Number is too small"
else:
for i in range(len(lst_nums) - 3):
prod_lst.append((int(lst_nums[i]) * int(lst_nums[i + 1]) * int(lst_nums[i + 2]) * int(lst_nums[i + 3])))
product = min(prod_lst)
return product
def main():
product = lowest_product("1234111")
print(product)
if __name__ == "__main__":
main() |
5759bf30a5b36f20a9184bd34ad36bd8df2a8f55 | DavTho1983/List_comprehensions | /list_comprehensions2.py | 1,090 | 3.625 | 4 | movies = ["Star Wars", "Gandhi", "Casablanca", "Shawshank Redemption", "Toy Story", "Gone with the Wind", "Citizen Kane", "It's a Wonderful Life", "The Wizard of Oz", "Gattaca", "Rear Window", "Ghostbusters", "To Kill A Mockingbird", "Good Will Hunting", "2001: A Space Odyssey", "Raiders of the Lost Ark", "Groundhog Day", "Close Encounters of the Third Kind"]
#List of tuples of movie and release date
moviedates = [("Citizen Kane", 1941), ("Spirited Away", 2001), ("It's a Wonderful Life", 1946), ("Gattaca", 1997), ("No Country for Old Men", 2007), ("Rear Window", 1954), ("The Lord of the Rings: The Fellowship of the Ring", 2001), ("Groundhog Day", 1993), ("Close Encounters of the Third Kind", 1977), ("The Royal Tenenbaums", 2001),
("The Aviator", 2004), ("Raiders of the Lost Ark", 1981)]
# gmovies = []
# for title in movies:
# if title.startswith("G"):
# gmovies.append(title)
#
# print(gmovies)
gmovies = [str.upper(title) for title in movies if title.startswith("G")]
print(gmovies)
pre2k = [title for (title, year) in moviedates if year < 2000]
print(pre2k)
|
05d90d7252e157357b748e52eb8dfa313cce754c | vladimirpecerskij/vvp- | /linked list.py | 1,424 | 4.03125 | 4 | def add_at_end(self,data):
if not self.head:
self.head = node(data = data)
return
curr = self.head
while curr.next:
curr = curr.next
curr.next = node(data=data)
def delete_node(self,key):
curr = self.head
prev = None
while curr and curr.data !=key:
prev = curr
curr = curr.next
if prev is None:
self.head = curr.next
elif curr:
prev.next = curr.next
curr.next = None
def get_last_node(self):
temp = self.head
while(temp.next is not None):
temp = temp.next
return temp.data
def print_list( self ):
node = self.head
while node != None:
print(node.data, end = " => ")
node = node.next
s= linked_list()
s.add_at_front(5)
s.add_at_end(8)
s.add_at_front(9)
s.print_list()
|
f16138e4adf8dbd4535ad4cb15c58a915a232938 | wagnersistemalima/Mundo-3-Python-Curso-em-Video | /pacote de dawload/projeto progamas em Python/Aula 19 Dicionarios parte 1.py | 513 | 3.59375 | 4 | # Aula 19 Dicionarios. É assim que tratamos os dicionarios
pessoas = {'nome': 'Gustavo', 'sexo': 'M', 'idade': 22}
print(pessoas['nome'])
print(pessoas['idade'])
print(pessoas['sexo'])
print(f'{pessoas["nome"]} tem {pessoas["idade"]} anos') # Utilizar aspas duplas para a localização [" "]
print(pessoas.keys()) # nome / sexo / idade
print(pessoas.values()) # Gustavo / M / 22
print(pessoas.items()) #Composição de elementos: lista e treis tuplas
|
694ff1d23f5f436aa0605a34cc6183cd0ad26cb3 | rafacab1/1daw-python-prog | /Primer Trimestre/03 Bucles/3.py | 1,263 | 4.28125 | 4 | # 3. Algoritmo que pida caracteres e imprima ‘VOCAL’ si son vocales y ‘NO VOCAL’
# en caso contrario, el programa termina cuando se introduce un espacio.
#
#
# Autor: Rafael Alberto Caballero Osuna
#
#
# 22/10/19
#
# Algoritmo
# Mientras que una variable sea distinta de " "
# Pido un número
# Si es igual que "a" o "e" o "i" o "u" o "o" y la longitud es 1
# Muestro VOCAL
# Si no, compruebo que la longitud sea 1 y no sea " ", si es cierto, muestro "NO VOCAL"
# Si no, compruebo si es " ", si es cierto, muestro saliendo.
# Si no es nada de lo anterior, muestro error.
#
# Variables
# caracter = Caracter introducido
#
caracter = "aeiou"
print("Programa que pide un caracter y dice si es vocal. Para salir intruduce un espacio. ")
while caracter != " ":
caracter = input("\nIntroduce un carácter: ")
if caracter.lower() == "a" or caracter.lower() == "e" or caracter.lower() == "i" or caracter.lower() == "o" or caracter.lower() == "u" and len(caracter) == 1:
print("VOCAL")
elif len(caracter) == 1 and caracter != " ":
print("NO VOCAL")
elif caracter == " ":
print("\nSaliendo...")
else:
print("\nHa ocurrido un error. Recuerda que debes introducir un sólo caracter.") |
a75c2be32d91de1aa33d7589830fda39744e6075 | URI-ABD/clam | /py-clam/abd_clam/core/dataset.py | 7,153 | 3.75 | 4 | """This module defines the `Dataset` class."""
import abc
import pathlib
import random
import typing
import numpy
class Dataset(abc.ABC):
"""A `Dataset` is a collection of `instance`s.
This abstract class provides utilities for accessing instances from the data.
A `Dataset` should be combined with a `Metric` to produce a `Space`.
"""
@property
@abc.abstractmethod
def name(self) -> str:
"""Ideally, a user would supply a unique name for each `Dataset`."""
pass
@property
@abc.abstractmethod
def data(self) -> typing.Any: # noqa: ANN401
"""Returns the underlying data."""
pass
@property
@abc.abstractmethod
def indices(self) -> numpy.ndarray:
"""Returns the indices of the instances in the data."""
pass
@abc.abstractmethod
def __eq__(self, other: "Dataset") -> bool: # type: ignore[override]
"""Ideally, this would be a quick check based on `name`."""
pass
@property
def cardinality(self) -> int:
"""The number of instances in the data."""
return self.indices.shape[0]
@property
@abc.abstractmethod
def max_instance_size(self) -> int:
"""The maximum memory size (in bytes) of any instance in the data."""
pass
@property
@abc.abstractmethod
def approx_memory_size(self) -> int:
"""Returns the approximate memory size (in bytes) of the data."""
pass
@abc.abstractmethod
def __getitem__(
self,
item: typing.Union[int, typing.Iterable[int]],
) -> typing.Any: # noqa: ANN401
"""Returns the instance(s) at the given index/indices."""
pass
@abc.abstractmethod
def subset(
self,
indices: list[int],
subset_name: str,
) -> "Dataset":
"""Returns a subset of the data using only the indexed instances.
This subset should be of the same class as object from which it is created.
"""
pass
def max_batch_size(self, available_memory: int) -> int:
"""Conservatively estimate of the number of instances that will fill memory.
Args:
available_memory: in bytes.
Returns:
The number of instances that will fill `available_memory`.
"""
return available_memory // self.max_instance_size
def complement_indices(self, indices: list[int]) -> list[int]:
"""Returns the indices in the dataset that are not in the given `indices`."""
return list(set(range(self.cardinality)) - set(indices))
def subsample_indices(self, n: int) -> tuple[list[int], list[int]]:
"""Randomly subsample n indices from the dataset.
Args:
n: Number of indices to select.
Returns:
A 2-tuple of:
- list of selected indices.
- list of remaining indices.
"""
if not (0 < n < self.cardinality):
msg = (
f"`n` must be a positive integer smaller than the cardinality of "
f"the dataset ({self.cardinality}). Got {n} instead."
)
raise ValueError(msg)
# TODO: This should be from self.indices
indices = list(range(n))
random.shuffle(indices)
return indices[:n], indices[n:]
class TabularDataset(Dataset):
"""This wraps a 2d numpy array whose rows are instances and columns are features.
To check if two `TabularDataset`s are equal, this class only checks that
they have the same `name`.
To check if two instances are equal, this class simply checks for
element-wise equality among the instances.
"""
def __init__(self, data: numpy.ndarray, name: str) -> None:
"""Initializes a `TabularDataset`.
Args:
data: A 2d array whose rows are instances and columns are features.
name: This should be unique for each object the user instantiates.
"""
self.__data = data
self.__name = name
self.__indices = numpy.asarray(list(range(data.shape[0])), dtype=numpy.uint)
@property
def name(self) -> str:
"""Returns the name of the dataset."""
return self.__name
@property
def data(self) -> numpy.ndarray:
"""Returns the underlying data."""
return self.__data
@property
def indices(self) -> numpy.ndarray:
"""Returns the indices of the instances in the data."""
return self.__indices
def __eq__(self, other: "TabularDataset") -> bool: # type: ignore[override]
"""Checks if two `TabularDataset`s have the same name."""
return self.__name == other.__name
@property
def max_instance_size(self) -> int:
"""Returns the maximum memory size (in bytes) of any instance in the data."""
item_size = self.__data.itemsize
num_items = numpy.prod(self.__data.shape[1:])
return int(item_size * num_items)
@property
def approx_memory_size(self) -> int:
"""Returns the approximate memory size (in bytes) of the data."""
return self.cardinality * self.max_instance_size
def __getitem__(
self,
item: typing.Union[int, typing.Iterable[int]],
) -> numpy.ndarray:
"""Returns the instance(s) at the given index/indices."""
return self.__data[item]
def subset(self, indices: list[int], subset_name: str) -> "TabularDataset":
"""Returns a subset of the data using only the indexed instances."""
return TabularDataset(self.__data[indices, :], subset_name)
class TabularMMap(TabularDataset):
"""This is identical to a `TabularDataset` but the data is a `numpy.memmap`."""
def __init__(
self,
file_path: typing.Union[pathlib.Path, str],
name: str,
indices: typing.Optional[list[int]] = None,
) -> None:
"""Initializes a `TabularMMap`."""
self.file_path = file_path
data = numpy.load(str(file_path), mmap_mode="r")
indices = list(range(data.shape[0])) if indices is None else indices
self.__indices = numpy.asarray(indices, dtype=numpy.uint)
if self.__indices.max(initial=0) >= data.shape[0]:
msg = "Invalid indices provided."
raise IndexError(msg)
super().__init__(data, name)
@property
def indices(self) -> numpy.ndarray:
"""Returns the indices of the instances in the data."""
return self.__indices
def __getitem__(
self,
item: typing.Union[int, typing.Iterable[int]],
) -> numpy.ndarray:
"""Returns the instance(s) at the given index/indices."""
indices = self.__indices[item]
return numpy.asarray(self.data[indices, :])
def subset(self, indices: list[int], subset_name: str) -> "TabularMMap":
"""Returns a subset of the data using only the indexed instances."""
return TabularMMap( # type: ignore[return-value]
self.file_path,
subset_name,
indices,
)
__all__ = [
"Dataset",
"TabularDataset",
"TabularMMap",
]
|
ed786f016c70c4423d9255cabd667abbc17aa4c9 | aritraaaa/Competitive_Programming | /Number_Theory/Primality Test/Sieve_of_Eratosthenes.py | 980 | 4.25 | 4 | '''Python program to print all primes smaller than or equal to n using Sieve of Eratosthenes'''
def SieveOfEratosthenes(n):
# Create a boolean array "prime[0..n]" and initialize
# all entries it as true. A value in prime[i] will
# finally be false if i is Not a prime, else true.
prime = [True for i in range(n+1)]
p=2
while(p * p <= n):
# If prime[p] is not changed, then it is a prime
if (prime[p] == True):
# Update all multiples of p
for i in range(p * 2, n+1, p):
prime[i] = False
p+=1
# Print all prime numbers
for p in range(2, n):
if prime[p]:
print (p)
'''if(prime[n]):
print("PRIME")
else:
print("NOT PRIME")'''
# driver program
n = 100 #input
print ("Following are the prime numbers smaller",)
print ("than or equal to", n)
SieveOfEratosthenes(n)
# https://www.youtube.com/watch?v=ATyAnOCI1Ms |
1cb5343471295e8b4f7c76670a75ca45be4de466 | AnastasioNieves/Python- | /Cursos/Mastermind/Ejercicio Grados.py | 146 | 3.84375 | 4 | print("bienvenido a mi conversor")
a = float(input("Escriba los grados fahrenheit"))
b = (a-32)*5/9
print("Equivalen estos celcius: " + str(b)) |
c2cc637ee9bd12a707076201fafe98d35db5fa5f | daniel-reich/turbo-robot | /jyGco3e82sNfYKvCj_2.py | 431 | 4.03125 | 4 | """
Create a function that takes an integer `n` and reverses it.
### Examples
rev(5121) ➞ "1215"
rev(69) ➞ "96"
rev(-122157) ➞ "751221"
### Notes
* This challenge is about using two operators that are related to division.
* If the number is negative, treat it like it's positive.
"""
def rev(n):
numero=""
n=abs(n)
while n>0:
numero=numero+str(n%10)
n=n//10
return numero
|
8457c7b14938e17c2db036a814ff6855bafc8408 | jragbeer/Project-Euler | /ProjectEuler31.py | 1,322 | 3.515625 | 4 | import cProfile
import io
import itertools
import pstats
# Project Euler Problem 31
#
# In England the currency is made up of pound, £, and pence, p, and there are eight coins in general circulation:
#
# 1p, 2p, 5p, 10p, 20p, 50p, £1 (100p) and £2 (200p).
# It is possible to make £2 in the following way:
#
# 1×£1 + 1×50p + 2×20p + 1×5p + 1×2p + 3×1p
# How many different ways can £2 be made using any number of coins?
#
# Find the sum of all the numbers that can be written as the sum of fifth powers of their digits.
def profile(fnc):
"""A decorator that uses cProfile to profile a function"""
def inner(*args, **kwargs):
pr = cProfile.Profile()
pr.enable()
retval = fnc(*args, **kwargs)
pr.disable()
s = io.StringIO()
sortby = 'cumulative'
ps = pstats.Stats(pr, stream=s).sort_stats(sortby)
ps.print_stats()
print(s.getvalue())
return retval
return inner
@profile
def stuff():
a = [100,50, 20,10,5,2,1]
b = {i:range(0,int(200/i)) for i in a}
print(*list(b.values()))
r = itertools.product(*list(b.values()))
final = [x for x in r if sum([x[0] * 100, x[1] * 50, x[2] * 20, x[3] * 10, x[4] * 5, x[5] * 2, x[6]]) == 200]
print(len(final)+8)
stuff() |
ef824c4eedf00958c523011a38c401a7d896844e | eduardomezencio/tsim | /tsim/core/units.py | 1,270 | 4.0625 | 4 | """Units, values and functions for space and time."""
from __future__ import annotations
from datetime import time
from math import floor
Timestamp = float
Duration = float
SECOND = 1.0
MINUTE = 60.0 * SECOND
HOUR = 60.0 * MINUTE
DAY = 24.0 * HOUR
INT_SECOND = int(SECOND)
INT_MINUTE = int(MINUTE)
INT_HOUR = int(HOUR)
INT_DAY = int(DAY)
def normalized_hours(timestamp: Timestamp) -> float:
"""Get hours in range 0.0 <= hours < 24.0 from timestamp."""
return (timestamp % DAY) / HOUR
def time_string(timestamp: Timestamp) -> str:
"""Get string representation of timestamp."""
remaining = floor(timestamp)
seconds = remaining % 60
remaining = (remaining - seconds) // 60
minutes = remaining % 60
remaining = (remaining - minutes) // 60
hours = remaining % 24
return str(time(hours, minutes, seconds))
def whole_days(timestamp: Timestamp) -> int:
"""Get whole number of days since epoch from timestamp."""
return timestamp // DAY
def kph_to_mps(speed_kph: float) -> float:
"""Convert kilometers per hour to meters per second."""
return 1000.0 * speed_kph / HOUR
def mps_to_kph(speed_mps: float) -> float:
"""Convert meters per second to kilometers per hour."""
return HOUR * speed_mps / 1000.0
|
246f45427a272ba44ac78d256c95096d63c5475a | xiaochideid/yuke | /7-12/3.列表 元组 字符串 集合之间的转换.py | 1,733 | 4.34375 | 4 | # 重点内容:
# 将类型一转化成类型二:命名=类型2(类型1)特殊:转化为字符串string1=''.join(list or tuple or set)
# 列表:list []
# 元组:tuple ()
# 字符串:string {}
# 集合:set {}
# ..................列表转化成元组 字符串 集合...............
# 列表转换成元组
list1=['a','b','c','d']
tup=tuple(list1)
print(type(tup))
print(tup)
# 列表转化成字符串
string=''.join(list1)
print(type(string))
print(string)
# 列表转化成集合
set1=set(list1)
print(type(set1),set1,sep='')
print(set1)
# ,,,,,,,,,,,,,,,,,,元组转化成列表 字符串 集合...............
# 元组转化成列表
tuple1=('q','w','e')
list2=list(tuple1)
print(type(list2))
print(list2)
# 元组转化成字符串
string1=''.join(tuple1)
print(type(string1))
print(string1)
# 元组转化成集合
set2=set(tuple1)
print(type(set2))
print(set2)
# ...............字符串转化成列表 元组 集合...............
# 字符串转化成列表
string2='qdqf'
list3=list(string2)
print(type(list3))
print(list3)
# 字符串转化成元组
tuple2=tuple(string2)
print(type(tuple2))
print(tuple2)
# 字符串转化成集合
set3=set(string2)
print(type(set3))
print(set3)
# ................集合转化成列表 元组 字符串................
# 由于集合是无序的,所以转化出来的列表元组字符串的结果也是无序的
# 声明一个非空集合
my_set={'a','d','d','e'}
# 声明一个空集合
my_set1=set()
# 集合转化为字符串
string3=''.join(my_set)
print(type(string3))
print(string3)
# 集合转化为列表
list4=list(my_set)
print(type(list4))
print(list4)
# 集合转化为元组
tuple3=tuple(my_set)
print(type(tuple3))
print(tuple3)
|
1ef1f340963813e34ae4bc344aa45e5344d0d774 | jefersonmz78/cursoemvideo | /ex044.py | 990 | 3.6875 | 4 | print('{:=^40}'.format(' Lojas Guanabara '))
preço = float(input('Preço das compras: R$'))
print('''FORMAS DE PAGAMENTO
[1] à vista dinheiro/cheque
[2] à vista cartão
[3] 2x no cartão
[4] 3x Ou mais no cartão''')
opção = int(input('Qual é a opção ? '))
if opção == 1:
total = preço - (preço * 10 / 100)
elif opção == 2:
total = preço - (preço * 5/ 100)
elif opção == 3:
total = preço
parcela = total / 2
print('Sua compra será parcelada 2x de R${:.2f}'.format(parcela))
elif opção == 4:
total = preço +(preço *20 /100)
totparc = int(input('Quantas parcelas? '))
parcela = total /totparc
print('Sua compra será parcelada em{}x de R${:.2f} COM JUROS'.format(totparc, parcela))
else:
total = preço
print('OPÇÂO INVÁlIDA de pagamento. Tente novamente!')
print('Sua compra de R${:.2f} vai custar R${:.2f} no final.'.format(preço, total))
print('{:=^20}'.format(' Lojas Guanabara agradece a preferência'))
|
24a00e26367bd1f85243880f1148c9efdd6ec58d | avengerryan/daily_practice_codes | /five_sept/programiz/seven.py | 297 | 3.828125 | 4 |
# shuffle deck of cards
# importing modules
import itertools, random
# make a deck of cards
deck= list(itertools.product(range(1, 14), ['Spade', 'Heart', 'Diamond', 'Club']))
random.shuffle(deck)
# draw five cards
print("You got: ")
for i in range(5):
print(deck[i][0], 'of', deck[i][1]) |
c6ace24d2f27534f6d81146f2fd835ff4b30ed1f | tylerlorenzen/python-guessing-game | /pythonNumberGuessingGame.py | 1,480 | 4.125 | 4 | #Guessing the Random Number Game.
import random
import time
import numpy as np
import sys
#Delay printing
def delay_print(s):
#print one character at a time
for c in s:
sys.stdout.write(c)
sys.stdout.flush()
time.sleep(0.1)
print('Hello and welcome to my Random Number game! What is your name?')
name = input()
print(f'Welcome {name}, I am thining of a number between 1 and 20')
secretNumber = random.randint(1, 20)
for guessesTaken in range(1, 7):
print('Take a guess.')
guess = int(input())
if guess < secretNumber:
print('Your guess is too low!')
elif guess > secretNumber:
print('Your guess is too high!')
else:
break # This condition is for the correct guess
if guess == secretNumber:
print(f'Good job {name}! You guessed the number in {str(guessesTaken)} guesses!')
else:
print(f'Nope. The number was thinking of was {secretNumber}')
delay_print(f'\n\nThanks for playing my Random Number Game! Checkout some of my other stuff at tylerlorenzen.tech! \n\nThanks,\n\nTyler!')
# This is another way to do it.
#def guess(x):
# random_number = random.randint(1, x)
# guess = 0
# while guess != random_number:
# guess = int(input(f'Guess a number between 1 and {x}: '))
# if guess < random_number:
# print('Sorry, guess again. Too low.')
# elif guess > random_number:
# print('Sorry, guess again. Too high.')
#
# print(f'Yay, congrats! You won!)
|
cc1f3e9e625cac5ffcb3b8cb5c5bdbafaf132604 | hasnatosman/30days | /break.py | 122 | 3.796875 | 4 | for number in range (1, 11):
if number == 5:
continue
if number == 9:
break
print(number) |
b36086b538967c79a423af4b5f7c113f74283d77 | DebugConnoisseur/practice-programs | /sajibot.py | 293 | 3.84375 | 4 | a=2
b=7
c=10
d=2
e=14
if a>b:
print('Guddu CHildu')
else:
print('Worst Fellow')
if c<b:
print('Guddu Childu')
else:
print('Worst fellow')
if a==d:
print('Guddu Childu')
else:
print('Worst fellow')
if a*b==e:
print('Guddu Childu')
else:
print('Worst Fellow')
|
a116d816cb0d49c507fe9db34e939c6b97f811d3 | Candeladlf/UnsungInsistentDrupal | /main.py | 458 | 3.703125 | 4 | # Actividad 2 - Ejercicio 3
kilometros = float(input("¿Cuandos kilometros ha recorrido? "))
litros = float(input("¿Cuantos litros ha consumido? "))
print(f"El consumo ha sido : {round(100*litros/kilometros,2)} litros cada 100 kms")
# Actividad 2 - Ejercicio 4
IVA = float(input("¿Cuanto IVA vas a pagar (sin porcentaje) ? "))
precio = float(input("¿Cuanto IVA vas a pagar (sin porcentaje) ? "))
print("El precio final es " +str((IVA/100)*precio+precio)) |
6bf71e9ccd9981e27eb6ddba4f4fc63a5431efdb | tammyen/python | /prog5.py | 1,041 | 4.0625 | 4 | ##Lesley Tam Uyen Tran
##September 7, 2018
##ECS 10 Eiselt
##
##prog5.py
#Problem 1
def addTables(table1, table2):
"""function will ask for two arguments, both being a 2 dimmen-
sional tables. each value in the first table will be added with
a value in the second table with the same index and then
will be added into a third table. the third table will be
returned."""
table3 = []
index1 = 0 #this is the row
for row1 in table1:
index2 = 0 #this is the column
add_table = [] #makes separate lists like in the input
for num1 in row1:
num_add = num1 + table2[index1][index2]
#the two indexes will be used to find the value in
#table 2
index2 += 1
add_table = add_table + [num_add]
#value found will be added to a preliminary table
table3 = table3 + [add_table]
#preliminary table will be added to the final table
#to account for rows
index1 += 1
return(table3)
|
f57e23e713579878a1d5ebea8a2147ea20483a51 | anvesh2502/Leetcode | /Tree_RightView.py | 802 | 3.75 | 4 | # Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def __init__(self) :
self.level=dict()
def buildRightTree(self,root,index=0) :
if root==None : return
self.level.setdefault(index,[])
self.level[index].append(root.val)
self.buildRightTree(root.left,index+1)
self.buildRightTree(root.right,index+1)
def rightSideView(self, root):
"""
:type root: TreeNode
:rtype: List[int]
"""
l=[]
self.buildRightTree(root)
i=0
while i in self.level :
l.append(self.level[i][-1])
i+=1
return l
|
f1ed4032b5e383e2fcc43c8c405e1067901736cf | ClearlightY/Python_learn | /top/clearlight/algorithm/sort/bubble_sort.py | 483 | 3.859375 | 4 | def BubbleSort(lst):
n = len(lst)
if n <= 1:
return lst
for i in range(0, n):
for j in range(0, n - i - 1):
if lst[j] > lst[j + 1]:
(lst[j], lst[j + 1]) = (lst[j + 1], lst[j])
return lst
x = input("请输入待排序数列:\n")
y = x.split()
arr = []
for i in y:
arr.append(int(i))
arr = BubbleSort(arr)
print('数列排序如下:')
for i in arr:
print(i, end=' ')
x, y = 1, 2
print(x, y, end=' ')
print('adsf')
|
e50a11206db0f499a130059cf554f49fd246aa97 | waynekwon/Python_Data | /helloworld.py | 323 | 3.671875 | 4 | # print('100+200')
# print('hello world')
# #helloworld exercise
# print('The quick brown fox','jumps over', 'the lazy dog')
# print('100+200=', 100+200)
# name=input()
# print(name)
# x=input()
# y=input()
# print(int(x)+int(y))
# z=input('Enter Your Name: ')
# print('hello', z)
x=1024
y=768
print('1024 * 768 = ', x*y)
|
73545d4680598d57971d981c6d2f437c378a3d99 | jabibenito/pynet | /learnpy_ecourse/class4/Javi/ex3.py | 2,652 | 3.546875 | 4 | # III. Create a program that converts the following uptime strings to a time in seconds.
# uptime1 = 'twb-sf-881 uptime is 6 weeks, 4 days, 2 hours, 25 minutes'
# uptime2 = '3750RJ uptime is 1 hour, 29 minutes'
# uptime3 = 'CATS3560 uptime is 8 weeks, 4 days, 18 hours, 16 minutes'
# uptime4 = 'rtr1 uptime is 5 years, 18 weeks, 8 hours, 23 minutes'
# For each of these strings store the uptime in a dictionary using the device name as the key.
# During this conversion process, you will have to convert strings to integers. For these string to integer conversions use try/except to catch any string to integer conversion exceptions.
# For example:
# int('5') works fine
# int('5 years') generates a ValueError exception.
# Print the dictionary to standard output.
import pprint
MINUTE_SECONDS = 60
HOUR_SECONDS = 60 * MINUTE_SECONDS
DAY_SECONDS = 24 * HOUR_SECONDS
WEEK_SECONDS = 7 * DAY_SECONDS
YEAR_SECONDS = 365 * DAY_SECONDS
uptime1 = 'twb-sf-881 uptime is 6 weeks, 4 days, 2 hours, 25 minutes'
uptime2 = '3750RJ uptime is 1 hour, 29 minutes'
uptime3 = 'CATS3560 uptime is 8 weeks, 4 days, 18 hours, 16 minutes'
uptime4 = 'rtr1 uptime is 5 years, 18 weeks, 8 hours, 23 minutes'
device = {}
for line in (uptime1, uptime2, uptime3, uptime4):
uptime_time = line.split(",")
(device_name, uptime_filed) = uptime_time[0].split(" uptime is")
uptime_time[0] = uptime_filed
#print uptime_time
uptime_seconds = 0
for line in uptime_time:
if "years" in line:
(years, junk) = line.split(" years")
try:
uptime_seconds += int(years) * 31536000
except ValueError:
print "Error conversion"
elif "weeks" in line:
(weeks, junk) = line.split(" weeks")
try:
uptime_seconds += int(weeks) * 604800
except ValueError:
print "Error conversion"
elif "days" in line:
(days, junk) = line.split(" days")
try:
uptime_seconds += int(days) * 86400
except ValueError:
print "Error conversion"
elif "hours" in line:
(hours, junk) = line.split(" hours")
try:
uptime_seconds += int(hours) * 3600
except ValueError:
print "Error conversion"
elif "minutes" in line:
(minutes, junk) = line.split(" minutes")
try:
uptime_seconds += int(minutes) * 60
except ValueError:
print "Error conversion"
device[device_name] = uptime_seconds
pprint.pprint(device)
|
8dfdcfa1d39999d822c55d2efa9d53e7e7b4245c | AdamZhouSE/pythonHomework | /Code/CodeRecords/2500/60636/258870.py | 355 | 3.546875 | 4 | def pancakeSort(A):
"""
:type A: List[int]
:rtype: List[int]
"""
res = list()
for i in range(len(A), 1, -1):
A = A[:A.index(i)-1] + A[:A.index(i)]
res += [A.index(i)+ 1, i]
return res
A=eval(input())
a=pancakeSort(A)
while(1 in a):
a.pop(a.index(1))
print(a) |
bcd41fbc9ea976689cecb6136d45d5ada188635a | anketlale/ML_AZ | /Machine Learning A-Z/Part 1 - Data Preprocessing/Section 2 -------------------- Part 1 - Data Preprocessing --------------------/datap.py | 2,247 | 3.84375 | 4 | # importing library
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
dataset=pd.read_csv('C:/Users/Anket Lale/Desktop/Machine Learning A-Z/Part 1 - Data Preprocessing/Data.csv')
print("dataset:",dataset)
print()
print()
#------------------------------------------------------------
X = dataset.iloc[:, :-1].values
y = dataset.iloc[:, 3].values
print("X =",X)
print()
print("Y =",y)
print()
# 1)-------------------handling missing data-------------
from sklearn.impute import SimpleImputer
#sklearn library's imputer use to handle missing values
#1.create object of class
imputer = SimpleImputer(missing_values = np.nan, strategy = 'mean', verbose = 0)
#--axis =0 means column ( mean )
#2.fit in our data
imputer = imputer.fit(X[:,1:3])
#--index is 1 , 2 to take in fit
#3.
X[:, 1:3] = imputer.transform(X[:, 1:3])
#4.print x
print("handling missing x=",X)
print()
# 2)-------------------encode Categorical data --------------
#------------------dependant :
from sklearn.preprocessing import OneHotEncoder
from sklearn.compose import ColumnTransformer
#clas of sklearn for category
#this make value encoded
#1.make object
ct = ColumnTransformer([('encoder', OneHotEncoder(), [0])], remainder='passthrough')
X = np.array(ct.fit_transform(X), dtype=np.float)
#----------------------Encoding the Dependent Variable :
from sklearn.preprocessing import LabelEncoder
y = LabelEncoder().fit_transform(y)
print("encoding x=")
print(X)
print()
print("encoding y=")
print(y)
# 3)--------------------------------make test data and train data----------------------------------------------
from sklearn.model_selection import train_test_split
X_train , X_test , y_train , y_test = train_test_split(X,y,test_size = 0.2,random_state = 0)
print("X_train=",X_train)
print("X_test=",X_test)
print("y_train=",y_train)
print("y_test=",y_test)
# 4)--------------------------------feature scaling----------------------
from sklearn.preprocessing import StandardScaler
sc_X = StandardScaler()
X_train = sc_X.fit_transform(X_train)
X_test = sc_X.transform(X_test)
print("X_train scaling=",X_train)
print("X_test scaling=",X_test)
|
338cd1464110abf63183720311610577fd8615ba | Dimk000/Labs | /Semestr tasks/Dichotomy/Py/main.py | 473 | 4.125 | 4 | from math import fabs
def F(x):
return x*x*x-3*x+1
c = float()
a = float(input("Введите 1-ую границу интервала: "))
b = float(input("Введите 2-ую границу интервала: "))
eps = float(input("Введите точность: "))
while fabs(a - b) >= eps:
c = (a + b) / 2
if F(c) * F(a) < 0:
a = c
else:
b = c
print('Минимум функции на заданном интервале = ', c) |
b6b6ac69765b56fc710064ee39a214b2d61469d5 | gcifuentess/holbertonschool-higher_level_programming | /0x0B-python-input_output/12-student.py | 821 | 3.671875 | 4 | #!/usr/bin/python3
"""Student to JSON module"""
class Student():
"""Student class"""
def __init__(self, first_name, last_name, age):
"""Student constructor"""
self.first_name = first_name
self.last_name = last_name
self.age = age
def to_json(self, attrs=None):
'''Returns dictionary description of json object filtered'''
flag = False
if (type(attrs) is list):
flag = True
for attr in attrs:
if type(attr) is not str:
flag = False
if flag is True:
my_dict = {}
for key, value in self.__dict__.items():
if key in attrs:
my_dict[key] = value
else:
my_dict = self.__dict__.copy()
return my_dict
|
570c23d660eba7c93504ed0472928aef9d62a053 | Melv1nS/CS313E_Projects | /Assignments/Assignment 5/Office.py | 3,350 | 3.5 | 4 | # Input: a rectangle which is a tuple of 4 integers (x1, y1, x2, y2)
# Output: an integer giving the area of the rectangle
def area (rect):
width = rect[2] - rect[0]
length = rect[3] - rect[1]
area = width * length
return area
# Input: no input
# Output: a string denoting all test cases have passed
"""def test_cases ():
assert area ((0, 0, 1, 1)) == 1
# write your own test cases
return "all test cases passed"
"""
def create_grid(dimensions):
grid =[]
for i in range(dimensions[1]):
grid.append([])
for row in grid:
for i in range(dimensions[0]):
row.append(0)
return grid
def read_input():
#note dimensions need to be within 1 and 100
#names 1-20 characters
dimensions = tuple([int(x) for x in input().split()])
num_employees = int(input())
emp_list = []
for i in range(num_employees):
employee = input().split()
emp_list.append(employee.copy())
employee.clear()
return dimensions, emp_list
def get_length(rect):
length = rect[3] - rect[1]
return length
def get_width(rect):
width = rect[2] - rect[0]
return width
def increment_grid(grid, rect):
row_start = len(grid) - rect[3]
row_end = len(grid) - rect[1]
col_start = rect[0]
col_end = rect[2]
for row in range(row_start, row_end):
for col in range(col_start, col_end):
grid[row][col] += 1
def unallocated_space(grid):
unallocated = 0
for row in grid:
unallocated += row.count(0)
return unallocated
def total_space(grid):
total = len(grid[0]) * len(grid)
return total
def contestedSpace(grid):
contested = 0
for row in grid:
for col in row:
if col > 1:
contested += 1
return contested
def find_guaranteed(grid, rect):
row_start = len(grid) - rect[3]
row_end = len(grid) - rect[1]
col_start = rect[0]
col_end = rect[2]
guaranteed = 0
for row in range(row_start, row_end):
for col in range(col_start, col_end):
if grid[row][col] == 1:
guaranteed += 1
return guaranteed
def main():
# read the data
dimensions, emp_list = read_input()
name_list = []
rect_list = []
for emp in emp_list:
name_list.append(emp[0])
rect_list.append((int(emp[1]), int(emp[2]), int(emp[3]), int(emp[4])))
grid = create_grid(dimensions)
for rect in rect_list:
increment_grid(grid, rect)
"""for row in grid:
print(row)"""
print('Total', total_space(grid))
print('Unallocated', unallocated_space(grid))
print('Contested', contestedSpace(grid))
i = 0
for rect in rect_list:
print(name_list[i], str(find_guaranteed(grid, rect)))
i += 1
# run your test cases
'''
print (test_cases())
'''
# print the following results after computation
# compute the total office space
# compute the total unallocated space
# compute the total contested space
# compute the uncontested space that each employee gets
if __name__ == "__main__":
main()
|
71a67870d97a9605486871417b7f6a2342e416b6 | nss-cohort-40/c40-keahua-arboretum-lava-dodgers | /actions/cultivate_plant.py | 9,812 | 3.828125 | 4 | import os
import copy
from plants import *
def choose_plant():
os.system('cls' if os.name == 'nt' else 'clear')
print("1. Mountain Apple Tree")
print("2. Silversword")
print("3. Rainbow Eucalyptus Tree")
print("4. Blue Jade Vine")
print("")
try:
plant = int(input("Choose plant to cultivate >> "))
except ValueError:
print("The input must be a number from the list.")
input("Press enter to continue >>")
return
if plant == 1:
return("Mountain Apple Tree")
elif plant == 2:
return("Silversword")
elif plant == 3:
return("Rainbow Eucalyptus Tree")
elif plant == 4:
return("Blue Jade Vine")
else:
os.system('cls' if os.name == 'nt' else 'clear')
print("That number is not available. Please choose a plant from the list.")
input("Press enter to return to the plant menu >>")
return
def cultivate_plant(arboretum):
plant = choose_plant()
os.system('cls' if os.name == 'nt' else 'clear')
#Cultivate Mountain Apple Tree
if plant == "Mountain Apple Tree":
new_plant = Mountain_Apple()
biomes_available = []
for biome in arboretum.mountains:
if len(biome.plants) < 4:
biomes_available.append(biome)
if biomes_available == []:
print("There are no biomes available for this plant. Please annex the proper biome before attempting to cultivate!")
input("Press enter to continue >> ")
return
else:
for x in range(len(biomes_available)):
animals_in_biome_string = get_biome_specifics_animals(biomes_available, x)
plants_in_biome_string = get_biome_specifics_plants(biomes_available, x)
print(f"{x+1}. {biomes_available[x]} | {str(biomes_available[x].id)[:8]}{plants_in_biome_string}{animals_in_biome_string} | ({len(biomes_available[x].plants)}/4)")
try:
biome_choice = int(input("Choose a biome > ")) - 1
except ValueError:
print("The input must be a number.")
input("Press enter to continue >>")
return
try:
if biome_choice >= 0:
biomes_available[biome_choice].add_plant(new_plant)
os.system('cls' if os.name == 'nt' else 'clear')
print(f"The {plant} has successfully been cultivated!")
input("Press enter to continue >>")
else:
raise IndexError
except IndexError:
print("The number must be in the list.")
input("Press enter to continue >>")
return
#Cultivate Silversword
if plant == "Silversword":
new_plant = Silversword()
biomes_available = []
for biome in arboretum.grasslands:
if len(biome.plants) < 15:
biomes_available.append(biome)
if biomes_available == []:
print("There are no biomes available for this plant. Please annex the proper biome before attempting to cultivate!")
input("Press enter to continue >> ")
return
else:
for x in range(len(biomes_available)):
animals_in_biome_string = get_biome_specifics_animals(biomes_available, x)
plants_in_biome_string = get_biome_specifics_plants(biomes_available, x)
print(f"{x+1}. {biomes_available[x]} | {str(biomes_available[x].id)[:8]}{plants_in_biome_string}{animals_in_biome_string} | ({len(biomes_available[x].plants)}/15)")
try:
biome_choice = int(input("Choose a biome > "))- 1
except ValueError:
print("The input must be a number.")
input("Press enter to continue >>")
return
try:
if biome_choice >= 0:
biomes_available[biome_choice].add_plant(new_plant)
os.system('cls' if os.name == 'nt' else 'clear')
print(f"The {plant} has successfully been cultivated!")
input("Press enter to continue >>")
else:
raise IndexError
except IndexError:
print("The number must be in the list.")
input("Press enter to continue >>")
return
#Cultivate Rainbow Eucalyptus Tree
if plant == "Rainbow Eucalyptus Tree":
new_plant = Rainbow_Eucalyptus()
biomes_available = []
for biome in arboretum.forests:
if len(biome.plants) < 32:
biomes_available.append(biome)
if biomes_available == []:
print("There are no biomes available for this plant. Please annex the proper biome before attempting to cultivate!")
input("Press enter to continue >> ")
return
else:
for x in range(len(biomes_available)):
animals_in_biome_string = get_biome_specifics_animals(biomes_available, x)
plants_in_biome_string = get_biome_specifics_plants(biomes_available, x)
print(f"{x+1}. {biomes_available[x]} | {str(biomes_available[x].id)[:8]}{plants_in_biome_string}{animals_in_biome_string} | ({len(biomes_available[x].plants)}/32)")
try:
biome_choice = int(input("Choose a biome > "))- 1
except ValueError:
print("The input must be a number.")
input("Press enter to continue >>")
return
try:
if biome_choice >= 0:
biomes_available[biome_choice ].add_plant(new_plant)
os.system('cls' if os.name == 'nt' else 'clear')
print(f"The {plant} has successfully been cultivated!")
input("Press enter to continue >>")
else:
raise IndexError
except IndexError:
print("The number must be in the list.")
input("Press enter to continue >>")
return
#Cultivate Blue Jade Vine
if plant == "Blue Jade Vine":
new_plant = Blue_Jade()
biomes_available = []
for biome in arboretum.grasslands:
if len(biome.plants) < 12:
biomes_available.append(biome)
for biome in arboretum.swamps:
if len(biome.plants) < 15:
biomes_available.append(biome)
if biomes_available == []:
print("There are no biomes available for this plant. Please annex the proper biome before attempting to cultivate!")
input("Press enter to continue >> ")
return
else:
for x in range(len(biomes_available)):
plants_in_biome_string = get_biome_specifics_plants(biomes_available, x)
animals_in_biome_string = get_biome_specifics_animals(biomes_available, x)
if biomes_available[x].name == "Swamp":
print(f"{x+1}. {biomes_available[x]} | {str(biomes_available[x].id)[:8]}{plants_in_biome_string}{animals_in_biome_string} | ({len(biomes_available[x].plants)}/12)")
else:
print(f"{x+1}. {biomes_available[x]} | {str(biomes_available[x].id)[:8]}{plants_in_biome_string}{animals_in_biome_string} | ({len(biomes_available[x].plants)}/15)")
try:
biome_choice = int(input("Choose a biome > ")) - 1
except ValueError:
print("The input must be a number.")
input("Press enter to continue >>")
return
try:
if biome_choice >= 0:
biomes_available[biome_choice].add_plant(new_plant)
os.system('cls' if os.name == 'nt' else 'clear')
print(f"The {plant} has successfully been cultivated!")
input("Press enter to continue >>")
else:
raise IndexError
except IndexError:
print("The number must be in the list.")
input("Press enter to continue >>")
return
def get_biome_specifics_plants(biomes_available, x):
plants_in_biome = []
for plant in biomes_available[x].plants:
test_plants_in_biome = copy.deepcopy(plants_in_biome)
for item in plants_in_biome:
if item[0] == plant.species:
item.append(plant.species)
if test_plants_in_biome == plants_in_biome:
plants_in_biome.append([plant.species])
plants_in_biome_string = ""
for plant_list in plants_in_biome:
if plants_in_biome_string == "":
plants_in_biome_string = f" | ({len(plant_list)} {plant_list[0]}"
else:
plants_in_biome_string = plants_in_biome_string + f", {len(plant_list)} {plant_list[0]}"
if plants_in_biome_string != "":
plants_in_biome_string = plants_in_biome_string + ")"
return plants_in_biome_string
def get_biome_specifics_animals(biomes_available, x):
plants_in_biome = []
for plant in biomes_available[x].animals:
test_plants_in_biome = copy.deepcopy(plants_in_biome)
for item in plants_in_biome:
if item[0] == plant.species:
item.append(plant.species)
if test_plants_in_biome == plants_in_biome:
plants_in_biome.append([plant.species])
plants_in_biome_string = ""
for plant_list in plants_in_biome:
if plants_in_biome_string == "":
plants_in_biome_string = f" | ({len(plant_list)} {plant_list[0]}"
else:
plants_in_biome_string = plants_in_biome_string + f", {len(plant_list)} {plant_list[0]}"
if plants_in_biome_string != "":
plants_in_biome_string = plants_in_biome_string + ")"
return plants_in_biome_string
|
5deee4cfca0fb430299af44ccb3f7e99528d2d16 | pythonebasta/lab | /provaEreditarietaMultipla.py | 623 | 3.5625 | 4 | class madre:
def __init__(self):
pass
def parla(self):
print("Parla la classe madre")
class figlia(madre):
def __init__(self):
pass
#def parla(self):
#print("Parla la classe figlia")
class figlio(madre):
def __init__(self):
pass
def parla(self):
print("Parla la classe figlio")
class nipote(figlia, madre):
def __init__(self):
pass
#def parla(self):
# print("Parla la classe nipote")
mia_classe = nipote()
print()
mia_classe.parla()
print()
import numpy as np
arr = np.array([1, 2, 3, 4, 5, 6, 7])
print(arr[1:5])
|
682c65aa59bd11b213ea110266e4eea435012d62 | Enokisan/AtCoder-History | /AtCoder/ABC204/A/A.py | 152 | 3.53125 | 4 | a = list(map(int, input().split()))
if (a[0]==a[1]):
print(a[0])
elif not (0 in a):
print(0)
elif not (1 in a):
print(1)
else:
print(2) |
42594999794886d07edfb8f061a81112c017545f | balazsczap/adventofcode2019 | /1a.py | 573 | 3.703125 | 4 | import math
from functools import reduce
from input_1 import task_input
def calculate_basic_fuel(mass):
return math.floor(mass / 3) - 2
def add_extra_fuel(extra):
new_fuel = calculate_basic_fuel(extra)
if (new_fuel <= 0):
return 0
return new_fuel + add_extra_fuel(new_fuel)
def calculate_all_fuel(mass):
initial_fuel = math.floor(mass / 3) - 2
return initial_fuel + add_extra_fuel(initial_fuel)
fuels = map(lambda x: calculate_all_fuel(int(x)), task_input.splitlines())
result = reduce(lambda acc, val: acc + val, fuels)
print(result) |
a1f540295270989f0d3d615f1711a2d1108728c5 | Mayym/learnPython | /2-Python高级语法/2-2 函数式编程/1-3.py | 893 | 4.3125 | 4 | # 定义一个普通函数
def my_func(a):
print("In my_func")
return None
a = my_func(8)
print(a)
# 函数作为返回值返回,被返回的函数在函数体内定义
def my_func2():
def my_func3():
print("In my_func3")
return 3
return my_func3
# 使用上面定义
# 调用my_func2,返回一个函数my_func3,赋值给f3
f3 = my_func2()
print(type(f3))
print(f3)
f3()
print("-" * 100)
print(f3())
# 复杂一点的返回函数的例子
# args: 参数列表
# 1.my_func4定义函数,返回内部定义的函数my_func5
# 2.my_func5使用了外部变量,这个变量是my_func4的参数
def my_func4(*args):
def my_func5():
rst = 0
for n in args:
rst += n
return rst
return my_func5
f5 = my_func4(1,2,3,4,5,6,7,8,9,0)
# f5的调用方式
print(f5())
f6 = my_func4(10,20,30,40,50)
print(f6()) |
dd111751dc79151cd7ad7ebd8d69d15ab8de91b1 | shivangi-prog/leetcode | /generateParenthesis.py | 569 | 3.515625 | 4 | class Solution:
def generateParenthesis(self, n):
"""
:type n: int
:rtype: List[str]
"""
# 不用穷举组合+剪枝+堆栈判断,直接设定规则来生成就行
result = []
def generate(left, right, s):
if left == 0 and right == 0:
result.append(s)
return
if left:
generate(left - 1, right, s + '(')
if left < right:
generate(left, right - 1, s + ')')
generate(n, n, '')
return result
|
2eae74ab9edf88f0723a08b0f52c8f580337abeb | stephenchenxj/myLeetCode | /391_Perfect Rectangle.py | 2,673 | 3.8125 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Apr 28 15:17:58 2020
@author: chen
391. Perfect Rectangle
Hard
323
68
Add to List
Share
Given N axis-aligned rectangles where N > 0, determine if they all together form an exact cover of a rectangular region.
Each rectangle is represented as a bottom-left point and a top-right point. For example, a unit square is represented as [1,1,2,2]. (coordinate of bottom-left point is (1, 1) and top-right point is (2, 2)).
Example 1:
rectangles = [
[1,1,3,3],
[3,1,4,2],
[3,2,4,4],
[1,3,2,4],
[2,3,3,4]
]
Return true. All 5 rectangles together form an exact cover of a rectangular region.
Example 2:
rectangles = [
[1,1,2,3],
[1,3,2,4],
[3,1,4,2],
[3,2,4,4]
]
Return false. Because there is a gap between the two rectangular regions.
Example 3:
rectangles = [
[1,1,3,3],
[3,1,4,2],
[1,3,2,4],
[3,2,4,4]
]
Return false. Because there is a gap in the top center.
Example 4:
rectangles = [
[1,1,3,3],
[3,1,4,2],
[1,3,2,4],
[2,2,4,4]
]
Return false. Because two of the rectangles overlap with each other.
Accepted
23,277
Submissions
77,911
"""
import sys
class Solution(object):
def isRectangleCover(self, rectangles):
"""
:type rectangles: List[List[int]]
:rtype: bool
"""
cornersCnt = dict()
sumarea = 0
minx = sys.maxint
miny = sys.maxint
maxx = 0
maxy = 0
for rect in rectangles:
cornersCnt[(rect[0],rect[1])] = cornersCnt.get( (rect[0],rect[1]), 0) + 1
cornersCnt[(rect[2],rect[3])] = cornersCnt.get( (rect[2],rect[3]), 0) + 1
cornersCnt[(rect[0],rect[3])] = cornersCnt.get( (rect[0],rect[3]), 0) + 1
cornersCnt[(rect[2],rect[1])] = cornersCnt.get( (rect[2],rect[1]), 0) + 1
if minx > rect[0]:
minx = rect[0]
if miny > rect[1]:
miny = rect[1]
if maxx < rect[2]:
maxx = rect[2]
if maxy < rect[3]:
maxy = rect[3]
sumarea += (rect[2]-rect[0]) * (rect[3]-rect[1])
if sumarea != (maxx-minx)*(maxy-miny):
return False
fourCorners = [(minx, miny), (minx, maxy), (maxx, miny), (maxx, maxy)]
cnt = 0
for corner in cornersCnt.keys():
if cornersCnt[corner] == 1:
cnt += 1
if corner not in fourCorners:
return False
elif (cornersCnt[corner] != 2) and (cornersCnt[corner]!= 4):
return False
return cnt == 4
|
ff29d73189d1a5b638ddf1e61e0cece41948fc46 | trinhgliedt/Algo_Practice | /2021_06_14_merge_two_sorted_lists.py | 1,735 | 4.21875 | 4 | # https://leetcode.com/problems/merge-two-sorted-lists/
# Merge two sorted linked lists and return it as a sorted list. The list should be made by splicing together the nodes of the first two lists.
# Example 1:
# Input: l1 = [1,2,4], l2 = [1,3,4]
# Output: [1,1,2,3,4,4]
# Example 2:
# Input: l1 = [], l2 = []
# Output: []
# Example 3:
# Input: l1 = [], l2 = [0]
# Output: [0]
# Constraints:
# The number of nodes in both lists is in the range [0, 50].
# -100 <= Node.val <= 100
# Both l1 and l2 are sorted in non-decreasing order.
# Definition for singly-linked list.
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
class Solution:
def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode:
cur = ListNode(0)
# set ans here, cos we want ans to always be pointing at the head of cur. Cos at the end of the code cur won't be at the head anymore/
ans = cur
while (l1 and l2):
if l1.val > l2.val:
cur.next = l2
l2 = l2.next
else:
cur.next = l1
l1 = l1.next
cur = cur.next
while l1:
cur.next = l1
l1 = l1.next
cur = cur.next
while l2:
cur.next = l2
l2 = l2.next
cur = cur.next
return ans.next
s = Solution()
l1_1 = ListNode(5)
l1_2 = ListNode(6)
l1_4 = ListNode(8)
l1_1.next = l1_2
l1_2.next = l1_4
l2_1 = ListNode(1)
l2_3 = ListNode(3)
l2_4 = ListNode(4)
l2_1.next = l2_3
l2_3.next = l2_4
answer = s.mergeTwoLists(l1_1, l2_1)
print(answer)
while answer != None:
print(answer.val, end=",")
answer = answer.next
|
a61c710abbe43fdb1c1d315091bb33477044738d | Krishnom/python-udemy-course | /src/functions/excercise/master_yoda.py | 242 | 3.9375 | 4 | # MASTER YODA: Given a sentence, return a sentence with the words reversed
def master_yoda(text):
reversed_text = text.split()
# print(reversed_text)
reversed_text = reversed_text[::-1]
return " ".join(reversed_text)
pass
|
c63ebd3b8d5d02aba09c2425b95107118836b8ac | VainateyaDeshmukh/Python_DataStructure | /Python Practics.py | 10,587 | 3.921875 | 4 | import numpy as np
import pandas as pd
import matplotlib.pyplot as plot
import scipy as sc
#assignment no.1 (Question A) TM1817154
# Company can spend maximum 70,000 on training. Training will be approved for each employee in the same order as mentioned in Nomination1dictionary below.
# Following
# data is given:
# Fees
# for each course is:
# Fee = {'Python': 15000, 'R': 12000}
# Dictionary of employee id and the course they are opting for is:
#
# Nomination1 = {101: 'Python', 102: 'R', 103: 'Python', 104: 'Python', 105: 'R', 106: 'Python', 107: 'R'}
#
# Based on this data, write a function to store the approved output in the dictionary object.
#
# Expected
# output is:
# {101: 'Yes', 102: 'Yes', 103: 'Yes', 104: 'Yes', 105: 'Yes'}
# Note: Solve this using for loop only
def course1(total,fee,nomination1):
output={}
try:
for key in nomination1 : #alternative -----for key,course in nomination1.items():
if nomination1[key] in fee:
total=total - fee[nomination1[key]]
if total >=0:
output[key]='Yes'
else:
total = total + fee[nomination1[key]]
except Exception as e:
print("something has gone wrong in: %s-%s" %(key,e))
print(total)
return output
total = 70000
fee = {'Python':15000,'R':12000}
nomination1 ={101:'Python',102:'R',103:'Python',104:'Python',105:'R',106:'Python',107:'R'}
print(course1(total,fee,nomination1))
#assignment no.1 (Question B) TM1817154
#Company has a budget of 80,000 for training, cannot exceed this. Training cost for each employee is given below in the dictionary where key is employee id and value is training cost. Approval will be in the sequence of employee id.
# Cost = {101:18000,102:15000,103:18000,104:12000,105:15000,106:15000,107:12000}
#
# Based on this data, write a function to store the approved output in the dictionary object.
# Expected output is:
# {101: 'Yes', 102: 'Yes', 103: 'Yes', 104: 'Yes', 105: 'Yes', 106: 'No', 107: 'No'}
# Note: Solve this using while loop only
def course2(total,cost):
output = cost
i=0
list2 = list(output.keys())
list1 = list(output.values())
while i <= len(output) - 1:
try:
if total >= list1[i]:
total = total - list1[i]
output[list2[i]] = 'Yes'
i += 1
else:
output[list2[i]] = 'No'
i += 1
except:
print("something has gone wrong in:", list2[i])
i += 1
return output
total = 80000
cost ={101:18000,102:'gh',103:18000,104:12000,105:15000,106:15000,107:12000}
print(course2(total,cost))
#Assignment2 (Question1)-----------------------------------------------------------------------------------------------------
# Question A:
# List of product and list of corresponding quantity of each product are given below.
# prod = ['Prod1', 'Prod2', 'Prod2','Prod3','Prod1']
# qnt = [10,25,15,20,40]
# Write a function to store total of each product quantity. In the function, you will pass the parameters prod & qnt given above.
# Expected output:{'Prod1': 50, 'Prod2': 40, 'Prod3': 20}
# Note: While writing this code you will need unique value of prod, to get it, use set(prod) command
# TM1817154
def prod_qnt(prod, qnt):
output = {}
for i in range(0, len(prod)):
if prod[i] not in output:
output[prod[i]] = qnt[i]
else:
output[prod[i]] += qnt[i]
return output
prod = ['Prod1', 'Prod2', 'Prod2', 'Prod3', 'Prod1']
qnt = [10, 25, 15, 20, 40]
print(prod_qnt(prod, qnt))
#Assignment2 (Question2)
# Following data is given:
# qnt1=[10,25,15,20,40]
# price1 = [10,8,5,7,4]
# Write a function to create a list of purchase amount (qnt1*price1) of each item.
# Expected output: [100, 200, 75, 140, 160]
# Note: Calculate using map function
def qnt_price(qnt1,price1):
return list(map(lambda x,y :x*y,qnt1,price1))
qnt1=[10,25,15,20,40]
price1=[10,8,5,7,4]
print(qnt_price(qnt1,price1))
#Assignment 3 (Question A)--------------------------------------------------------------------------------------------------------------
# There are two categories of bank customers – Regular & Gold customers. Bank Name ‘ABC Bank’, is a static attribute at class level.
# In this scenario, we have following attributes:
# Customer ID (custid)
# Name (name)
# Method Print Statement (PrintState):
# You need to display message: “Customer Statement for Custid : 100, Name : Cust1 “
# For Regular customer :
# Daily Withdrawal limit (wlimit) – Set default to 1000 but can be changed on customer request.
# Method for checking bank balance & Print it (chkbal):
# If last quarter average balance is less than 10000 then return string “Low balance charges will be 100†else “No chargesâ€. Use this string to print the output, from the instance of the class.
# Last 12 months balance = [10000, 10000, 15000, 10000, 10000, 10000, 10000, 10000, 10000, 10000, 40000, 60000]
# For Gold customer will have:
# Name of Relationship manager (RM)
# Method for checking bank balance & Print it (chkbal):
# If last year average balance is less than 100000 then return string “Low balance charges will be 500†else “No chargesâ€. Use this string to print the output, from the instance of the class.
# Last 12 months balance = [100000, 100000, 150000, 100000, 100000, 100000, 100000, 100000, 100000, 100000, 40000, 60000]
# You need to set following values for the attributes of the instance of the class (object)
# Custid =100
# Name = ‘Cust1’
# RM = ‘RM1’
# Create appropriate classes and demonstrate how you are using inheritance and polymorphism.
class Customer:
bank ="ABC BANK"
def __init__(self,custid,custname):
# object attributes
self.id = custid
self.name = custname
def print_statement(self):
print("Customer Statement for Custid : {0}, Name : {1}".format(self.id,self.name))
class Regular_cust(Customer):
def __init__(self,wlimit,list1,custid,custname):
# object attributes
super().__init__(custid,custname)
self.wlimit = 1000
self.list=list1
def checkbal(self):
a=sum(self.list[-3:])
super().print_statement()
if a/3 < 10000:
string = "Low balance charges will be 100"
else :
string ="no charges"
print(string)
class Gold_cust(Customer):
def __init__(self,rmname,list1,custid,custname):
# object attributes
super().__init__(custid,custname)
self.rmname = rmname
self.list=list1
def checkbal(self):
super().print_statement()
a=sum(self.list)
if a/12 < 100000:
string = "Low balance charges will be 500"
else:
string = "no charges"
print(string)
def checkbalance(CustType):
CustType.checkbal()
rmname="RM1"
wlimit=2000
custid=100
custname='Cust1'
list1=[10000, 10000, 15000, 10000, 10000, 10000, 10000, 10000, 10000, 10000, 40000, 60000]
list2=[100000, 100000, 150000, 100000, 100000, 100000, 100000, 100000, 100000, 100000, 40000, 60000]
g1=Gold_cust(rmname,list2,custid,custname)
r1=Regular_cust(wlimit,list1,custid,custname)
checkbalance(g1)
#Assignment No3 (QuestionB) TM1817154
# Write following string to the file ‘TextAssign3b.txt’
# “There are some phone no. (022)-2367, (020)-5689, 8970 22, (020)-8945, 020-4599. Also, we have some email aa@abc.com, pqr@abc.com, zz@xyz.com, kk.com “
# You need to extract phone starting with the code format (020) only. Also, extract email with a domain abc.com.
import re
txt="There are some phone no. (022)-2367, (020)-5689, 8970 22, (020)-8945, 020-4599. " \
"Also, we have some email aa@abc.com, pqr@abc.com, zz@xyz.com, kk.com"
d=re.findall('[\w]+@abc.com',txt)
print(d)
e=re.findall(r'\(020\)\d{3}-\d{4}',txt)
print(e)
#Assignment No 4----------------------------------------------------------------------------------------------
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
data = pd.read_csv("C:\\Users\\Swapnil Bhor\\PycharmProjects\\data\\Emp.csv")
data1=data.copy()
#Question1
# What is the education & income of empid =2 & 5. Extract using both methods (positional and label name based).
a1=data.iloc[[1,4],[2,6]]#positional
a2=data.loc[[1,4],["Education","Income"]]#Label name based
#Question2
#Get the age of emp where education is ‘UG’ and income is greater than 5000.
df1=data[(data.Education=='UG') & (data.Income >=5000)].loc[:,["Age"]]
# df4=data[(data.Education=='UG') & (data.Income >=5000)]["Age"]
#Question3
# Sort the same dataframe object in the descending order of income.
data.sort_values('Income',inplace=True,ascending=False)
#Question4
# How to get the following output from the given data?
# Age Income
# Gender F M F M
# Dept
# Research 29.00 39.67 4193.0 4777.0
# Sales 44.33 36.00 4451.0 3251.0
p1=pd.pivot_table(data,index=['Dept'],values=['Age','Income'],columns=['Gender'],aggfunc=[np.mean])
p1=round(p1,2)
print(p1)
#Question5
# Create a new dataframe object with two records and combine it with the original dataframe.
# 15 Research UG F No 25 3500
# 14 Sales PG M Yes 4500
#using lists
lst1 = [[15,'Research','UG','F','No',25,3500],[14,'Sales','PG','M','Yes',np.nan,4500]]
df1= pd.DataFrame(lst1,columns=['EmpID','Dept','Education','Gender','Married','Age','Income'])
df13=pd.concat([data1,df1],ignore_index=True)
#using dictionary
dict1={'EmpID':[15,14],'Dept':['Research','Sales'],'Education':['UG','PG'],'Gender':['F','M'],'Married':['M','F'],'Age':[25,np.nan],'Income':[3500,4500]}
df2=pd.DataFrame(dict1)
df23=pd.concat([data1,df2],ignore_index=True)
#Question 6
# Create bar chart using following data:
# city = ['Mumbai', 'Pune', 'Chennai', 'Delhi']
# Customers = [1200, 1000, 800, 1500]
city = ['Mumbai', 'Pune', 'Chennai', 'Delhi']
Customers = [1200, 1000, 800, 1500]
plt.bar(city,Customers,width=.5)
plt.xlabel('City')
plt.ylabel('Customers')
plt.title('City vs Customers')
plt.show()
#Question7
# Create Numpy array in the range of 0 to 50 which is multiple of 10.
# Create another array of random number between 100 to 200. Add both the arrays.
# Make sure that result should not keep changing every time.
a1 = np.arange(0,50,10)
np.random.seed(123)
a2=np.random.randint(1,100,5)
a3=np.add(a1,a2)
|
5f5141f8985e0d1d11d4be85c555d287eb721939 | append-knowledge/pythondjango | /1/exam/cal.py | 705 | 4 | 4 | def add(num1,num2):
print(num1+num2)
def sub(num1,num2):
print(num1-num2)
def mul(num1,num2):
print(num1*num2)
def div(num1,num2):
print(num1/num2)
def expo(num1,num2):
print(num1**num2)
print("calculator")
x=print('1)ADDITION\n2)SUBTRACTION\n3)MULTIPLICATION\n4)DIVISION\n5)EXPONENT')
print()
y=int(input('enter the operetion '))
num1=float(input("enter the first number "))
num2=float(input('enter the second number '))
if y >= 6:
print('check the number you have dialed')
elif y==1:
add(num1,num2)
elif y==2:
sub(num1,num2)
elif y==3:
mul(num1,num2)
elif y==4:
div(num1,num2)
elif y==5:
expo(num1,num2)
else:
print("check the number you have dialed") |
462458fd63d7d98a8016c632764da4c111877bce | wereii/simple-raspi-rc | /client.py | 1,203 | 3.53125 | 4 | # python3
import sys
import socket
import keyboard
import time
DELAY = 0.1
UDP_IP = ""
UDP_PORT = 6666
if not UDP_IP:
# Pokud neni zadana IP, nastav na localhost
UDP_IP = "127.0.0.1"
if not UDP_PORT:
# Pokud neni zadan port, nastav na 8008
UDP_PORT = 8008
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
print("Sending commands to {}:{}".format(UDP_IP, UDP_PORT))
def send_msg(data):
try:
sock.sendto(str(data).encode(), (UDP_IP, UDP_PORT))
except Exception as ex:
print("Something went wrong.")
print(ex)
def try_is_pressed(key):
# Catching 'dictionary changed size'
try:
return keyboard.is_pressed(key)
except RuntimeError:
return False
while True:
time.sleep(DELAY)
# Each command is presented as number
# Server has definitions what to do for each number
# It's possible to send whole word instead of number
# but for sake of
if try_is_pressed('up'):
send_msg(1)
if try_is_pressed('down'):
send_msg(2)
if try_is_pressed('right'):
send_msg(3)
if try_is_pressed('left'):
send_msg(4)
if try_is_pressed('esc'):
send_msg(5)
|
6c103ea08f35adcb390584b53d661188cf5ae622 | Davestrings/PythonCode | /consecutivesum.py | 190 | 4.0625 | 4 | number = int(input("Enter a number: "))
num=1
total = 0
# while num <= number:
while num <= number:
total = total + num
num += 1
print(total)
if total % num == 0:
print(total)
|
52de584817f5c5f763f3a12721fcdab4d796f239 | roopish/csv_report | /Python/csv_report.py | 775 | 3.796875 | 4 | #!/usr/bin/env python
def main():
csvfile = open('test.csv', 'r')
input_dict = {} # dictionary to store names, events and avg time
mean=0.0
for line in csvfile.readlines():
cols = line.split(",")
names = cols[0].title() #capitalize first letter
time = cols[1]
city = cols[2]
if input_dict.get(names): #name already exists in dictionary
input_dict[names].append(time)
else: #new record
input_dict[names] = list([time])
print("Name\t"+"Avg_time\t"+"No_Of_events")
for key,time in input_dict.items():
mean = (sum(map(int, time))/len(time))
print(key+"\t"+str(mean)+"\t\t"+ str(len(time)));
#-------------------------------
if __name__ == "__main__":
main()
|
70cc764305b915f31e9661034f598333b09560f5 | edevaldolopes/learning | /04 - stringsList.py | 628 | 3.953125 | 4 | txt1 = 'The best code'
list1 = ['one', 'two', 'three']
print(txt1)
print(list1)
print(txt1[0])
print(list1[0])
# slice
print(txt1[0:3])
print(list1[0:2])
# slice, step
print(list1[0:3:2])
# negative
print(list1[-1])
# add
list1.append('four')
list1.insert(0, 'zero')
print(list1)
# remove
list1.remove('one')
del list1[2]
print(list1)
# rename
list1[0] = 'one'
list1[1] = 'one'
list1[2] = 'one'
print(list1)
# count
print(list1.count('one'))
# text
print(len(txt1))
print(txt1.count('e'))
print(txt1.find('best'))
print(txt1.upper())
print(txt1.capitalize())
# test logic
print(txt1.islower())
print(txt1.isnumeric())
|
d45f36617d30097b343495ceb641fce508e3c392 | ZinollinIlyas/python | /18/classwork/example.py | 414 | 3.59375 | 4 | class Cat:
def __init__(self, name, age=None, color="White"):
self.name = name
self.age = age
self.color = color
def meow(self, something):
print("Meow", something)
def purr(self):
print("Purrr")
def ask_food(self):
for i in range(3):
self.meow("asd")
self.purr()
murka = Cat("Murka", color="white", age=5)
print(murka.name)
|
5e05c2170523529aee4e56239f335f2ced135a62 | lishuchen/Algorithms | /leecode/26_Remove_Duplicates_from_Sorted_Array.py | 400 | 3.546875 | 4 | #!/usr/bin/env python
# -*- coding: UTF-8 -*-
class Solution(object):
def removeDuplicates(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
if not nums:
return 0
idx = 1
for i in range(1, len(nums)):
if nums[i] != nums[i - 1]:
nums[idx] = nums[i]
idx += 1
return idx
|
628d238e9c033a7ab2c8d5661098a1e07866e3d2 | gabriellaec/desoft-analise-exercicios | /backup/user_102/ch41_2019_09_03_22_24_47_823991.py | 188 | 3.96875 | 4 | senha = true
while senha:
x = str(input("Tenta acertar minha senha:"))
if x==andre:
print("desisto")
else:
print("Você acertou a senha!")
senha = false |
7e8ef4c22515967e6e981ebbc6c77a2953d4d49f | pigswillfly/advent_of_code_2019 | /1_solution_a.py | 150 | 3.546875 | 4 | f = open('1_puzzle_input.txt', 'r')
total_fuel = 0
for line in f.readlines():
fuel = int(int(line) / 3) - 2
total_fuel += fuel
print(total_fuel)
|
4dbd78e0f3fdffe0d847c60e60501de5c860dab2 | provoke01/Python-Programs | /Typecasting.py | 298 | 3.9375 | 4 | name = "Bill"
count = 1234
floaty = 95.9500
stranger = str(count)
intfloat = float(count)
print("Integer: ", count)
print("String: ", name)
print("Float: ", floaty)
print("Integer to String: ", stranger)
print("Integer to Float: ", intfloat)
print("Thats the basics of typecasting primitive types") |
acf59533b034956b615a5fd7fafdedfb4652465f | 11EXPERT11/pythonProject | /Start.py | 483 | 3.703125 | 4 | from random import randint
print("угадай число от 0 до 50 которое я загадал")
user = int(input())
num = randint(0, 50)
while user != num:
user = int(input("повторите попытку"))
if user < num:
print("ваше число меньше загаданного")
elif user > num:
print("ваше число больше загаданного")
else:
print("вы угадали")
break
|
9c12c141f69093bf17c00988aed93c8928572471 | Timur1986/work-with-FILE | /io_conor.py | 430 | 3.734375 | 4 | # Копировать файл с новым названием (способами без with)
x = input('Укажите имя файла для копирования: ')
y = input('Введите новое имя файла: ')
n_conor = open(x, 'rb')
n_chicken = open(y, 'wb')
n_chicken.write(n_conor.read())
n_conor.close()
n_chicken.close()
print('Файл с новым именем успешно создан!')
|
e5460f8fea63034afd4e2454b728e8752f31bbb1 | grodrigues3/InterviewPrep | /Leetcode/symmetricBinTree.py | 1,885 | 4.03125 | 4 | """
Symmetric Tree Total Accepted: 66661 Total Submissions: 210965 My Submissions Question Solution
Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center).
For example, this binary tree is symmetric:
1
/ \
2 2
/ \ / \
3 4 4 3
But the following is not:
1
/ \
2 2
\ \
3 3
Note:
Bonus points if you could solve it both recursively and iteratively.
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
"""
class Solution:
# @param {TreeNode} root
# @return {boolean}
def isSymmetric(self, root):
if not root or (root.left is None and root.right is None):
return True
qL = [root.left]
qR = [root.right]
while qL or qR:
curL = qL.pop(0)
curR = qR.pop(0)
if curR is None and curL is None:
continue
elif curR is None or curL is None:
return False
if curL.val != curR.val:
return False
qL += curL.left,
qL += curL.right,
qR += curR.right,
qR += curR.left,
return True
if __name__ == "__main__":
from data_structures.TreeNode import TreeNode
threeL = TreeNode(3)
threeR = TreeNode(3)
fourL = TreeNode(4)
fourR = TreeNode(4)
twoL = TreeNode(2)
twoR = TreeNode(2)
root = TreeNode(1)
root.left = twoL
root.right = twoR
twoL.left = threeL
twoR.right = threeR
twoL.right = fourR
twoR.left = fourL
S = Solution()
print S.isSymmetric(root) #example from comments above
twoR.right, twoR.left = twoR.left, twoR.right #swap two nodes and...
print S.isSymmetric(root) #as is above
|
d1f09e2d52ca12134467857590e76101caa47802 | zerformza5566/CP3-Peerapun-Sinyu | /assignment/Exercise8_Peerapun_S.py | 1,440 | 3.515625 | 4 | userName = input("Id : ")
password = input("Password : ")
if userName == "admin" and password == "1234":
print("Login completed.")
print("----FPStore----")
print("-------Product list--------")
print("1. Leather bag : 150 THB")
print("2. Backpack : 199 THB")
print("3. Wallet : 220 THB")
print("---------------------------")
userSelectedProduct = int(input("ระบุสินค้าที่ต้องการ : "))
if userSelectedProduct == 1:
print("1. Leather bag")
userQuantityProduct = int(input("จำนวนสินค้าที่ต้องการ : "))
print("Leather bag", userQuantityProduct, "ชื้น เป็นเงิน:", 150 * userQuantityProduct)
elif userSelectedProduct == 2:
print("2. Backpack")
userQuantityProduct = int(input("จำนวนสินค้าที่ต้องการ : "))
print("Backpack", userQuantityProduct, "ชื้น เป็นเงิน:", 199 * userQuantityProduct)
elif userSelectedProduct == 3:
print("3. Wallet")
userQuantityProduct = int(input("จำนวนสินค้าที่ต้องการ : "))
print("Wallet", userQuantityProduct, "ชื้น เป็นเงิน:", 220 * userQuantityProduct)
print("----ขอบคุณ----")
else:
print("Incorrect Id/Password.") |
1fc51b04dc63b9c87e0062405298b371c72ff793 | Tharnickanth/Python-For-Beginners | /ControlFlow/TernaryOperator.py | 107 | 3.96875 | 4 |
age = int(input("Enter you age :"))
message = "Eligible" if age >= 18 else "Not Eligible"
print(message)
|
639fbdb1856bda615837fb5124df84b202a687bf | YJL33/LeetCode | /current_session/daily_challenge/find_nearest_right_node_in_binary_tree.py | 819 | 3.828125 | 4 | # Definition for a binary tree node.
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
import collections
from typing import Optional
class Solution:
def findNearestRightNode(self, root: TreeNode, u: TreeNode) -> Optional[TreeNode]:
# use BFS-like strategy: craft layer(s)
dq = collections.deque()
dq.append((root,0))
while dq:
while len(dq) != 0:
nd, layer = dq.popleft()
if nd == u:
return dq.popleft()[0] if dq and dq[0][1] == layer else None
if nd.left:
dq.append((nd.left, layer+1))
if nd.right:
dq.append((nd.right, layer+1))
return None |
f11bc41703e34183643e6064c7d982ec18c18f62 | jbub/spy-data-types | /strings.py | 1,248 | 4.6875 | 5 | # lets define some strings
my_string = "hello there!"
# accesing individual characters by indexes
my_string[1]
# slicing also works for strings
my_string[1:4]
# string concatenation
my_string + ' hello ' + ' world '
# concatenation of other types (explicit conversion is needed)
number = 3
'My number is = ' + str(3)
# old way of string formatting
'My name is %s, and my age is %d' % ('John', 32)
# new way of string formatting
'My name is {0}, and my age is {1:d}'.format('Alicia', 32)
'My name is {name}, and my age is {age:d}'.format(name='Jane', age=22)
# join elements of sequence using string delimiter
', '.join(['my', 'oh', 'my'])
# lowercase all characters
my_string.lower()
# uppercase all characters
my_string.upper()
# is string alphabetic only ?
my_string.isalpha()
# is string digit only ?
my_string.isdigit()
# is string whitespace only ?
my_string.isspace()
# is string starting/ending with prefix, suffix ?
my_string.startswith('hello')
my_string.endswith('world')
# replace occurrences of hello with world
my_string.replace('hello', 'world')
# split string into list by separator
my_string.split(',')
# returns string left filled with "0" digits to make a string of length width
my_string.zfill(3) |
b63161d220b2066182b0baf591d11e67affa1bae | nwthomas/code-challenges | /src/daily-coding-problem/easy/find-friend-groups/test_find_friend_group.py | 674 | 3.546875 | 4 | from find_friend_groups import find_friend_groups
import unittest
class TestFindFriendGroups(unittest.TestCase):
def test_returns_two_groups(self):
"""Takes in an adjacency list of friends and returns 2"""
adj_list = {0: [1, 2], 1: [2], 2: [0], 3: []}
result = find_friend_groups(adj_list)
self.assertEqual(result, 2)
def test_returns_three_groups(self):
"""Takes in an adjacency list of friends and returns 3"""
adj_list = {0: [1, 2], 1: [0, 5], 2: [0], 3: [6], 4: [], 5: [1], 6: [3]}
result = find_friend_groups(adj_list)
self.assertEqual(result, 3)
if __name__ == "__main__":
unittest.main() |
78217df7c72e3745b091d8e986aa397389502f76 | amantaya/Image-Processing-Python | /image-processing/09-connected-components/InvContours.py | 953 | 3.875 | 4 | '''
* Python program to use contours to count the objects in an image.
'''
import cv2
import sys
# read command-line arguments
filename = sys.argv[1]
t = int(sys.argv[2])
# read original image
img = cv2.imread(filename)
# create binary image
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
blur = cv2.GaussianBlur(gray, (5, 5), 0)
(t, binary) = cv2.threshold(blur, t, 255, cv2.THRESH_BINARY_INV)
# find contours
(_, contours, _) = cv2.findContours(binary, cv2.RETR_EXTERNAL,
cv2.CHAIN_APPROX_SIMPLE)
# print table of contours and sizes
print("Found %d objects." % len(contours))
for (i, c) in enumerate(contours):
print("\tSize of contour %d: %d" % (i, len(c)))
# draw contours over original image
for (i, c) in enumerate(contours):
if len(c) > 100:
cv2.drawContours(img, [c], 0, (0, 0, 255), 5)
# display original image with contours
cv2.namedWindow("output", cv2.WINDOW_NORMAL)
cv2.imshow("output", img)
cv2.waitKey(0)
|
189c5653ecfd297a60c6f1bcadc38794f4754a52 | matkins1/Project-Euler | /P23.py | 3,720 | 4 | 4 | ## Problem 23
## A perfect number is a number for which the sum of its proper divisors is exactly equal to the number.
## For example, the sum of the proper divisors of 28 would be 1 + 2 + 4 + 7 + 14 = 28, which means that 28 is a perfect number.
## A number n is called deficient if the sum of its proper divisors is less than n and it is called abundant if this sum exceeds n.
## As 12 is the smallest abundant number, 1 + 2 + 3 + 4 + 6 = 16, the smallest number that can be written as the sum of two abundant numbers is 24.
## By mathematical analysis, it can be shown that all integers greater than 28123 can be written as the sum of two abundant numbers.
## However, this upper limit cannot be reduced any further by analysis even though it is known that the greatest number that cannot be
## expressed as the sum of two abundant numbers is less than this limit.
## Find the sum of all the positive integers which cannot be written as the sum of two abundant numbers.
# define function for creating list tuples of (numbers, sum of factors)
def factors():
# initialize list for holding tuples for 1) each number 1 through 28,123 and 2) sum of factors of that number & other storage lists
list = []
temp_list = []
# iterate through range 14,061 (half of 28,123 amount above as we are looking at sums of two abundant numbers)
for i in range(1,28124):
# clear temp_list for storage of factors of next iteration
temp_list = []
# test for factors of each number in range above
for j in range(1,i):
if i % j == 0:
# if factor is found, store factor in list
temp_list.append(j)
# appends tuple of (each successive digit in 28,123 range, sum of all factors of that digit)
list.append((i,sum(temp_list)))
# returns list of tuples (number, sum of factors)
return list
# define function for returning list of abundant numbers using factors() function
def return_abundant():
# calls factors() function and stores results in list
list = factors()
#initialize list to hold all abundant numbers
abundant_list = []
# code to iterate through "list" and check for abundant numbers pairs in list and store those numbers in "abundant_list"
for k in range(0,len(list)):
if list[k][1] > list[k][0]:
abundant_list.append(list[k][0])
# returns list of all abundant numbers
return abundant_list
# define function to generate all sums of two abundant numbers from list of abundant numbers using factors() and return_abundant() functions
def check_abundant():
# import timeit and start timer to measure time of function
import timeit
start = timeit.default_timer()
import itertools
# calls return_abundant() function and stores results in list
list = return_abundant()
abundant_sums = []
# iterate through list and generate sums of all numbers
for l in range(0,len(list)):
for m in range((l-1),len(list)):
abundant_sums.append(list[l] + list[m])
# sort and remove duplicates
abundant_sums = sorted(set(abundant_sums))
# remove all sums over 28123
abundant_sums = filter(lambda a: a < 28124, abundant_sums)
# returns solution which is sum of all positive integers through 28,123 less sum of integers that can be made with abundant sums
print (sum(range(0,28124)) - sum(abundant_sums))
# stop timer and print total elapsed time
stop = timeit.default_timer()
print "Total time:", stop - start, "seconds" |
812efd2e2f99e0de1588171c5f8b198859eefae2 | Melifire/CS120 | /Projects/Short 1/swap.py | 458 | 4.09375 | 4 | ''' File: swap.py
Author: Ben Kruse
Purpose: Swap the first half and second half of an input,
leaves the middle character if applicable
'''
import math
def main():
inp = input('Please give a string to swap: ')
length = len(inp)
print(inp[math.ceil(length / 2) : ] + #takes the last chars
inp[length//2 : math.ceil(length/2)] + #takes mid char (if appl.)
inp[ : length//2]) #takes the starting chars
main()
|
c0e5eac05c5e860915f5913619cd8a11db4c7ae1 | jbmenashi/python-course | /functions/basic_functions.py | 335 | 3.59375 | 4 | def say_hi ():
print("Hi")
say_hi()
def print_square_of_7():
return 7 * 7
print(print_square_of_7())
from random import random
def coin_flip():
if random() > 0.5:
return "heads"
else:
return "tails"
print(coin_flip())
def generate_evens():
return [num for num in range(1, 50) if num % 2 == 0] |
86a45b7671abb488d1bebb64b4bb4479b2b4ae2d | abhishekparakh/Matasano-Challenges | /P3-alt.py | 1,957 | 3.765625 | 4 | #Single-byte XOR cipher
import binascii
import sys
from bitstring import BitArray
#using only the two few characters to check for frequencies
vowels = ['e', 't', 'a', 'o', 'i', 'u']
englishLetters = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', \
'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', \
'q', 'r', 's', 't', 'u', 'v', 'w', 'x', \
'y', 'z']
#Decryption part
string = '26294f2e4f222e214f263c4f2029292a3d2a2b4f2e4f292e2c3b4f3827262c274f28202a3c4f2e282e26213c3b4f27263c4f26213c3b26212c3b3c4f272a4f382623234f3c2c3d3a3b262126352a4f263b4f2c23203c2a23364f2e212b4f3a21232a3c3c4f3b272a4f2a39262b2a212c2a4f263c4f20392a3d38272a23222621284f272a4f382623234f3d2a293a3c2a4f3b204f2d2a23262a392a4f263b4f26294f20214f3b272a4f203b272a3d4f272e212b4f272a4f263c4f2029292a3d2a2b4f3c20222a3b272621284f3827262c274f2e2929203d2b3c4f2e4f3d2a2e3c20214f29203d4f2e2c3b2621284f26214f2e2c2c203d2b2e212c2a4f3b204f27263c4f26213c3b26212c3b3c4f272a4f382623234f2e2c2c2a3f3b4f263b4f2a392a214f20214f3b272a4f3c232628273b2a3c3b4f2a39262b2a212c2a4f3b272a4f203d262826214f20294f22363b273c4f263c4f2a373f232e26212a2b4f26214f3b27263c4f382e36'
text = bytes.fromhex(string).decode('utf-8')
print(text)
#Trying to break the cipher by counting characters
#Looking for most commonly occurring character (e) and then finding out what it is xored with to get the key
charFreq = dict()
for c in text:
if c not in charFreq:
charFreq[c] = 1
else:
charFreq[c] += 1
#Find the most commonly occurring character
currentHighest = -1
charHighest = ''
for t in charFreq:
if charFreq[t] > currentHighest:
currentHighest = charFreq[t]
charHighest = t
#print(charHighest)
#print(currentHighest)
print('key: ', chr(ord(charHighest) ^ ord(' '))) #space is the most common character
#Decryption part ends
#Encryption part starts
#text = 'IF A MAN IS OFFERED A FACT WHICH GOES AGAINST HIS INSTINCTS HE WILL ' \
# 'SCRUTINIZE IT CLOSELY AND UNLESS THE EVIDENCE IS OVERWHELMING HE WILL ' \
# 'REFUSE TO BELIEVE IT IF ON THE OTHER HAND HE IS OFFERED SOMETHING WHICH ' \
# 'AFFORDS A REASON FOR ACTING IN ACCORDANCE TO HIS INSTINCTS HE WILL ACCEPT ' \
# 'IT EVEN ON THE SLIGHTEST EVIDENCE THE ORIGIN OF MYTHS IS EXPLAINED IN THIS WAY'
#print(text)
#Encryption part ends
for k in englishLetters:
out = ''
for c in text:
out += chr(ord(k)^ord(c))
print("key: ", k, ' Decryption: ', out) #prints ASCII characters (used during decryption)
#out = out.encode() #convert to bytes like object #for encryption
#print(out.hex()) #convert bytes like objects to hex #for encryption
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.