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 |
|---|---|---|---|---|---|---|
652b819dee3d37fa01f2e2168dfb03ddce7a4ab2 | rafasapiens/learning | /teste.py | 80 | 3.5625 | 4 | import math
nome=(input("Olá qual seu nome amigo?"))
print("Bem vindo", nome)
|
bccfae1a0c05881a1edad06dc6e836997f7b884d | SILVER-BASHINE/Deep_Learning_Homework | /homework1/neural_net.py | 5,911 | 4.21875 | 4 | from __future__ import print_function
import numpy as np
import matplotlib.pyplot as plt
class ThreeLayerNet(object):
"""
A three-layer fully-connected neural network. The net has an input dimension of
N, a hidden layer dimension of H, and performs classification over C classes.
We train the network with a soft... |
d83adc66c830e781f2746ba439915ed9b09f5385 | geshem14/my_study | /Coursera_2019/Python/week6/week6task6.py | 5,149 | 4.1875 | 4 | # week 6 task 6
# coursera https://www.coursera.org/learn/python
# -osnovy-programmirovaniya/programming/Hs8PB/grazhdanskaia-oborona
"""
текст задания тут 79 символ=>!
Штаб гражданской обороны Тридесятой области решил обновить план спасения на
случай ядерной атаки. Извест... |
e0a2a5880c99e823d98c573278ea5ab521b34542 | hunterluok/Security | /pythoncode/35_copylinknode.py | 1,020 | 3.796875 | 4 |
from pythoncode.listnode import ListNode
class CopyNode:
def __init__(self):
pass
def copy_node(self, node1, node2, index=1):
if node1 is None:
return node2
if node2 is None:
return node1
if index % 2 == 1:
mergerd = node1
merg... |
1486e1cad4880f4842828491e5705c84a53ee98b | mafm9/Problems | /String/frequency.py | 308 | 4 | 4 | inputstring = "Peter piper picked a peck of pickled peppers Peter"
words = inputstring.split()
frequency = [words.count(x) for x in words]
print(frequency)
combine = dict(list(zip(words,frequency)))
longest = max(words,key=len)
print(combine)
print(f"Longest words: {longest}")
print(f"length: {len(longest)}") |
f8cbf756f588ba191c27520050c11d25d40e8c69 | dapazjunior/ifpi-ads-algoritmos2020 | /Fabio_02/Fabio02_Parte_a/f2_a_q20_quadrantes.py | 705 | 4.125 | 4 | def main():
angulo = int(input('Digite um ângulo em graus: '))
quadrante = verificar_quadrante(angulo)
if angulo == 0 or angulo == 90 or angulo == 180 or angulo == 270:
print(f'O ângulo {angulo}° está no eixo de intercessão dos quadrantes.')
else:
print(f'O ângulo {angulo}° est... |
8fac0f9a3b7141b1cb3ba090e6cbce4e632cd16a | skyesyesyo/AllDojo | /python/OOP/Reading/inheritance.py | 1,370 | 4.53125 | 5 | # class Parent(object): # inherits from the object class
# parent methods and attributes here
# class Child(Parent): #inherits from Parent class so we define Parent as the first parameter
# parent methods and attributes are implicitly inherited
# child methods and attributes
############################
class Veh... |
d99071f9c45d3fbf4dd9a4919d2a3c8ac9e36228 | magmax/programming-challenge-2 | /finalists/Ignacio/challenge_11/t11.py | 3,508 | 3.71875 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# *** Challenge 11: Descrambler ***
import sys
score_table = { 'A': 1, 'E': 1, 'I': 1, 'L': 1, 'N': 1, 'O': 1, 'R': 1, 'S': 1, 'T': 1, 'U': 1,
'D': 2, 'G': 2,
'B': 3, 'C': 3, 'M': 3, 'P': 3,
'F': 4, 'H': 4, 'V': 4, 'W': 4, ... |
bd58f185e8fb9180db548b8865835a73a2f5627c | buxuele/ctf_notes | /snippet/pillow_watermark.py | 637 | 3.671875 | 4 | import sys
from PIL import ImageDraw, ImageFont, Image
"""
add water-mark to an image
"""
def watermark_text(filename,text, pos):
photo = Image.open(filename)
# make the image editable
drawing = ImageDraw.Draw(photo)
black = (3, 8, 12)
font = ImageFont.truetype("/usr/share/fonts... |
1c665ec0fb6c709794a415e3c7f212a728286643 | duchieu307/vuhoangduchieu-fundamentals-c4e13 | /Session04/Homework/exercise2.py | 398 | 3.796875 | 4 | princess = {
"banana": 4,
"apple": 2,
"orange": 1.5,
"pear": 3
}
stock = {
"banana": 6,
"apple": 0,
"orange": 32,
"pear": 15,
}
for keys, values in stock.items():
print(keys, values, sep = ': ')
print('price', princess[keys], sep = ': ')
total = 0
for keys, values in princess.ite... |
19de3be4600da288e42142355c7d5689c2943ed7 | Warwickc3295/CTI110 | /Test2.py | 243 | 3.75 | 4 | import turtle
turtle.speed(10)
turtle.color('hotpink')
turtle.bgcolor('red')
turtle.pensize(2)
size=1
while (True):
for x in range(4):
turtle.forward(size)
turtle.right(60)
size=size + 1
turtle.right(10)
|
6c6f67fb413892046eacf0992c2f1f77df636b61 | idesign0/Programming-Repo | /Python/10.STRINGS/strings.py | 234 | 3.6875 | 4 | ###strings
# 3 ways
x ='xyzeervqrv'
y ="xyevnvz"
z ="""xyzeveqrveq"""
print(len(x)*100)
print(len(y))
print(len(z))
print('max length of above strings')
print(max(len(x),len(y),len(z)))
print(len(x*100))
d=10
print(x + str(d))
|
5a86394ec78fb18a3886a0e080fdd15252e34f5c | javiergr3ybeard/Xtern-Coin | /xterncoin.py | 1,281 | 3.953125 | 4 | #! /usr/bin/python
import random
guessesTaken = 0
getCoins = 0
print('Hello what is your name?')
myName = input()
def main():
global guessesTaken
global getCoins
# Asks which command you want to run.
handleGuess = random.randint(1, 10)
word = input('To make a guess type "guess"\n To look at how many coin... |
769db2f78b91deeb0b56612b6c9862242453f5d1 | njenga5/python-problems-and-solutions | /Solutions/problem84.py | 200 | 4.15625 | 4 | '''
Question 84:
Please write a program to shuffle and print the list [3,6,7,8].
Hints:
Use shuffle() function to shuffle a list.
'''
from random import shuffle
s = [3, 6, 7, 8]
shuffle(s)
print(s)
|
4cfa656eef07676dff7b300af5f80322211df8af | christophertrmn/Plot | /daigram.py | 1,146 | 3.90625 | 4 | import math
import itertools
import matplotlib.pyplot as plt
try:
namalegend = []
mulai = int(input("How many trajectories?"))
for x in range(mulai):
namalegend.append("Ball {}".format(x + 1))
initialvelocity = input("Enter the initial velocity for trajectory {} (m/s) ".format(x + 1))
... |
ac3cd3c40a302a494c86148acc4ab107795676f6 | KareliaConsolidated/CodePython | /Basics/146_Python_Ex_07.py | 694 | 4.0625 | 4 | # SumUp Diagonals
# Write a function called sum_up_diagonals which accepts an N*N list of lists and sums the two main diagonals in the array; the one from the upper left to the lower right, and the one from the upper right to the lower left.
def sum_up_diagonals(arr):
total = 0
for i,val in enumerate(arr):
total +=... |
03b564a742f5ecddc2da51d14dfb5553d95d9c36 | z3ero/Leetcode | /剑指Offer/21_调整数组顺序使奇数位于偶数前面.py | 1,281 | 3.515625 | 4 | class Solution:
# 思路1: 冒泡排序的思路,前偶后奇交换,O(n**2)
# 思路2: 插入排序的思路
# 使用两个指针,a 指针指向下一个奇数要插入的位置,b指针用来遍历数组
# 每次找到一个奇数,则将[a,b] 统一向后移动一位,复杂度也是 O(n**2)
def reOrderArray_2(self, array):
p1 = 0
p2 = 0
length = len(array)
# 找到第一个偶数(即奇数要插入的位置)
while p1<length and ... |
39402041515911f37aa7d1955c52b3427c3f644e | stirfrypapi/coding_challenges | /trees_graphs/PrefixTree.py | 1,980 | 3.859375 | 4 | class Node:
def __init__(self, v=None):
self.val = v
self.next = None
self.isWord = False
self.child = None
class List:
def __init__(self):
self.list = [Node() for i in range(26)]
class Trie:
def __init__(self):
"""
Initialize your data structure ... |
585a20ec68d1a2e62c0a3964e787bc559bc9ae81 | baahmad/artificial_neural_networks | /lvq2_svm_networks/code/backprop.py | 4,801 | 3.578125 | 4 | from random import seed
from random import random
from random import randrange
from math import exp
from csv import reader
import csv
# Network initialization
def initialize_network(n_inputs, n_hidden, n_outputs):
network = list()
hidden_layer = [{'weights':[random() for i in range (n_inputs + 1)]} \
... |
ba653316efbffa924d1cdd3dc906243278bba027 | funny860/sosio_software | /problem-1.py | 1,532 | 3.75 | 4 | import re
def check_email(email):
parts = email.split("@")
if(len(parts) != 2):
return False
#check if prefix of string is correct
prefix = parts[0]
sufix = parts[1]
li = ['.','_','-']
#considering only 3 special characters to be acceptable in prefix
if(len(prefix) > 64 and len(p... |
04accca532e0813f5183340f0cd23b1d5b09d631 | Naveen-kumar01/data-structure-and-algorithms | /pro.py | 601 | 4.03125 | 4 | class Stack:
def __init__(self):
self.items = []
def is_empty(self):
return self.items == []
def push(self, data):
self.items.append(data)
def pop(self):
return self.items.pop()
def peek(self):
return self.items[-1]
def show(sel... |
39aafe89c7dec26bf248161d0d286f400253e5b9 | renedekluis/HBO-ICT_python_2B | /Week3/Opdracht2/main.py | 2,019 | 4 | 4 | class ListNode:
def __init__(self,data,next_node):
self.data = data
self.next = next_node
def __repr__(self):
return str(self.data)
class MyCircularLinkedList:
"""
This class creates a looping list of nodes.
"""
def __init__(self):
self.tail = None
def __repr__(self):
"""
... |
6677a61fb5ed34e74aa1b9271e47bdefb0f61d2b | Chenhuaqi6/python_base | /day06/10.10代码/index.py | 574 | 3.765625 | 4 | # s = input('请输入字符串')
# if s:
# print('第一个字符是',s[0])
# print('最后一个字符是',s[-1])
# if len(s) % 2 == 1:
# center = int(len(s) // 2)
# print('中间这个字符是:',s[center])
# else:
# print("您输入的字符串有误")
# 输入字符串 切掉第一个和最后一个
# s = input("请输入一个字符串: ")
# if s:
# print("切片后的字符串", s[1:(len(s)-1)] )
s = in... |
4575b319560b9dd954dca08faf0ca4b0b71e7c76 | Neptune-Haiwang/MachineLearning_Basics | /算法与数据结构/A2递归/递归应用-探索迷宫.py | 2,067 | 4.15625 | 4 | '''探索迷宫
把迷宫分成行列整齐的方格,区分出墙壁和通道。
即每个方格都有行列位置:矩阵,
采用不同字符来分别代表:墙壁,通道,海龟投放点
'''
class Maze:
def __init__(self, mazeFileName):
rowsInMaze = 0
columnsMaze = 0
self.mazeList = []
mazeFile = open(mazeFileName, 'r')
rowsInMaze = 0
for line in mazeFile:
rowList = ... |
e246d0d0c4895be911eb059c6aca170dcfeffe5d | pfsmyth/Cambridge | /code/if.py | 308 | 3.515625 | 4 | # if .. End If
a= 5
b= 4
print("a is", a, "b is",b)
if a > b :
print(a, "is bigger than ", b)
a= 3
b= 4
print("a is", a, "b is",b)
if a > b :
print(a , "is bigger than ", b)
a= 4
b= 4
print("a is", a, "b is",b)
if a == b :
print(a, "is equal to", b)
|
0a1d77ee20ec914f3eb35020211b39c5ad53308f | izzitan/CP1404_practical | /prac_04/list_exercises.py | 1,000 | 4.0625 | 4 | """
Name: Hafidz Izzi Baihaqi
GitHub: https://github.com/izzitan/CP1404_practical
"""
def main():
numbers = []
for i in range(5):
numbers.append(int(input("Number: ")))
print("The first number is {}".format(numbers[0]))
print("The last number is {}".format(numbers[-1]))
print("The smalle... |
caf8ecba9e06db1d38ce888893d5cc91b19d2cb0 | KamalAres/Infytq | /Infytq/Day7/Exer-35.py | 707 | 3.78125 | 4 | #PF-Exer-35
def count_names(name_list):
count1=0
count2=0
s=[]
#start writing your code here
#Populate the variables: count1 and count2
# Use the below given print statements to display the output
# Also, do not modify them for verification to work
#print("_at -> ",count1)
#print("... |
89c5c573833ee71243d3ef7387ab67f810fc23d6 | GeorgiyDemo/FA | /Course_I/Алгоритмы Python/Part1/семинары/pract5/task2.py | 1,898 | 3.90625 | 4 | """
Реализовать создание, запись, чтение и удаление файла с данными о пользователе.
пользователь выбирает действие самостоятельно, а так же указывает путь к размещению файла.
"""
import os
class FileProcessing:
def __init__(self):
select_d = {
"1": self.file_add,
"2": self.file... |
e9c5787e0942eaae24494cbf1217d82f45df6402 | itsolutionscorp/AutoStyle-Clustering | /all_data/exercism_data/python/word-count/9ac2cf4b99cb43baa80df9cbb9e59fa3.py | 192 | 3.953125 | 4 | def word_count(string):
frequencies = {}
for word in string.split():
if word in frequencies:
frequencies[word] += 1
else:
frequencies[word] = 1
return frequencies
|
17758714e5ecb76c1339ffa25573e0fecfc02d85 | cvkittler/Machine-Learning-Workspace | /Homework 6/homework6_cvkittler.py | 8,830 | 3.5625 | 4 | import numpy as np
import matplotlib.pyplot as plt
import scipy.optimize
NUM_INPUT = 784 # Number of input neurons
NUM_HIDDEN = 40 # Number of hidden neurons
NUM_OUTPUT = 10 # Number of output neurons
NUM_CHECK = 5 # Number of examples on which to check the gradient
# Given a vector w containing all the weights a... |
92ae3ed0edd201b4b383825e5e507ecfab503985 | queensland1990/HuyenNguyen-Fundamental-C4E17 | /SS03/hwcrud3.py | 221 | 3.703125 | 4 | list=["T-shirt","Sweater","Jeans"]
print("Welcome to our shop, what do you want ?")
print("update position: 2")
print("new item ? ",end="")
list[1]="Skirt"
print(list[1])
print("our items: ",end="")
print(*list,sep=", ")
|
72d47ac362edc255e9df31b269c25eaf7b39ef56 | jyates722/Cssi19 | /day7/mystory.py | 415 | 3.875 | 4 | story ="""Clap your hands together,
{0} together
Clap your {1} together,
clap, {2} clap
Clap clap this way,
clap clap that {3},
clap clap all the day,
{4}, clap, clap"""
noun1 = raw_input("Enter an Noun1:")
noun2 = raw_input("Enter an Noun2:")
noun3 = raw_input("Enter an Noun3:")
noun4 = raw_input("Enter an N... |
dde9c69797d2273e4796c542aa46ea280f672522 | Satyavrath/pythonBasics | /stringLength.py | 410 | 4.0625 | 4 | def string_length(name):
count = 0
for string in name:
count += 1
return count
print(string_length("Hello"))
def test_stringLength():
assert string_length("Hello") == 5
assert string_length("myName") == 6
print("The string works fine")
test_stringLength()
# last letter of str... |
f8c7257e82d466dee87ddaaefc0b12e3a0a466f9 | HaroldEnrique/web-service | /Test/Test.py | 1,855 | 3.640625 | 4 | import json
import re
import os
class Test:
def __init__(self):
try: # De https://stackoverflow.com/questions/2835559/parsing-values-from-a-json-file
if os.path.exists('db.json'):
path='db.json'
elif os.path.exists('/data/db.json'):
path='/data/db.j... |
4c18f9ca399dcf6eb9b222bcb945723630b306dd | ericschorling/digital_crafts_python | /python_1/n_to_m.py | 125 | 4 | 4 | n = int(input("give me a number to start at"))
m = int(input("give me a ending number"))
while n <= m:
print(n)
n+=1 |
623938d0d0b872cd839f1d6aacee23825f6e8819 | pedrofrancal/Python | /aprendendo/dicionarios/iterando.py | 615 | 3.515625 | 4 | dados = {'Crossfox': 72832.16, 'DS5': 124549.07, 'Fusca': 150000, 'Jetta Variant': 88078.64, 'Passat': 106161.95}
# o métodos keys() retorna todas as chaves, a gente vai utilizar ele para iterar
for key in dados.keys():
print(dados[key])
# existe metodo para voltar todos os valores tambem
print(dados.values())
... |
9bbed30a67e3930b1d42390b58d3c226e8fc684a | zekiahmetbayar/python-learning | /Bolum3_Problemler/mukemmel_sayi.py | 301 | 3.84375 | 4 | sayi = int(input("Merak ettiğiniz sayıyı giriniz : "))
toplam = 0
for i in range(1,sayi):
if (sayi%i == 0):
toplam += i
if(toplam ==sayi):
print(" {} sayısı mükemmel bir sayıdır. ".format(sayi))
else:
print(" {} sayısı mükemmel bir sayı değildir. ".format(sayi)) |
9ab8d5db255ec34cd97ffac259d76b85458bca6d | 2021dbakhmat/greeting | /greeting.py | 267 | 4.125 | 4 | name1 = "Diana"
name2 = "Marl owe"
name3 = "sister"
print(name1)
print(name2)
print("hello, " + name1)
print(len(name2))
print(name2 + " has " + str(len(name2)) + " characters in their name!")
age1 = "16"
print("My" (name3 + " is " + str(len(age1)) + " years old!" )
|
08b6d4380e88010e493c5a8454d7e53f11a4a654 | guydav/minerva | /formal/raquetball.py | 4,392 | 3.609375 | 4 | import random
import tabulate
from utils import *
SERVE_WIN_PROBABILITY = 0.6
OPPONENT_WIN_PROBABILITY = 0.5
PLAY_TO = 21
START_SERVE = True
NUM_TRIALS = 100000
def single_game(p_serve=SERVE_WIN_PROBABILITY, p_opponent=OPPONENT_WIN_PROBABILITY, play_to=PLAY_TO,
start_serve=START_SERVE):
my_score... |
28aa8f52e2c8a4fbd73bbf3946f677cc88e848a4 | zepetto7065/study_codingTest | /12주차/문제/지혜수_10870_피보나치수5.py | 187 | 3.828125 | 4 | def fibo(n):
a = 0
b = 1
c = 0
for _ in range(n-1):
c = a + b
a, b = b, c
return c
N = int(input())
if N == 0:
print(0)
elif N == 1:
print(1)
else:
print(fibo(N)) |
059a2de356024b80d7004c6f37a431417d26c27d | DaHuO/Supergraph | /codes/CodeJamCrawler/16_0_1_neat/16_0_1_Mauro_a.py | 369 | 3.5625 | 4 | def read_int():
return int(raw_input())
def solve(N):
if N == 0:
return "INSOMNIA"
seen = set()
n = 0
while True:
n += N
ans = n
seen.update(set(str(n)))
if len(seen) == 10:
return ans
for case in range(read_int()):
N = read_int()
ans = s... |
3ed138814ce0b262a3944cb6db1079af7ba100b8 | emersonsemidio/python | /Desafio.73.py | 349 | 3.921875 | 4 | Times = ('São Paulo ', 'Flamengo ', 'Atlético-Mg ', 'Palmeiras ', 'Grêmio ', 'Fluminense ')
print('-=' *20)
print('Os 5 primeiros são ',end = '')
for c in range(0,5):
print(Times[c],end='')
print('')
print('-=' *20)
print(f'Os 4 últimos são {Times[2:]}')
print('-=' *20)
print(f'O time que em 3° é o {Times[2]}... |
d82f726d464e9fc14261a9b059d6429eb89fd720 | kla0629/Backjoon | /2588.py | 515 | 3.734375 | 4 | """
(세 자리 수) × (세 자리 수)는 다음과 같은 과정을 통하여 이루어진다.
(1)과 (2)위치에 들어갈 세 자리 자연수가 주어질 때 (3), (4), (5), (6)위치에 들어갈 값을 구하는 프로그램을 작성하시오.
"""
a = int(input())
b = int(input())
if 100 <= a < 1000 and 100 <= b < 1000:
b_100 = int(b/100)
b_10 = int(b/10 - b_100*10)
b_1 = int(b - b_100*100 - b_10*10)
p... |
e98c075bd6df705c448082eda088c9040fe0d964 | gaurav-dalvi/codeninja | /python/CharSort.py | 759 | 3.75 | 4 | # Sort array of chars, ASCII only.
# Input : String of chars , terminated by newline of NULL
# Output: Sorted set of chars. You can overwrite array.
# Desired complexity : O(n) with constant space
def sortCharacters(inString):
inputList = list(inString)
asciiMap = [0] * 256
for i in xrange(len(inputList)):... |
a366ab030f405824d432fce15d6b96c2a72f23bb | gadoid/PythonNote | /Day1.py | 3,179 | 4.1875 | 4 | # int 整型
# 可以用 int() 强制转换为整型
float_number=1.1
print(int(float_number))
str_info="a"
# 进制
# 0b 2进制 0o 八进制 默认十进制 0x 十六进制
result=0b101+0o17+10+0x1D
print(result)
# 对其
#5 右对齐5位
#-5 左对齐 5位
print("%5d"%(result),"aaa")
print("%-5d"%(result),"aaa")
#float 浮点型
#转换整型为浮点型
int_number=2
print(float(int_number))
# .+数字打印固定位数小数... |
d9d8e95badf13bd1a561853ab9e815fd5353d3cb | liu-yuxin98/Python | /chapter6/6.2.py | 248 | 3.96875 | 4 | def sumDigits(number):
sum=0
if number<0:
number=-1*number
else:
number=number
while number != 0:
sum = sum + number % 10
number = (number - number % 10) / 10
return sum
print(sumDigits(-12345))
|
15f1893b4eb06b3d5f230c80c4225cced42ad593 | andresscode/coursera-cs-math-specialization | /math-thinking-cs/week-04/prime_conjecture.py | 236 | 3.578125 | 4 | def is_prime(n):
for i in range(2, n):
if n % i == 0:
return False
return True
def solve():
for i in range(1, 1000001):
num = i ** 2 + i + 41
if not is_prime(num):
return num
return -1
print(solve())
|
a6a61dcbb4ed002e75e26f999f14173aa6ff9638 | icole/MITx-6.00.1x | /problem-set-2/problem1.py | 563 | 3.78125 | 4 | balance = 4213
annualInterestRate = 0.2
monthlyPaymentRate = 0.04
totalPayment = 0
for i in range(1, 13):
print "Month: " + str(i)
minimumPayment = balance * monthlyPaymentRate
totalPayment += minimumPayment
print "Minimum monthly payment: %.2f" % minimumPayment
remainingBalance = balance - minimum... |
389ba775b135edee5a487b0b8c4791ee66dd3da9 | Davidxswang/leetcode | /easy/1370-Increasing Decreasing String.py | 2,323 | 3.890625 | 4 | """
https://leetcode.com/problems/increasing-decreasing-string/
Given a string s. You should re-order the string using the following algorithm:
Pick the smallest character from s and append it to the result.
Pick the smallest character from s which is greater than the last appended character to the result and append i... |
62c99807a59d0cb31c2bc0d0e7bd184a09872590 | didi1215/leetcode | /leetcode/leetcode/editor/cn2/[剑指 Offer 22]链表中倒数第k个节点.py | 1,154 | 3.65625 | 4 | # 输入一个链表,输出该链表中倒数第k个节点。为了符合大多数人的习惯,本题从1开始计数,即链表的尾节点是倒数第1个节点。
#
# 例如,一个链表有 6 个节点,从头节点开始,它们的值依次是 1、2、3、4、5、6。这个链表的倒数第 3 个节点是值为 4 的节点。
#
#
#
# 示例:
#
#
# 给定一个链表: 1->2->3->4->5, 和 k = 2.
#
# 返回链表 4->5.
# Related Topics 链表 双指针
# 👍 218 👎 0
# leetcode submit region begin(Prohibit modification and deletion... |
fe487327c7a3595f0d6722e6cfd2214cc8048b05 | C-Probert/python | /decimal.py | 980 | 4 | 4 | #!/usr/bin/python
import sys
hexmap = {0:'0', 1:'1',2:'2',3:'3',4:'4',5:'5',6:'6',7:'7',8:'8',9:'9',10:'A',11:'B',12:'C',13:'D',14:'E',15:'F'}
#function handles conversion of binary and hex.
#val is the decimal number and divnum is the number to divide by.
def convert_number(val, divnum):
quotient, remainder... |
24c377e51a2f279e6ddfe039fc3fbeef0a1a02c6 | taisei5i7/Python_learnigdebris | /3.7.2/panic my answer.py | 378 | 4.0625 | 4 | phrase = "Don't panic!"
plist = list(phrase)
print(phrase)
print(plist)
target = ["o", "n", "t", "a", "p"]
word = plist
found = []
for letter in word:
if letter in target:
if letter not in found:
found.append(letter)
plist = found
found.remove("a")
found.insert(2, " ")
found.insert(4, "a")
n... |
5d55ba16d3527c01c2176632d6d01312381e4ebe | cryp2knight/numerical-methods-notebooks | /notebooks/montecarlo.py | 1,980 | 3.953125 | 4 | # EXERCISE 1
from numpy.random import rand
from math import sqrt
def estimate_pi_with_monte_carlo(n=1000):
inside_points = 0
for _ in range(n):
x = rand()
y = rand()
distance = sqrt(x**2 + y**2)
if distance < 1:
inside_points += 1
return 4 * (inside_points / n)
... |
ded3511c3cfc1a61ce9dd684eedb8e39a2bcf052 | JosephLevinthal/Research-projects | /5 - Notebooks e Data/1 - Análises numéricas/Arquivos David/Atualizados/logDicas-master/data/2019-1/224/users/4366/codes/1734_2504.py | 325 | 3.796875 | 4 | quant1=int(input("digite a quantidade inicial de copias:"))
quant2=int(input("digite a quantidade inicial de leucocitos:"))
p1=int(input("digite o percentual1:"))
p2=int(input("digite o percentual2:"))
p1=p1/100
p2=p2/100
t=0
while(2*quant1>quant2):
quant1=quant1+quant1*p1
quant2=quant2+quant2*p2
t=t+1
print(t)
... |
426e26c9437d937cda71942ecf1195e1eacad9b2 | skipter/Programming-Basics-Python | /Exam 01.12.2018/01.School Supplies.py | 297 | 3.75 | 4 | pencil = int(input())
pen = int(input())
liquid = float(input())
discount = int(input())
pencip_price = pencil * 5.80
pen_price = pen * 7.20
liquid_price = liquid * 1.20
materials = pencipPrice + penPrice + preparatPrice
total = materials - ((materials * discount) / 100)
print(f"{total:.3f}")
|
117ef5751de8e4c5f8f691aafaa906fd501350e5 | lincolnjohnny/py4e | /2_Python_Data_Structures/Week_5/ex_09_04.py | 973 | 3.796875 | 4 | # Write a program to read through the mbox-short.txt and figure out who has sent the greatest number
# of mail messages.
# The program looks for 'From ' lines and takes the second word of those lines as the person
# who sent the mail.
# The program creates a Python dictionary that maps the sender's mail address to ... |
9d8066dd96b54af5bee1bd08f7ddea26e2ce6bde | Jackerdelta/VillagerTradePriceCheck | /PriceChecker.py | 2,586 | 3.59375 | 4 | import decimal
from decimal import *
class main:
def __init__(self,item_to_offer,item_for_trade,calculation_type,average_item_per_block,price_of_block,price_per_stack_in_shop,margin_desired):
setcontext(Context(prec=5))
self.item_to_offer=Decimal(item_to_offer)
self.item_for_trade=Decimal(i... |
1544c510f19b813837db7c9d4884521287b35986 | nortonacosta/Exercicios_Loops | /ex15.py | 104 | 3.875 | 4 | n = int(input('Digite um npumero ímpar: '))
for i in range(0, n):
if i % 2 == 1:
print(i)
|
f7972ebd14b6cf5f0bdda54d43409740203aeb00 | SirSanewa/rekrutacja | /app.py | 7,568 | 3.546875 | 4 | from sqlalchemy import func, desc
from models import Person
from session import session_creator
import argparse
from datetime import datetime
def percentage(number, total):
"""
Calculates and returns percentage value from given number and total amount.
:param number: int
:param total: int
:return:... |
0d7eae12c763142b4c1c04f5b91b5b6513f6ade5 | emilybee3/Flask-Madlibs | /madlibs.py | 3,293 | 3.65625 | 4 | from random import choice, randint#gets the choice function from random library
from flask import Flask, render_template, request
#importing the class Flask and the functions render_template and request from flask
# "__name__" is a special Python variable for the name of the current module
# Flask wants to know this... |
a27ecb0e07e8cb284ee3226b6f63d954b1aae65f | mnxtr/Leetcode | /Arrays/Two_Sum_Sorted.py | 1,126 | 4 | 4 | # Given an array of integers numbers that is already sorted in ascending order, find two numbers such that they add up to a specific target number.
# Return the indices of the two numbers (1-indexed) as an integer array answer of size 2, where 1 <= answer[0] < answer[1] <= numbers.length.
# You may assume that each i... |
b64e1c78d84ca3679a5c82cd72adf7f90149fa70 | talianassi921/python-practice | /Questions/capitalize_first_letter.py | 165 | 3.90625 | 4 | def capitalize_first_letter(sentence):
return " ".join([x[0].upper()+x[1:] for x in sentence.split(" ")])
print(capitalize_first_letter("talia is really cool")) |
bad62e9fc395ade1c58a834ea1136b0abe778d7c | Praful-a/Python-Programming | /Lists/list_methods.py | 4,679 | 4.875 | 5 | # # You can learn more :- https://www.programiz.com/python-programming/methods/list
# append :- The append() method adds an item to the end of the list.
animals = ['cat', 'dog', 'rabbit']
animals.append('guinea pig')
print(animals)
extend: - The extend() extends the list by adding all items of a list(passed as an a... |
719a526d2f8055676deceb068d545ac8667c661a | seatable/seatable-api-python | /seatable_api/column.py | 11,418 | 3.671875 | 4 | from datetime import datetime
from .constants import ColumnTypes
# Set the null list to distinguish the pure none and the number 0 or 0.00, which is
# a critical real value in number type column.
NULL_LIST = ['', [], None]
# Column Value related classes handle the compare computation of the table data
class ColumnV... |
f034abade681f231cec2b7dd1e815c5dd567e203 | Guitaristchris809/Payday-Calc | /PP1.0.py | 434 | 3.59375 | 4 | cash = float(17.50)
hours = float(raw_input("Hours worked in the past two weeks? ")) # def hours
def payment(): # calc reg pay
return hours * cash
def over():
if hours > 80:
OT = (hours - 80) * 8.75 # calc overtime hours
return OT
else:
OT = 0
return OT
def f... |
de2807b02f8a6f829875f26608af8300056e36f0 | simonzhang0428/Book_Think_Python | /File.py | 2,559 | 3.546875 | 4 | # infile = open('test.txt')
# with open('test.txt') as infile:
# for line in infile:
# line = line.rstrip()
# words = line.split()
# for word in words:
# word = word.rstrip(".,?!")
# print(word)
#
# using with, no need to close file
# infile.close()
# input_string =... |
edaa0a584a79471d7c5a0c5057f188fd0b0f7bfd | lucianofalmeida/Desafios_Python | /desafio050.py | 167 | 4.0625 | 4 | pessoas = ['rodrigo','rafael','guilherme','pedro','greyce','check','dark']
print(pessoas[-3:])
#o resultado são os 3 ultimos elementos da lista de forma negativa
|
67421d01436e1320ddb5c2e16c5f6c09a6bda7fb | jeremysherriff/HTPC-Manager | /libs/sqlobject/util/csvexport.py | 6,758 | 3.5625 | 4 | """
Exports a SQLObject class (possibly annotated) to a CSV file.
"""
import os
import csv
try:
from cStringIO import StringIO
except ImportError:
from StringIO import StringIO
import sqlobject
__all__ = ['export_csv', 'export_csv_zip']
def export_csv(soClass, select=None, writer=None, connection=None,
... |
97e2b9ec37e22b245ad3a8698b537f3f92a25b01 | samhuynhle/insertion_sort_python | /insertionsort.py | 417 | 3.921875 | 4 | testlist1 = [8,9,10,2,3,6,4,5,1,7]
def insertion_sort(some_list):
count = 0
for x in range(1, len(some_list), 1):
for j in range(x, 0, -1):
if some_list[x-j] > some_list[x]:
count += 1
some_list[x], some_list[x-j] = some_list[x-j], some_list[x]
print(count... |
a9e0695375429d465a19cc6ea233269159424818 | vipmunot/Data-Analysis-using-Python | /Python Programming Beginner/Customizing Functions and Debugging Errors-61.py | 3,286 | 3.890625 | 4 | ## 3. Optional Arguments ##
# Default code
def tokenize(text_string, special_characters, clean=False):
if clean == True:
cleaned_story = clean_text(text_string, special_characters)
story_tokens = cleaned_story.split(" ")
else:
story_tokens = text_string.split(" ")
return(story_token... |
a72ddb7ef6141a6bc96295149a0fed0dc241b4e8 | jasmine95dn/flask_best_worst_scaling | /tests/unit/test_models.py | 3,625 | 3.5625 | 4 | '''
Unit Tests for models.py
'''
def test_new_user(new_user):
"""
GIVEN a User model
WHEN a new User is created
THEN check
1. if username, email, password are defined correctly
2. if password is stored as hashed password, not plaintext
3. if get_id() returns a string in form 'user:<user_id>'
"""
### 1.
a... |
218484d4b63e6887c56234d3e188e841cc5ffe61 | atharva07/python-files | /problem2.py | 590 | 4.03125 | 4 | # initializng list
test_list = [3,5,6,2,34,43,54]
print("checking if 5 is present or not (using loop) : ")
# checking if 5 exist or not
for i in test_list:
if(i == 5):
print("element exist")
if (5 in test_list):
print('yes')
else:
print('no')
from bisect import bisect_left
test_set_list = [1,3,... |
f27c240d7154135c24249bbc49926e6f121e087f | narin-anongchai/RescueMaze | /docs/tutorials/Vision/step3_letter_detection.py | 4,430 | 3.640625 | 4 | """
Example OpenCV letter detection
Written by Fatemeh Pahlevan Aghababa, Amirreza Kabiri, MohammadHossein Goharinejad - 2020
"""
# if you haven't install opencv yet, please type "pip install opencv-python" in your terminal/command line.
import cv2
import numpy
import matplotlib.pyplot as plt
def find_victim_big(i... |
839d9a1cb0947df9a423ccdf4872bf35cc7d5e54 | skreynolds/RoboND_Code | /06_deepLearning/01_introNN/15_simpleNN/simple.py | 368 | 3.890625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Wed Nov 8 06:55:23 2017
@author: Shane Reynolds
"""
import numpy as np
def sigmoid(x):
# TODO: Implement sigmoid function
return 1/(1+np.exp(-x))
inputs = np.array([0.7, -0.3])
weights = np.array([0.1, 0.8])
bias = -0.1
# TODO: Calculate the output
output = sigmoid(s... |
fa6b2a341e522d5e252a60ad4493b4d7fbd6e8f0 | harishdasari1595/Personal_projects | /Algorithms and Datastructure/linked_list/swap_kth_node_from_end.py | 2,550 | 4.15625 | 4 | import sys
#Class for creating a node of a linked list
class node:
def __init__(self, info):
self.info = info
self.next = None
class LinkedList:
def __init__(self):
#At start the head is pointing to None
self.head = None
def display(self):
print ("#"*50)
... |
ce4de4da06874ce0bf862bb7c30a49d7e9a40f2b | reckful88/learning-python | /lianxi_alist.py | 669 | 3.953125 | 4 | #-*- coding:utf-8 -*-
#####求一个列表中最大的元素######
#def alist(n):
# a = n[0]
# for x in n:
# if x > a:
# a = x
# return a
def maxmin(n):
maxs = n[0]
mins = n[0]
for x in n:
if maxs < x:
maxs = x
if maxs > x:
mins = x
maxmin([1,2,3,4,5,6])
print max, mins
'''
In [26]:... |
aed4bc972a196867dc7b695a14be9a862a3c6fb3 | ravalrupalj/BrainTeasers | /Edabit/The_Frugal_Gen.py | 1,281 | 4.09375 | 4 | #The Frugal Gentleman
#Atticus has been invited to a dinner party, and he decides to purchase a bottle of wine. However, he has little knowledge of how to choose a good bottle. Being a very frugal gentleman (yet disliking looking like a cheapskate), he decides to use a very simple rule. In any selection of two or more ... |
096fd2e2f6e463f1b707a3ba007079ab829033a3 | rengoo/hello-world | /helloworld.py | 564 | 3.65625 | 4 | # This Program says hello
import random # Importiert Modul; Alternative ist from, womit man sich das Prefix spart
print('Hello')
myName = input("Eingabe?")
def caseselect(answer):
if answer == 1:
return 'lol'
elif answer == 2:
return 'jolo'
def myfunctionawesomefunction():
print("You have... |
e4bedd235221c712ccfa3d1ebfd1c960061d9b1b | felipe-basina/python | /codigos/verifica_total_caracteres.py | 393 | 3.5625 | 4 | # Verifica o total de caracteres diferentes
# para que seja possivel criar um anagrama, a partir de duas metades,
# de uma determinada palavra
from collections import Counter
s = "hhpddlnnsjfoyxpciioigvjqzfbpllssuj"
if len(s)%2 == 1:
print "-1"
print Counter(s[0:len(s)/2])
print Counter(s[len(s)/2:])
temp = Counter(s[... |
2ab52b08d731acc1df2368c72dd69262595ece52 | Totoro2205/python-rush-tasks | /level-1/task-1/task-1-15-1.py | 170 | 3.828125 | 4 | #!/usr/bin/env python3
#coding: utf-8
"""
pythonic way
"""
a = 1
b = 2
print('a = {}, b = {}'.format(a, b))
tmp = a
a = b
b = tmp
print('a = {}, b = {}'.format(a, b))
|
aff367252204147b02afc4ee0bd3b19574ded47d | rafaelperazzo/programacao-web | /moodledata/vpl_data/482/usersdata/348/110214/submittedfiles/Av2_Parte4.py | 365 | 3.953125 | 4 | # -*- coding: utf-8 -*-
m = int(input('informe as linhas: '))
n = int(input('informe as colunas: '))
matriz = []
for i in range (m):
linhas = []
for j in range (n):
linhas.append(int(input('informe os elementos: ')))
matriz.append(linhas)
print(matriz)
for i in range (m-1,-1,-1):
for j in rang... |
9c719e27b4949ef3233c228045820d0f206904e0 | SoniaSanchezSoto/Python-practice | /numeroMaximo.py | 216 | 3.921875 | 4 | def num_max (a, b, c):
if a > b and a > c:
print (a)
elif b > a and b > c:
print (b)
elif c > a and c > b:
print (c)
else:
print ("Son Iguales")
num_max(1,2,3) |
51580829d3cb4e41be32d27413f5b3d3678b6be6 | agnaka/CEV-Python-Exercicios | /Pacote-download/Exercicios/ex086.py | 759 | 3.75 | 4 | matriz = [[0, 0, 0], [0, 0, 0], [0, 0, 0]]
for l in range(0,3):
for c in range(0, 3):
matriz[l][c] = int(input(f'Digite um valor para [{l}, {c}]'))
print('-=' * 30)
for l in range(0,3):
for c in range(0,3):
print(f'[{matriz[l][c]:^5}]', end = '')
print()
print()
print('FIM')
'''lista = [[], ... |
8a54287b6778d50690e5004f1e9e4c6afb74068c | vektorelpython/Python17Temel | /Ornek2.py | 738 | 3.578125 | 4 | # a = 1
# b = 1
# bolum = 0
# for i in range(0,100):
# c = a+b
# print(c)
# b,a = c,b
# if bolum == a/b:
# print(i)
# break
# else:
# bolum = a/b
metin = "Aç raporunu koy okunur o parça"
# metin = metin.replace(" ","").lower()
# print(metin)
# print(len(metin)//2)
# print(... |
4086b49cf8e65c224e7f16e74cfc4c3144b719e2 | Orcha02/holbertonschool-higher_level_programming | /0x01-python-if_else_loops_functions/6-print_comb3.py | 255 | 3.90625 | 4 | #!/usr/bin/python3
for num1 in range(10):
for num2 in range(10):
if num1 == 8 and num2 == 9:
print("{0:d}{1:d}\n".format(num1, num2), end="")
elif (num1 < num2):
print("{0:d}{1:d}".format(num1, num2), end=", ")
|
122579eccc6ccea8dd34ecb29b3309f825ddba8d | yinhuax/leet_code | /datastructure/my_sorted/Select_sort.py | 585 | 3.9375 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Author : Mike
# @Contact : 597290963@qq.com
# @Time : 2021/2/9 12:03
# @File : Select_sort.py
class Select_sort(object):
def select_sort(self, alist):
n = len(alist)
for i in range(n - 1):
min_index = i
for j in range... |
7ade61b9c4203df975feb291bd3fd28bbd296f5b | wk8/noble-words | /knight_solver.py | 1,536 | 3.703125 | 4 | class KnightSolver(object):
def __init__(self, grid, dictionary_root):
self._grid = grid
self._root = dictionary_root
def find_longest_words(self):
'''
Returns a list of the longest words from the dictionary found
in the grid; i.e. all words in the returned list have the... |
7d2a45f0a81adeaecd6e894068e7cd1930a86e7c | GouravSardana/sorting_algos | /selection_sort.py | 624 | 4 | 4 | def selection_sort(lst):
n = len(lst)
for i in range(n): # to loop throught through all the elments within the list
smallest_index = i # let the index for smallest element be initially i
for j in range(i+1, n): # loop from i + 1 to n
if(lst[j] < lst[smallest_index]): # if any element is less than lst[sm... |
ae1c4128b0b1b60bad1174cfe0357a762fd05c96 | GabrieLima-dev/Coursera | /bhaskara.py | 563 | 3.828125 | 4 | import math
a = float(input("Digite o valor de a: "))
b = float(input("Digite o valor de b: "))
c = float(input("Digite o valor de c: "))
delta = b ** 2 - 4 * a * c
if delta == 0:
raiz_1 = (-b + math.sqrt(delta))/(2 * a)
print("a raiz desta equação é", raiz_1)
else:
if delta < 0:
print("esta equ... |
c794653e7610a9f0ad3aaaf3523a7dabef36973b | Javier-cyber-Wx/Farenheit-a-celcius | /algoritmo 1/primer programa.py | 249 | 3.9375 | 4 | def fahrenheit_a_celsius(f):
return (f - 32) / 1.8
f = float(input("Ingresa los grados Fahrenheit: "))
c = fahrenheit_a_celsius(f)
print(f"Los {f} grados Fahrenheit son {c} grados celsius")
input("Presione una tecla para finalizar....")
|
3458b4dccb86827584d2aab063135ca98909ebe3 | CharlieX1701/NatureConnect | /readQuotes.py | 627 | 3.859375 | 4 | ''''
The purpose of this program is to read in a file containing inspirational
quotes, clean the data, and then randomly select a quote from this file
and print it for the user.
'''
import random
#read in quotes data, clean it, write out to file
def readQuotes():
filename = 'quotes.csv'
infile = open(... |
78cbc3b097352947ed9c537c5b3959899fa55a0e | jennyChing/onlineJudge | /11408.py | 1,722 | 3.875 | 4 | '''
Primes
11408 - Count DePrimes
Input
Each line contains a and b in the format ‘a b’. 2 ≤ a ≤ 5000000. a ≤ b ≤ 5000000. Input is terminated by a line containing ‘0’.
Output
Each line should contain the number of DePrimes for the corresponding test case. Explanation: In Test Case 2, take 10. Its Prime Factors are... |
6dcc80c5091f79e68902b1b2d01fd88de26c599b | hyc121110/LeetCodeProblems | /Others/gardenNoAdj.py | 1,240 | 4.25 | 4 | '''
You have N gardens, labelled 1 to N. In each garden, you want to plant one of 4 types of flowers.
paths[i] = [x, y] describes the existence of a bidirectional path from garden x to garden y.
Also, there is no garden that has more than 3 paths coming into or leaving it.
Your task is to choose a flower type for e... |
166c9b0763f36d5631f1acd1140f22d61210ac6c | patmorin/lhp | /lhp_demo.py | 6,220 | 3.515625 | 4 | #!/usr/bin/python3
import sys
import time
import random
import itertools
import matplotlib.pyplot as plt
import scipy.spatial
import lhp
def triangulate(points):
n = len(points)
dt = scipy.spatial.Delaunay(points)
assert(dt.npoints == n)
assert(len(dt.convex_hull) == 3)
assert(dt.nsimplex == 2*n -... |
77cc8c1d0eda809026c68048bb9047ba24505f76 | kain21/Lesson | /4.py | 73 | 3.578125 | 4 | a = 2
b = int(input("Введите значение b: "))
print (a + b) |
5d84378f660cd0098b7dcb58325b34b728a7e520 | Noe-ZM28/Curso-Python | /Flujo/Iteracion/while/While_4.py | 542 | 4.0625 | 4 | while (True):
print("*************************")
print("**Selecciona una opcion**")
print("*************************")
print("""1) Saludar
2) Sumar 2 numeros
3) Salir""")
print("<: ")
opcion = input()
if opcion == '1':
print("Hola:D")
elif opcion == '2':
a = float(input(... |
6238c68b588c229c61f5e972d771cf9e626681c2 | tri-llionaire/tri-llionaire.github.io | /numbers.py | 759 | 3.5625 | 4 | #GUESS A NUMBER THAT'S BEEN RANDOMLY GENERATED
import random, time
find = random.randint(0, 9999999)
x = 0
t = 0
s = int(input('how many seconds to try: '))
guesses = []
start = time.time()
while (time.time() - start) < s:
guess = random.randint(0, 9999999)
'''while guess in guesses:
t += 1
gues... |
052f50f4923856f1460e8bad879c8a7b9e5c4887 | muellerjo/COVID-2019-Plots | /00_ETL-Python/02_add-population and KPIs.py | 2,561 | 4.125 | 4 | #!/usr/bin/env python
# coding: utf-8
# In[2]:
#After the Union of the CSVs, we will add the population of the countries to the completed dataset
#First we load the dataset with the numbers of world population
import pandas as pd
import numpy as np
#Load the CSVs
covid_cases = pd.read_csv ('../01_ETLOutput-CSV/01... |
0f83199c73619f818b356c7593d9e17bb505cc7c | brendanstuff/wisconsin | /pixelartclass.py | 2,224 | 3.59375 | 4 | from turtle import Turtle
t = Turtle()
size = 20
row = 5
blue = 3
t.st()
for i in range(row):
t.begin_fill()
for j in range(4):
t.forward(size)
t.right(90)
t.end_fill()
t.forward(size)
t.back(size * row)
t.setpos(t.xcor(), t.ycor() + size)
# Next row
... |
a077dcdf767fcfbb67b1d575fc421169733b9987 | humbertoperdomo/practices | /python/PythonCrashCourse/PartI/Chapter05/hello_admin.py | 375 | 3.90625 | 4 | #!/usr/bin/python3
#users = ['anonymous', 'webmaster', 'admin', 'dbadmin', 'humberto']
users = []
if users:
for user in users:
if user == 'admin':
print("Hello " + user + ", would you like to see a status report?")
else:
print("Hello " + user + ", thank you for logging in a... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.