blob_id stringlengths 40 40 | repo_name stringlengths 5 127 | path stringlengths 2 523 | length_bytes int64 22 3.06M | score float64 3.5 5.34 | int_score int64 4 5 | text stringlengths 22 3.06M |
|---|---|---|---|---|---|---|
b772bc7a8556a4070ebf851945f161225e10e8c9 | anamariagds/listas_remoto | /semana7/eh_primo.py | 412 | 3.75 | 4 | def eh_primo(n):
inicio = 1
divisor = 0
while inicio<= n:
if n % inicio == 0:
divisor +=1
inicio +=1
return divisor
def main():
n =int(input("Digite um número: "))
d = eh_primo(n)
if d ==2:
print(f'O número {n} é Primo')
else:
pr... |
1ce025f3c757223a58d45f1297c77792d2bc169a | anamariagds/listas_remoto | /semana7/H.py | 269 | 3.734375 | 4 | def somatorio():
n = int(input("Digite o valor de n: "))
i = 1
H = 1
while i <n:
i+=1
H += (1/i)
if i ==n:
break
print(f'O valor de H é {H:.4f}')
def main():
somatorio()
if __name__=='__main__':
main()
|
420a970d2a73a9219d5fad02ab0b01d825409e04 | anamariagds/listas_remoto | /projetos_pec166/semana8/ex3.py | 477 | 3.921875 | 4 | from random import *
print("Gerador de cumprimentos")
adjetivos = ['maravilhosa', 'acima da média', 'excelente', 'íncrivel', 'competente']
hobbies = ['andar de bicicleta', 'programar', 'fazer chá', 'em leitura', 'cantar']
nome = input("Qual é o seu nome?: ")
print("Aqui está o seu cumprimento", nome , ":")
#obtém i... |
ab1039cfe770712d7ab98a9b413765013c4e2c26 | anamariagds/listas_remoto | /semana8/maiorqmedialistasex.py | 463 | 3.640625 | 4 | def ler_notas(n):
notas = []
for i in range(n):
notas.append(float(input(f'Nota {i+1} de {n}: ')))
return notas
def media(notas):
return sum(notas)/len(notas)
def maiores_que(media, notas):
maiores = []
for nota in notas:
if nota > media:
maiores.append(nota)
r... |
2428a5c917bc1b5b99401b3461f7fe3e9b144c7c | anamariagds/listas_remoto | /projetos_pec166/testandopedac.py | 643 | 3.859375 | 4 |
score = 0
def q1(marcou):
if marcou.lower() == 'a':
global score
score = score+1
return f'Certa!'
elif marcou.lower() == 'b':
return f'Pense um pouco'
elif marcou.lower() == 'c':
return f'Estude mais!'
else:
return f'Você não escolheu uma alternativa v... |
f1073e9fd0b05a6ed68dd4efca274204ebcea20d | anamariagds/listas_remoto | /condicionais/evogal.py | 241 | 3.640625 | 4 | def vogal(l):
if l in 'a A e E i I o O u U':
return True
else:
return False
def main():
letra = str(input("Digite uma letra: "))
teste = vogal(letra)
print(teste)
if __name__ == '__main__':
main()
|
7579f7c27794f366b1d1e47b32f0b0f7e447683c | anamariagds/listas_remoto | /projetos_pec166/semana8/ex2.py | 328 | 3.546875 | 4 | from random import*
print("Gerador de Cumprimentos")
print("-------------------")
cumprimentos=["Excelente trabalho. Realmente muito bem feito.",
"Suas habilidades de programaçãp são muito, muito boas!",
"Você é um humano excelente"
]
print(choice(cumprimentos))
print("De nada... |
28dce4905d8671b15c6175afdead6a90619ee16b | anamariagds/listas_remoto | /semana10/conversorparte3.py | 2,132 | 3.984375 | 4 | def menu():
print("trdtr de exprss")
print("="*13)
print("Menu: ")
print('''
c = converter uma frase
p = imprimir dicionário
a = adicionar uma palavra
d = remover uma palavra
q = sair
''')
def convertetxt(texto):
sentence = input("Insira uma frase: ").lower()
transform... |
65926fa0c9bce1efd05487eab5df936a22f2a771 | anamariagds/listas_remoto | /condicionais/maisatual.py | 786 | 3.9375 | 4 | def recente(ano1, ano2, mes1, mes2, dia1, dia2):
if (ano1 > ano2) or (ano1 == ano2 and mes1>mes2) or (ano1 == ano2 and mes1==mes2 and dia1>dia2):
return f'{dia1}/{mes1}/{ano1}'
elif (ano2 > ano1) or (ano1 == ano2 and mes2 > mes1) or (ano1 == ano2 and mes2==mes1 and dia2>dia1):
return f'{dia2}/{... |
1e36a8f36f30a8f4131ffa58c2c6664dc88bf76f | aefritz/fivethirtyeight-cafe-solution | /solution.py | 283 | 3.84375 | 4 | import math
iterator = 0
accumulator = 0.00000
while iterator <= 50:
accumulator += float(math.factorial(50 + iterator)*pow(.5, 50)*pow(.5,iterator)*(50-iterator)/(math.factorial(iterator)*math.factorial(50)))
iterator += 1
print("The expected value is " + str(accumulator))
|
af2c02c975c53c1bd12955b8bbe72bac35ab54fd | BryanBain/Statistics | /Python_Code/ExperimProbLawOfLargeNums.py | 550 | 4.1875 | 4 | """
Purpose: Illustrate how several experiments leads the experimental probability
of an event to approach the theoretical probability.
Author: Bryan Bain
Date: June 5, 2020
File: ExperimProbLawOfLargeNums.py
"""
import random as rd
possibilities = ['H', 'T']
num_tails = 0
num_flips = 1_000_000 # change this value ... |
76410773c1e3e749db0098d256f86f71e6ab9c05 | BryanBain/Statistics | /Python_Code/ttest1samp.py | 4,481 | 3.765625 | 4 | """
Purpose: Perform a t test for a one sample mean with user input.
Author: Bryan Bain
Date: July 10, 2020
File Name: ttest1samp.py
"""
import scipy.stats as stats
import math
import numpy as np
def obsToT(xbar, mu, sigma, n):
return (xbar-mu)/(sigma/math.sqrt(n))
quit = False
while not quit:
mu = ... |
e151546301909f5fed9bdc0e85a83a3a86080a9f | lannyMa/py_infos | /01/in_func.py | 169 | 3.546875 | 4 | #!/usr/bin/env python
# coding=utf-8
# 实现in
a = "i am maotai"
is_in = False
stra = "ma"
for s in a:
if s == stra:
is_in=True
break
print is_in |
df8334c84f13066e6b62f062f049709225de1065 | lannyMa/py_infos | /03/zhuce.py | 497 | 3.6875 | 4 | #!/usr/bin/env python
# coding=utf-8
#----------------
# 注册模块
#----------------
while True:
name = raw_input("name: ").strip()
pwd = raw_input("pwd: ").strip()
pwd2 = raw_input("pwd: ").strip()
if pwd != pwd2:
print "密码不一致,re-enter"
continue
if name and pwd:
with open("user... |
0bd4d260bef0115c7b7bbd1f1a3ff961b8d12f11 | dart-neitro/xmltodict3 | /tests/test_xml_to_dict.py | 6,521 | 3.53125 | 4 | import xml.etree.ElementTree as ElementTree
from xmltodict3 import XmlToDict
def test_simple_case():
text = "<root>1</root>"
etree_element = ElementTree.fromstring(text)
expected_result = {'root': '1'}
result = XmlToDict(etree_element).get_dict()
assert result == expected_result, result
def tes... |
4f0019dc7b77f7c5190b4dd3dba50244af97a009 | Qazaqbala-N/last | /lab7/WEBDEV/Informatics/Cycle/while/b.py | 55 | 3.578125 | 4 | a = int(input())
i = 2
while a%i!=0:
i=i+1
print(i) |
d635853788e48b21f636edba4327923fac5a1863 | Qazaqbala-N/last | /lab7/WEBDEV/Informatics/Cycle/for/c.py | 130 | 3.75 | 4 | import math
a = int(input())
b = int(input())
print(" ".join([str(i) for i in range(a,b+1) if math.sqrt(i)==int(math.sqrt(i))] ))
|
8fa63d49d396110d5d6d87f55fd1c29a9bf5eb64 | ali-a10/Sudoku-Solver | /Solver.py | 630 | 3.78125 | 4 |
from typing import runtime_checkable
def valid_move(board, number, position):
# check column
for row in range(len(board)):
if board[row][position[1]] == number and position[0] != row:
return False
# check row
for col in range(len(board)):
if board[position[0]][col... |
d2e63bfba6fdfa348260d81a84628cacc6243a18 | Yasthir01/Bootcamp-Tasks-and-Projects-Part1 | /Level 1/Task 7/investment_calculator.py | 986 | 4.125 | 4 | """A program on an Investment Calculator"""
import math
# user inputs
# the amount they are depositing
P = int(input("How much are you depositing? : "))
# the interest rate
i = int(input("What is the interest rate? : "))
# the number of years of the investment
t = int(input("Enter the number of years of the investm... |
720fefd121f1bc900454dcbfd668b12f0ad9f551 | Yasthir01/Bootcamp-Tasks-and-Projects-Part1 | /Level 1/Task 2/conversion.py | 445 | 4.25 | 4 | """Declaring and printing out variables of different data types"""
# declare variables
num1 = 99.23
num2 = 23
num3 = 150
string1 = "100"
# convert the variables
num1 = int(num1) # convert into an integer
num2 = float(num2) # convert into a float
num3 = str(num3) # convert into a string
string1 = int(string1) # c... |
1143957f959a603f694c7ed6012acf2f7d465a4c | Yasthir01/Bootcamp-Tasks-and-Projects-Part1 | /Level 1/Task 7/control.py | 258 | 4.125 | 4 | """Program that evaluates a person's age"""
# take in user's age
age = int(input("Please enter in your age: "))
# evaluate the input
if age >= 18:
print("You are old enough!")
elif age >= 16:
print("Almost there")
else:
print("You're just too young!") |
cf657243453a2c909570465f0e4e30072dac3eff | Yasthir01/Bootcamp-Tasks-and-Projects-Part1 | /Level 1/Task 3/example.py | 9,396 | 4 | 4 |
# ========= What are Strings? ===========
# A string is a common data type which is used to represent text.
# It is a sequence of characters, such as, letters, numerals, symbols and special characters.
# In Python, strings must be written within “quotation marks” in order for the computer to be able to read it.
# The ... |
aa41b93ab44deded12fa4705ea497d2c6bbc74e8 | Yasthir01/Bootcamp-Tasks-and-Projects-Part1 | /Level 1/Task 10/logic.py | 648 | 4.1875 | 4 | """A program about fast food service"""
menu_items = ['Fries', 'Beef Burger', 'Chicken Burger', 'Nachos', 'Tortilla', 'Milkshake']
print("***MENU***")
print("Pick an item")
print("1.Fries\n2.Beef Burger\n3.Chicken Burger\n4.Nachos\n5.Tortilla\n6.Milkshake")
choice = int(input("\nType in number: "))
for i in menu_i... |
ac6d9333960c992aef690fa764d7f98ffdc9963c | Yasthir01/Bootcamp-Tasks-and-Projects-Part1 | /Level 1/Task 17/animal.py | 815 | 4.1875 | 4 | """Inheritance in Python"""
class Animal(object):
def __init__(self, numteeth,spots,weight):
self.numteeth = numteeth
self.spots = spots
self.weight = weight
class Lion(Animal):
def __init__(self, numteeth, spots, weight):
super().__init__(numteeth, spots, weight)
self.type()
def type(self):
"""D... |
8be702fc476fbcca1b173f18a46f5fc02e3607ce | evilowl/learnpython | /qiuhe.py | 1,003 | 3.5625 | 4 | def calc(*numbers):
sum = 0
for n in numbers:
sum = sum + n * n
return sum
def person(name, age, **kw):
print 'name', name, 'age', 'other',kw
def func(a, b, c=0, *args, **kw):
print 'a=', a, 'b=',b, 'c=', c, 'args=', args, 'kw=', kw
def fact(n):
if n == 1:
... |
5a4ae83572e2cad5a3021d95d8a88ea5dcea1da4 | smblasik/Python_Excercises | /intro/celcius.py | 298 | 3.78125 | 4 | # Function to Convert Celcius to Farenheit
def fer(cel):
if cel > -273.15:
answer = cel * 1.8 + 32
return answer
temperatures=[10,-20,-289,100]
for c in temperatures:
with open("temp.txt","a+") as file:
if c > -273.15:
file.write(str(fer(c)) + "\n")
|
7eafe6d1231ff66b56fdeab6c409922e82ec5691 | purvajakumar/python_prog | /pos.py | 268 | 4.125 | 4 | #check whether the nmuber is postive or not
n=int(input("Enter the value of n"))
if(n<0):
print("negative number")
elif(n>0):
print("positive number")
else:
print("The number is zero")
#output
"""Enter the value of n
6
positive number"""
|
cb79a2766eac1ec30b3e443a469dbcd14bdc8358 | dashboardijo/py_ln | /com/py/finanindic/compute_psi.py | 4,934 | 3.5 | 4 | # Python代码实现PSI群体稳定指数
import pandas as pd
import numpy as np
from matplotlib import pyplot as plt
import math
def cal_psi(actual, predict, bins=10):
"""
功能: 计算PSI值,并输出实际和预期占比分布曲线
:param actual: Array或series,代表真实数据,如训练集模型得分
:param predict: Array或series,代表预期数据,如测试集模型得分
:param bins: 分段数
:return:
... |
bc52c54d5824c404709f3252210e77c0d1da393e | AdamSpannbauer/minimal_python_package | /my_pkg/perimeter.py | 371 | 4.03125 | 4 | def rect_perimeter(w, h):
"""Calc perimeter of a rectangle
:param w: width of rectangle
:param h: height of rectangle
:return: perimeter of rectangle
"""
return w * 2 + h * 2
def square_perimeter(a):
"""Calc perimeter of a square
:param a: length of square legs
:return: perimeter... |
2bc98f3ff734b47d6cc64effebe893718221ebb0 | Bart94/Project1 | /ExternalMethods.py | 1,871 | 3.53125 | 4 | from CircularPositionalList import CircularPositionalList
def bubblesorted(cplist):
temp = cplist.copy()
if not cplist.is_sorted():
current_node = temp._header._next
for i in range(len(temp) - 1):
next_node = current_node._next
for j in range(i, len(temp) - 1):
... |
85035bf134a0430c29da49fea24440c04f307faf | yuta-nakashima-10antz/behavior_tree | /main.py | 3,616 | 3.703125 | 4 | import random
my_hp = 150
enemy_hp = 120
#整数か判断
def is_integer(n):
try:
float(n)
except ValueError:
return False
else:
return float(n).is_integer()
#ルート
class Root(object):
sequence = []
node_count = 0
def __init__(self,my_hp,enemy_hp):
self.my_hp = my_hp
... |
168cf6562d8ebe5fa96d605ce088d29dd2be0a25 | LucianLaFleur/pythonPath | /security_scripts/dictBruteForce.py | 685 | 3.65625 | 4 | #!/use/bin/env python
import requests
target_url = "example.com"
# last item in dictionary is the button for submitting
data_dict = {"username": "potato1", "password":"", "Login":"submit"}
with open("path/to/dictionary.txt", "r") as wordlist_file:
for line in wordlist_file:
# assuming each keyword is on its own... |
d91936546e575c5b3daa3c20061d2541d379dc3b | AMJefford/Simulation-and-Chemistry-System | /Student File.py | 25,676 | 3.5625 | 4 | from tkinter import *
import tkinter.messagebox as tm
import sqlite3
import array
import string
import DatabaseKey
from cryptography.fernet import Fernet
from Simulation import *
import random
import time
class Login:
def __init__(self, root):
self.__UsernameE = Entry(root)
... |
1253e8d2eeda3c4f0f71b7457c9a77239fceeed9 | yamyak/plutus-stock-analysis | /Algorithms/Algorithm.py | 875 | 3.90625 | 4 | # algorithm base class
class Algorithm:
# initialize the weights and needs to nothing
def __init__(self, needs):
self.__weights = 0
self.__needed_values = needs
# verify that provided stock has all the entries the current algorithm needs
def verify_needs(self, stock):
# get all ... |
2b4534fe8edd038ffae69c1512b225305b00a46b | ky822/assignment7 | /hz990/Q4.py | 552 | 3.875 | 4 | import numpy as np
import matplotlib.pyplot as plt
def Run():
'''This function returns the Mandelbrot fractal image
'''
# Setting initial parameters
N_max = 50
some_threshold = 50.
x = np.linspace(-2, 1, 1000)
y = np.linspace(-1.5, 1.5, 1000)
# Constructing the grid
c = x[:,np.newaxis] + 1j*y[np.newaxis,:]
... |
f69927d9d6d8546f676889c04db0f0c467758fd2 | ky822/assignment7 | /yx887/question4.py | 761 | 3.84375 | 4 | import numpy as np
import matplotlib.pyplot as plt
def run_program():
print '-------- Begin Question 4 --------'
# Creat a grid of x, y
print 'Creating meshgrid ...'
nx, ny = 300, 300
x = np.linspace(-2, 1, nx)
y = np.linspace(-1.5, 1.5, ny)
xv, yv = np.meshgrid(x, y)
c = xv + 1j * yv... |
0fc620866a5180d3a6d0d51547d74896a6d3c193 | ky822/assignment7 | /yl3068/questions/question3.py | 734 | 4.3125 | 4 | import numpy as np
def result():
print '\nQuestion Three:\n'
#Generate 10*3 array of random numbers in the range [0,1].
initial = np.random.rand(10,3)
print 'The initial random array is:\n{}\n'.format(initial)
#Question a: pick the number closest to 0.5 for each row
initial_a = abs(initial-0... |
1f501409ef108fa83f7fb3b1522cb31d44cfb75c | ky822/assignment7 | /wl1162/question_sets/question3.py | 306 | 3.71875 | 4 | import numpy as np
def question3():
array=np.random.rand(10,3)
difference=abs(array-0.5) # find the differences with 0.5
rank=np.argsort(difference) # find the column index of the smallest elements
result=array[np.arange(10), [rank.T[0]]] # fancy index
print result
|
34bdf85e0820099703a3ed9a45aa010638f9f2ae | ky822/assignment7 | /fs1214/answers/Question2.py | 576 | 3.8125 | 4 | '''
Created on Oct 30, 2014
@author: ds-ga-1007
'''
import numpy as np
def main():
print '-----Question2-----'
#create array a and b.
a = np.arange(25).reshape(5,5)
b = np.array([1.,5,10,15,20])
print 'The dividend array - a is:'
print a
print 'The divisor array - b is:'
print b
... |
2942e089197e0524fa7ebe26d2ca7f9763efc8fe | ky822/assignment7 | /yl3068/questions/question1.py | 1,123 | 3.953125 | 4 | import numpy as np
def result():
print '\nQuestion One:\n'
#Generate the initial array
initial = np.arange(1,16,1).reshape((3,5)).transpose()
print 'The initial array is :\n{}\n'.format(initial)
#Question a: generate a new array that contains the 2nd and 4th rows
initial_a = initial[(1,3), :]... |
ddb6449e2fa4edd65569aa5cde8c3efa0f671c8d | ky822/assignment7 | /ql516/question4.py | 1,632 | 3.9375 | 4 | # -*- coding: utf-8 -*-
import numpy as np
def construct_a_grid():
"""
construct a grid of c = x + 1j*y values in range [-2,1] x [-1.5,1.5]
Return
======
an m x n numpy array
"""
grid_number = 100
x = np.linspace(-2,1,grid_number)
y = np.linspace(-1.5,1.5,grid_number)
... |
39e36aeb85538a4be57dd457d005fd12bc642e25 | ky822/assignment7 | /ql516/question3.py | 1,927 | 4.1875 | 4 | # -*- coding: utf-8 -*-
import numpy as np
def array_generate():
"""
generate a 10x3 array of random numbers in range[0,1]
"""
array = np.random.rand(10,3)
return array
def GetClosestNumber(array):
"""
for each row, pick the number closest to .5
"""
min_index = np.argmin(np.ab... |
32d88c9bf149a9f95d4b9dc97f28ebb06291a881 | ky822/assignment7 | /xz1082/question3.py | 989 | 4.09375 | 4 | import numpy as np
def answers():
print '\n------------this is question 3---------------'
array = np.random.rand(10, 3)
print 'The initial array is:\n{}\n'.format(array)
#3a
#find the minimum number in each row after subtracting 0.5 from each element in the matrix
array_close_to_half = abs... |
7d82924a9a4123d5a340cbbd352ddea2bd4b3e18 | ky822/assignment7 | /wl1207/question1.py | 694 | 4.125 | 4 | import numpy as np
def function():
print "This is the answer to question1 is:\n"
array = np.array(range(1,16)).reshape(3,5).transpose()
print "The 2-D array is:\n",array,"\n"
array_a = array[[1,3]]
print "The new array contains the 2nd column and 4th rows is:\n", array_a, "\n"
array_b = array[:, 1]
prin... |
5bf6e766d1df7624410a3b1fc243cfb1bc3b096b | ky822/assignment7 | /mj1547/Question2.py | 464 | 3.984375 | 4 | '''
@author: jiminzi
'''
from numpy import *
def Question2():
# create the array from 0 to 24 and 5*5
a = arange(25).reshape(5,5)
b = array([1., 5, 10, 15, 20])
#re shape the b array to a column
b = b.reshape(5,1)
#divide each column by b.reshape
result2 = divide(a,b)
print 'question 2... |
81f5a75d870f8e67f5694b03307f80a98a879c0d | f287772359/pythonProject | /practice_9.py | 2,983 | 4.125 | 4 | from math import sqrt
# 动态
# 在类中定义的方法都是对象方法(都是发送给对象的消息)
# 属性名以单下划线开头
class Person(object):
def __init__(self, name, age):
self._name = name
self._age = age
# 访问器 - getter方法
@property
def name(self):
return self._name
# 访问器 - getter方法
@property
def age(self):
... |
a8cac862a46c4305f8fdffe159af73950c612ed7 | zhuangzhuangsun/pgnlm | /pgnlm/helperfuncs.py | 5,837 | 3.609375 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
@author: jorag
"""
import numpy as np
def length(x):
"""Returns length of input.
Mimics MATLAB's length function.
"""
if isinstance(x, (int, float, complex, np.int64)):
return 1
elif isinstance(x, np.ndarray):
return max(x.sh... |
07f3932421101e7c415565e2a124dc2eaf9e3975 | KonstantinSKY/LeetCode | /922_Sort_Array_By_Parity_II.py | 981 | 3.515625 | 4 | """922. Sort Array By Parity II https://leetcode.com/problems/sort-array-by-parity-ii/ """
import time
from typing import List
class Solution:
def sortArrayByParityII2(self, A: List[int]) -> List[int]:
even = []
odd = []
res = []
for i in A:
if i % 2 == 0:
... |
8991eacf77fc4888ecd774733c4bbeed147bee45 | KonstantinSKY/LeetCode | /961_N-Repeated_Element_in_Size_2N_Array.py | 658 | 3.65625 | 4 | """ 961 https://leetcode.com/problems/n-repeated-element-in-size-2n-array/"""
import time
from typing import List
class Solution:
def repeatedNTimes2(self, A: List[int]) -> int:
for num in A:
if A.count(num) == len(A) / 2:
return num
def repeatedNTimes(self, A: List[int])... |
0c7e4a4bbb9de2a3f8ac1df103eb1405b8206a7d | KonstantinSKY/LeetCode | /811_Subdomain_Visit_Count.py | 1,421 | 3.515625 | 4 | """811. Subdomain Visit Count https://leetcode.com/problems/subdomain-visit-count/ """
import time
from typing import List
class Solution:
def subdomainVisits2(self, cpdomains: List[str]) -> List[str]:
domains = {}
for cp in cpdomains:
cp_list = cp.split()
domain_list = cp... |
17d1add048a7e5db1e09574e9d1fe27e3d3112e2 | KonstantinSKY/LeetCode | /running_sum_array.py | 513 | 3.609375 | 4 | """ """
import time
from typing import List
class Solution:
def runningSum(self, nums: List[int]) -> List[int]:
for i in range(1, len(nums)):
nums[i] += nums[i-1]
return nums
if __name__ == "__main__":
start_time = time.time()
print(Solution().runningSum([1, 2, 3, 4]))
pri... |
5de53095fb6440e8b67413a449cc8dd5409ffdde | KonstantinSKY/LeetCode | /905_Sort_Array_By_Parity.py | 785 | 3.609375 | 4 | """ 905 https://leetcode.com/problems/sort-array-by-parity/ """
import time
from typing import List
class Solution:
def sortArrayByParity2(self, A: List[int]) -> List[int]:
res = []
for num in A:
if num % 2 == 0:
res.insert(0, num)
else:
res... |
51d7876779936ede418062de2ea567a439f0df4e | KonstantinSKY/LeetCode | /1417_Reformat_The_String.py | 688 | 3.65625 | 4 | """1417. Reformat The String https://leetcode.com/problems/reformat-the-string/ """
import time
from typing import List
class Solution:
def reformat(self, s: str) -> str:
chars1 = list(filter(str.isalpha, s))
chars2 = list(filter(str.isdigit, s))
if abs(len(chars1) - len(chars2)) > 1:
... |
cf4f98186af476549d3287c95428522e712123a2 | KonstantinSKY/LeetCode | /977_Squares_of_a_Sorted_Array.py | 551 | 3.734375 | 4 | """977 Squares of a Sorted Array https://leetcode.com/problems/squares-of-a-sorted-array/"""
import time
from typing import List
class Solution:
def sortedSquares1(self, nums: List[int]) -> List[int]:
return sorted([num ** 2 for num in nums])
def sortedSquares(self, nums: List[int]) -> List[int]:
... |
6eabac430bffdd2f7480e9f91fe1076da46745db | TakashiNomura/tempy | /test2.py | 472 | 3.640625 | 4 | # coding: UTF-8
import sys
# フィボナッチ数を返す
def fibonacci(n):
a1, a2 = 1, 0
while n > 0:
a1, a2 = a1 + a2, a1
n -= 1
return a1
lines = sys.stdin.readlines()
for i, line in enumerate(lines):
line = line.strip("\n")
if line.isdigit() == True:
floor = int(line)
... |
d9c561375dadb8c61638d849295d6f6dc454f031 | rodforrb/cobsched | /sched.py | 8,353 | 3.6875 | 4 | '''
Scheduling algorithm implementation
Ben Rodford
'''
import collections
import csv
from dataclasses import dataclass
from collections import defaultdict
from random import shuffle
# https://en.wikipedia.org/wiki/Ford%E2%80%93Fulkerson_algorithm
# This class represents a directed graph using adjacency matrix rep... |
1757639b83d3a01f0586d78340f1e759d0213b14 | vdedejski/course-AI | /code.finki tasks/Lab01-2020/gradebook.py | 819 | 3.515625 | 4 | from math import ceil
def sumPoints(points):
li = [int(i) for i in points]
grade = ceil(sum(li)/10)
if grade >= 6: return grade
else: return 5
if __name__ == '__main__':
dictionary = {}
while True:
s = input()
if s == 'end': break
listInformation = s.split(",")
... |
16cc78a20222a11c562fb235a71d7d1f1f46c347 | yanzn0415/myedu | /day04/obiect_demo.py | 608 | 3.625 | 4 | class yan(object):
def __init__(self,name,age,sex):
self.name=name
self.age=age
self.sex=sex
def tiaochuan(self):
print('%s在跳船'%self.name)
def shuijiao(self):
print('%s在睡觉'%self.name)
class nan(yan):
def gongzuo(self):
self.tiaochuan
print('%s在修船'... |
deb9eb639725ca8cf4abf150161ec37108db96b6 | HaugenBits/CompProg | /ProgrammingChallenges/Chapter_1/CheckTheCheck/ChecktheCheck.py | 4,658 | 3.546875 | 4 | import sys
class ChessBoard:
def __init__(self, cBoard, num):
self.cBoard = cBoard
self.num = num
self.kinginCheck = "no"
self.kingOnBoard = False
def checkForCheck(self):
for y, line in enumerate(self.cBoard):
for x, ele in enumerate(line.strip()):
... |
54354c8ecf440c6da31add2fb1464a295193f6db | amenzl/programming-challenge | /DAG.py | 640 | 3.953125 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat Aug 24 07:38:37 2019
@author: anna
"""
import networkx as nx
#networkx creates graphs, functions include Graph(), add_nodes, add_edges
G=nx.Graph()
class DAG(nodes, edges):
def __init__(self):
self.nx.Graph()
def add_node(nodes):... |
441782770872fb7fd4b5d74caf8efe783bafbc76 | lion7500000/python-selenium-automation | /Python program/1111111.py | 222 | 3.5625 | 4 | def likes(names):
for name in names:
i = [name]
print (i)
if len[i] >= 4:
print (f'{i[0]},{i[1]} and 2 others like this')
names =["Ivan","Petr","Slava","Nik"]
print (likes(names)) |
f9ef83fec9801fce7dbaa3ff233147568fa3e17e | slawiko/machine-learning-examples | /Week_1/Lesson_2_Signs_Importance/importance.py | 654 | 3.5 | 4 | import numpy
import pandas
from sklearn.tree import DecisionTreeClassifier
default_data = pandas.read_csv('../titanic.csv', index_col='PassengerId')
data = pandas.DataFrame(data=default_data, columns=['Survived', 'Pclass', 'Fare', 'Age', 'Sex'])
data = data.dropna()
data = data.replace(to_replace='male', value=1)
dat... |
7c04c0d710d45acf96f6c7f87ec27dcf4a316112 | twsswt/pydysofu | /pydysofu/find_lambda.py | 1,535 | 3.59375 | 4 | """
Utility routines for extracting lambda expressions from source files.
@twsswt
"""
import ast
def find_candidate_object(offset, source_line):
start = source_line.index('lambda', offset)-1
end = start + 7
while end <= len(source_line):
try:
candidate_source = source_line[start:end]... |
07de99725f8f7c3efe6099dc1502106fe24b6b53 | Luffky/INFOX | /app/analyse/util/localfile_tool.py | 2,266 | 3.703125 | 4 | import os
import json
def write_to_file(file, obj):
""" Write the obj as json to file.
It will overwrite the file if it exist
It will create the folder if it doesn't exist.
Args:
file: the file's path, like : ./tmp/INFOX/repo_info.json
obj: the instance to be written into file (can be l... |
af2936763343333885ceb68b18f675591da9885e | yvanwangl/pythonLesson | /itertoolsFuncs/countFunc.py | 554 | 3.859375 | 4 | import itertools
# for it in itertools.count(1):
# print(it)
# for it in itertools.cycle('abc'):
# print(it)
# for it in itertools.repeat('b'):
# print(it)
# for it in itertools.repeat('b', 3):
# print(it)
# for it in itertools.takewhile(lambda x: x <= 10, itertools.count(1)):
# print(it)
# fo... |
893e14ac378b0716ae960815d2e35d935c4b3726 | adriano2004/Dobro_Triplo_Raiz | /dtr.py | 179 | 4 | 4 | n = float(input('Digite um número: '))
dobro = n*2
triplo = n*3
raiz = n** (1/2)
print(' O dobro é {} \n O triplo é {} \n A raiz quadrada é {:.2f}'.format(dobro,triplo,raiz)) |
8ce335b82eb993c91cfeb10aff2a127fe45c246f | huangm96/Intro-Python-II | /src/player.py | 1,457 | 3.703125 | 4 | # Write a class to hold player information, e.g. what room they are in
# currently.
class Player:
def __init__(self, name, room):
self.name = name
self.room = room
self.backpack = []
def travel(self, direction_cmd):
new_room = self.room.get_room_in_direction(direction_cmd)
... |
cf4f2389d5b947b91a22e50f75820bc7ded815f9 | Kamilet/learning-coding | /simple-program/check-io-solutions/remove-accents.py | 873 | 3.53125 | 4 | ACIENTS = {'ā': 'a', 'á': 'a', 'ǎ': 'a', 'à': 'a', 'ă': 'a',
'ō': 'o', 'ó': 'o', 'ǒ': 'o', 'ò': 'o', 'ớ': 'o',
'ê': 'e', 'ē': 'e', 'é': 'e', 'ě': 'e', 'è': 'e',
'ī': 'i', 'í': 'i', 'ǐ': 'i', 'ì': 'i',
'ū': 'u', 'ú': 'u', 'ǔ': 'u', 'ù': 'u',
'ǖ': 'u', 'ǘ': 'u', 'ǚ'... |
6779c9a4de1ac252d6c913d5de26aff3cbc64153 | Kamilet/learning-coding | /python/ds_reference.py | 534 | 4.25 | 4 | print('Simple Assignment')
shoplist = ['apple', 'mango', 'carrot', 'banana']
# mylist只是指向同一对象的另一名称
mylist = shoplist
# 购买了apple删除
del shoplist[0] #和在mylist中删除效果一样
print('shoplist is', shoplist)
print('my list is', mylist)
#注意打印结果
#二者指向同一对象,则会一致
print('Copy by making a full slice')
mylist = shoplist[:] #复制完整切片
#删除第一个... |
42b4268cba541335b2c70c9b78ceffc486ee429f | Kamilet/learning-coding | /simple-program/check-io-solutions/x-o-referee.py | 1,118 | 3.609375 | 4 | def checkme(ox, game_result):
if ox in game_result:
return True
for i in [0, 1, 2]:
if ox == game_result[0][i]+game_result[1][i]+game_result[2][i]:
return True
if ox == game_result[0][0]+game_result[1][1]+game_result[2][2]:
return True
if ox == game_result[0][2]+game_... |
98cf14d0264de7daa98d239358b3778c549d9e85 | Kamilet/learning-coding | /simple-program/check-io-solutions/reverse_roman.py | 996 | 3.765625 | 4 | '''罗马数字转阿拉伯数字'''
'''
Numeral Value
I 1 (unus)
V 5 (quinque)
X 10 (decem)
L 50 (quinquaginta)
C 100 (centum)
D 500 (quingenti)
M 1,000 (mille)
'''
roman_dict = {'I':1,'V':5,'X':10,'L':50,'C':100,'D':500,'M':1000}
def reverse_roman(roman_string):
number = 0
for i in range(0, len(roman_string)-1)... |
f055c541cf8f0622ac8323b7ac1cde14c1c21b40 | Kamilet/learning-coding | /simple-program/check-io-solutions/bird-language.py | 564 | 3.515625 | 4 | '''
辅音字母后随机加一个元音字母
元音字母重复2次
元音字母aeiouy
反向翻译
'''
def translate(song):
s = 0
word = []
while s != len(song):
word.append(song[s])
if song[s] in 'aeiouyAEIOUY':
s += 3
elif song[s] in ' ?!.':
s += 1
else:
s += 2
return ''.join(word)
tran... |
69ae3110fd5d49957b309a88ebe6229e0c12d493 | Kamilet/learning-coding | /simple-program/check-io-solutions/triangular-number.py | 239 | 3.59375 | 4 | '''
生成三角数
'''
def gen_triangular_number(limit):
numbers = [0]
height = 1
while numbers[-1] <= limit:
numbers.append(numbers[-1]+height)
height+=1
return numbers
print(gen_triangular_number(1000)) |
ae63f36897ced379ec1f7b20bc399182c36682c5 | Kamilet/learning-coding | /python/ds_str_methods.py | 305 | 4.1875 | 4 | #这是一个字符串对象
name = 'Kamilet'
if name.startswith('Kam'):
print('Yes, the string starts with "Kam"')
if 'a' in name:
print('Yes, contains "a"')
if name.find('mil') != -1:
print('Yes, contains "mil"')
delimiter='_*_'
mylist = ['aaa', 'bbb', 'ccc', 'ddd']
print(delimiter.join(mylist)) |
543bae19127af09272b507ba5ad37f2130c8191d | Kamilet/learning-coding | /simple-program/check-io-solutions/skew-symmetric-matrix.py | 3,752 | 4.0625 | 4 | '''
求一个矩阵是否和共轭矩阵+负号相等
'''
# in using sMartix
# https://github.com/Kamilet/Simple-Matrix-python
# From --------------------------------------
def sm_trans(matrix):
'''Transpose'''
_row, _colume = sm_check(matrix)
new_matrix = sm_gen(_colume,_row)
for _r in range(_row):
for _c in range(_colume):... |
aaff8a9ee177b70e7a554239ab6a848a23fc1489 | Kamilet/learning-coding | /simple-program/check-io-solutions/achilles-tortoise.py | 728 | 3.5 | 4 | '''
追击问题
输入checkio(v_fast,v_slow,advantage)
v_fast和v_slow代表两人速度
advantage代表慢的人领先的时间
求追击时间
'''
def chase(v_fast, v_slow ,advantage):
chase_time = advantage * v_fast / (v_fast - v_slow)
# print(round(chase_time,8))
return round(chase_time,8)
if __name__ == '__main__':
#These "asserts" using only for se... |
00623edf113252c423ac60fbc70ac528d77c9146 | hzhou/parser | /python_0/calc.py | 2,277 | 3.875 | 4 | import re
def main():
print(calc("1+2*-3"))
def calc(src):
src_len=len(src)
src_pos=0
precedence = {'eof':0, '+':1, '-':1, '*':2, '/':2, 'unary': 99}
re1 = re.compile(r"\s+")
re2 = re.compile(r"[\d\.]+")
re3 = re.compile(r"[-+*/]")
stack=[]
while 1:
while 1: # $do
... |
5db7ec314516082fd84e7feb746374f4aae24fb1 | ranaputta/Timeseries-Notebook | /Concrete Strength.py | 1,745 | 3.875 | 4 | #!/usr/bin/env python
# coding: utf-8
# In[1]:
import pandas as pd
import matplotlib as plt
import seaborn as sns
get_ipython().run_line_magic('matplotlib', 'inline')
# 1. Load the CSV data into a pandas data frame. Print some high-level statistical info about the data frame's columns.
# In[7]:
df=pd.read_csv(... |
ed2333967457b6aa9431fbd57355fd98a326107e | lishuoluke/lintcode_practice | /lintcode_Search a 2D Matrix.py | 574 | 3.828125 | 4 | class Solution:
"""
@param: matrix: matrix, a list of lists of integers
@param: target: An integer
@return: a boolean, indicate whether matrix contains target
"""
def searchMatrix(self, matrix, target):
# write your code here
if (matrix == []):
return False
n... |
7e4ac8f93572c5b82948cd755b6ab5c1c6cab94c | lishuoluke/lintcode_practice | /lintcode_longestwords.py | 436 | 3.609375 | 4 | class Solution:
"""
@param: dictionary: an array of strings
@return: an arraylist of strings
"""
def longestWords(self, dictionary):
# write your code here
max = -1
list = []
for item in dictionary:
if len(item) > max:
max = len(item)
... |
d8d779957f605b53341a6b40594394f7e750a4d9 | lishuoluke/lintcode_practice | /lintcode_Two Strings Are Anagrams.py | 355 | 3.671875 | 4 | class Solution:
"""
@param s: The first string
@param t: The second string
@return: true or false
"""
def anagram(self, s, t):
# write your code here
aaa = list(s)
bbb = list(t)
for item in aaa:
if (aaa.count(item) != bbb.count(item)):
... |
35e00bb8977bf34fccc17ae88babdd233bb0b2c3 | lishuoluke/lintcode_practice | /Min Stack.py | 604 | 3.734375 | 4 | class MinStack:
def __init__(self):
# do intialization if necessary
self.stack1 = []
self.stack2 = []
def push(self, number):
# write your code here
self.stack1.append(number)
if len(self.stack2) == 0 or number <= self.stack2[-1]:
self.stack2.append(... |
c7b0231d769f6a301883b1ab2020a6f1142f033c | QiyuZ/Voronoi_Pic-App | /Voronoi_realization.py | 7,919 | 3.53125 | 4 | import math
from data_structure import Point, Seg, Arc, Event, PriorityQueue
class Voronoi:
def __init__(self, points):
self.output = [] # Result, a list of segment
self.arc = None # parabola arcs
self.event = PriorityQueue() # circle events, old arc disappears
self.points = Prio... |
3f84337e2e1de9db7e2e79b73e5548d6a93084ce | deepdsavani/MachineLearning | /Machine Learning with Data Mining + Data Analysis and Visulization/Assignments solutions of ML for Data mining/cnn tensorflow.py | 4,086 | 3.5 | 4 | import tensorflow as tf
import numpy as np
#from tensorflow.examples.tutorials.mnist import input_data
#mnist = input_data.read_data_sets("data", one_hot=True)
#images_test = mnist.test.images
(x_train, y_train), (x_test, y_test) = tf.keras.datasets.cifar10.load_data()
print("x_train shape:", x_train.shape, "y_tra... |
bf8131f0a9c520a177487dc18a37689a2114cf11 | djole103/mangareader | /src/fun.py | 1,420 | 3.609375 | 4 | from collections import Counter
from random import randrange
import math
import re
def main():
str = "Shingeki No Kyojin"
print(str)
strlower = str.lower()
print(strlower)
finalstr = re.sub(pattern='\ ',repl='-',string=strlower)
print(finalstr)
spli = re.sub(pattern='-',repl='... |
2605eb18b7237fe6a6d179741b4bbc55103ece08 | gurgenXD/chess | /src/knight.py | 1,355 | 3.6875 | 4 | from piece import Piece, COLORS, BLACK, WHITE
from empty import Empty
CONSOLE_IMAGE = {
BLACK: '\33[94m♞',
WHITE: '\33[93m♘'
}
class Knight(Piece):
""" Knight """
def make_move(self, piece_to):
if self.can_move(piece_to):
self.board.history.append('{0}({1}) --> {2}({3})'.format(... |
2ce8822c0cf6bef4548538f3dffb4ffa6faef59a | FrontEnd404/CIS1501-Fall2020 | /test of lab 7.py | 2,414 | 4.09375 | 4 | import math
def payment_amount(p, r, t):
r = r/(12*100)
t = t*12
payment_amount = (p*r*pow(1+r,t))/(pow(1+r,t)-1)
return payment_amount
def number_of_payments(rate, payment_amount, present_value ):
number_of_payments = (-math.log(1 - rate * present_value/ payment_amount))/ math.log(1 ... |
ecc9a79e0aa2a467f181dde137c589da0c27fd5f | CyrilHub/GA | /Additional Problems/Problem 1 - Linear Search/Problem 1 - Linear Search.py | 228 | 3.875 | 4 | object_list = ["Maria","Dana","David","Lauren","David"]
look_for = "Dana"
def finder(object,target):
for name in object_list:
index = objec
if name == target
print
finder(object_list,look_for)
|
6b5679a3806e7c8dedccd1b71c65fb1b409c3177 | puncoz/machine-learning-kss-yipl | /kss-1-linear-regression/lr-salaries-clean.py | 8,155 | 3.59375 | 4 | import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import seaborn as sns
def linear_equation(m, x, c):
return m * x + c
def plot(x, y, m, c):
plt.scatter(x, y)
plt.xlabel("Experience")
plt.ylabel("Salary")
plt.plot(x, linear_equation(m, x, c), label="fit for line y={0}x + {1}... |
bf74e88b39ea7f8803515285093c230b92e1d08e | pedrore1z/CodigosPythonTurmaDSI | /Exercicios1/Exercicio5.py | 183 | 3.90625 | 4 |
valor = int(input("Informe um valor inteiro qualquer:"))
'''
if valor %2 == 0:
print("É par")
else:
print("É ímpar")
'''
print("É par" if valor % 2==0 else "É ímpar") |
cc0a17edab86e5b6bc41b52df483d5ff7edccab4 | pedrore1z/CodigosPythonTurmaDSI | /Exercicios1/Exercicio1.py | 350 | 3.84375 | 4 | print("*"*10,"Atividade 01","*"*10)
medida = float(input("Informe a base do seu terreno: "))
medida2 = float(input("Informe a altura do seu terreno: "))
print("\n\nPara cada m² o valor da construção será de R$850\n\n")
area = medida * medida2
print("Sua area é: ", area)
metros = 850
print("Você deverá pagar o valor ... |
b80f5888649a78baff290dc4b654f8ee82b0230a | Austin-Deccentric/snbank | /main.py | 2,980 | 3.5625 | 4 | import itertools
from datetime import datetime
import time
from random import choices, seed
import string
from os import remove
import sys
def login():
condition = True
while condition != 'end' :
print("Please enter your login details")
username = input("Please enter username: ").strip()
... |
43636e7cfc6c066118a154979fb28893de350770 | dalboalvaro/PythonChallenge | /PyBank/main.py | 1,980 | 3.921875 | 4 | import os
import csv
Profit=[]
# Path to collect data from the Resources folder
budgetCSV = os.path.join('budget_data.csv')
# Read in the CSV file
with open(budgetCSV, newline='') as csvfile:
# CSV reader specifies delimiter and variable that holds contents
csvreader = csv.reader(csvfile, delimiter=',')
... |
237909d12a8b40d25190b39f114ea7e45f163d25 | Sauvikk/practice_questions | /Level6/Trees/Populate Next Right Pointers Tree.py | 1,700 | 4.0625 | 4 | # Given a binary tree
#
# struct TreeLinkNode {
# TreeLinkNode *left;
# TreeLinkNode *right;
# TreeLinkNode *next;
# }
# Populate each next pointer to point to its next right node.
# If there is no next right node, the next pointer should be set to NULL.
#
# Initially, all next pointers are se... |
f1eaa8be26c79ee21721f948864ef016a22a5852 | Sauvikk/practice_questions | /Level6/Trees/Next Greater Number BST.py | 1,708 | 3.890625 | 4 | # Given a BST node, return the node which has value just greater than the given node.
#
# Example:
#
# Given the tree
#
# 100
# / \
# 98 102
# / \
# 96 99
# \
# 97
# Given 97, you should return the node corresponding to 98 as tha... |
5b01a489805c58909979dae65c04763df722bfaa | Sauvikk/practice_questions | /Level6/Trees/Balanced Binary Tree.py | 1,233 | 4.34375 | 4 | # Given a binary tree, determine if it is height-balanced.
#
# Height-balanced binary tree : is defined as a binary tree in which
# the depth of the two subtrees of every node never differ by more than 1.
# Return 0 / 1 ( 0 for false, 1 for true ) for this problem
#
# Example :
#
# Input :
# 1
# / \
... |
97c6c72d6f1630885880672535719d4ae8205205 | Sauvikk/practice_questions | /Level6/Trees/Root to Leaf Paths With Sum.py | 1,466 | 3.78125 | 4 | # Given a binary tree and a sum, find all root-to-leaf paths where each path’s sum equals the given sum.
#
# For example:
# Given the below binary tree and sum = 22,
#
# 5
# / \
# 4 8
# / / \
# 11 13 4
# / \ / \
# 7 2 5 1
# ret... |
50580ee661fdbf765c1e825c7580fdace4c8d0ef | Sauvikk/practice_questions | /Level8/Word Search Board.py | 1,618 | 3.90625 | 4 | # Given a 2D board and a word, find if the word exists in the grid.
#
# The word can be constructed from letters of sequentially adjacent cell,
# where "adjacent" cells are those horizontally or vertically neighboring.
# The cell itself does not count as an adjacent cell.
# The same letter cell may be used more than on... |
9cea8f90b8556dcacec43dd9ae4a7b4500db2114 | Sauvikk/practice_questions | /Level6/Trees/Sorted Array To Balanced BST.py | 951 | 4.125 | 4 | # Given an array where elements are sorted in ascending order, convert it to a height balanced BST.
#
# Balanced tree : a height-balanced binary tree is defined as a
# binary tree in which the depth of the two subtrees of every node never differ by more than 1.
# Example :
#
#
# Given A : [1, 2, 3]
# A height balance... |
3e5acab0b12687cbf10ba1c9bcf9d3220507ef58 | Sauvikk/practice_questions | /Level7/Dynamic Programming/Min Sum Path in Matrix.py | 1,295 | 3.515625 | 4 | # Given a m x n grid filled with non-negative numbers, find a path
# from top left to bottom right which minimizes the sum of all numbers along its path.
#
# Note: You can only move either down or right at any point in time.
# Example :
#
# Input :
#
# [ 1 3 2
# 4 3 1
# 5 6 1
# ]
#
# Output : 8
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.