blob_id stringlengths 40 40 | repo_name stringlengths 5 127 | path stringlengths 2 523 | length_bytes int64 22 545k | score float64 3.5 5.34 | int_score int64 4 5 | text stringlengths 22 545k |
|---|---|---|---|---|---|---|
3ed2fd1a398f1ea26d0f619e74404dec56463b70 | jfsawyer88/CodeEval | /2-Moderate/101-FindASquare/FindASquare.py | 1,289 | 3.875 | 4 | ## CodeEval
## Find A Square
## by using dot products
import sys
if 1 != len(sys.argv):
f = open(sys.argv[1], 'r')
else:
import os
f = open(os.getcwd() + '/test.txt', 'r')
# vector functions
def dist_sqr(a,b):
'''squared distance between two poins'''
return (a[0] - b[0])**2 + (a[1] - b[1])**2
def... |
2cfcedba42fd9ffff39eed5a54dc4ca18687be60 | santospadua/hands-on-python | /code/05-list-comprehension.py | 858 | 3.96875 | 4 | # Importando reduce
from functools import reduce
# Utilizando List Comprehension
nome = [letra for letra in "Antonio"]
# Imprimindo o resultado
print(nome)
# List Comprehension de números pares sob uma sequência de números
pares = [numero for numero in range(0, 12) if numero % 2 == 0]
# Imprimindo o resultado
print... |
255b4f53ff710b11971a87bc8358931710880792 | MrLiZ/exercises | /evaluations/go/demo.py | 396 | 3.578125 | 4 | #!/usr/bin/env python
#-*- coding: utf-8 -*-
def solution(A):
""""""
if not A:
return -1
else:
tot = sum(A)
acum = 0
for i, elem in enumerate(A):
tot -= elem
if tot == acum:
return i
acum += elem
return -1
if __na... |
fff940755b1e64cee4ea93d2be0ca03e57bcee8e | MrLiZ/exercises | /evaluations/codeeval/hard/longest_common_subsec.py | 1,556 | 3.53125 | 4 | #!/usr/local/bin python
#-*- coding: utf-8 -*-
import sys
import traceback
def longest_common_subseq(a, b):
""""""
length_a = len(a) + 1
length_b = len(b) + 1
matrix = [[set([]) for i in xrange(length_b)] for j in xrange(length_a)]
for i in xrange(1, length_a):
for j in xrange(1, length_... |
b7441d6f8d14685237d6aaad8c1c6f519d06415e | victordsantoss/elementary-island-by-checkio | /EvenTheLast.py | 361 | 3.765625 | 4 | def checkio (array):
i = 0
soma = 0
# Verifica se há elementos na matriz
if not array:
return 0
else:
while i < len (array):
if (i % 2 == 0):
soma += array[i]
i += 1
else:
i += 1
resultado = soma * a... |
af796264011124bbb30ddf0522df686b3c48d621 | victordsantoss/elementary-island-by-checkio | /RemoveAllBefore.py | 389 | 3.90625 | 4 | from typing import Iterable
def remove_all_before (items: list, border: int):
i = 0
if not items:
return items
# Verifica se o elemento está contido na lista
if border in items:
while i < len (items):
if items[i] != border:
items.pop (i)
els... |
cdc8fbc0c7157750629e80859440239fc08d9fd0 | Dan-IoT-2019-Summer/rocket_landing | /FirstClass/my_rocket.py | 1,943 | 4.0625 | 4 | # 2019_07_11_IoT_Summer_2019
# const list
max_input_fuel = 20 # You have thrusters that can be powered from 0 to 20.
min_input_fuel = 0
max_acceleration = 10 # acceleration (minimum -10, maximum +10)
min_acceleration = -10
g_acceleration = -10 # gravity_acceleration
r_height = 100 # rocket_height
r_velocity = 0 # rock... |
8cf387e7d25fe88b26c105cc6c9c4d02fa06bd98 | damiras/gb-python | /lesson5/task5.py | 942 | 3.84375 | 4 | """
Создать (программно) текстовый файл, записать в него программно набор чисел, разделенных пробелами.
Программа должна подсчитывать сумму чисел в файле и выводить ее на экран.
"""
from random import randint
number_count = 10
number_from_to = (-100, 100)
numbers_filename = 'task5.dat'
with open(numbers_filename, 'w... |
d3c5e30d763a1126c3075b37562a8c953c0102d7 | damiras/gb-python | /lesson6/task2.py | 1,215 | 4.3125 | 4 | """
Реализовать класс Road (дорога), в котором определить атрибуты: length (длина), width (ширина).
Значения данных атрибутов должны передаваться при создании экземпляра класса. Атрибуты сделать защищенными.
Определить метод расчета массы асфальта, необходимого для покрытия всего дорожного полотна.
Использовать формулу... |
b8d4afeac27b157097003a8f87713a10ffa53592 | damiras/gb-python | /lesson4/task3.py | 371 | 4.09375 | 4 | """
Для чисел в пределах от 20 до 240 найти числа, кратные 20 или 21. Необходимо решить задание в одну строку.
Подсказка: использовать функцию range() и генератор.
"""
result_list = [n for n in range(20, 241) if not n % 20 or not n % 21]
print(result_list)
|
5457a5bf08547f0b3b1d5b6b2ed4954c0c0e5fe0 | sofielohr/pset8 | /cardgame.py | 256 | 3.546875 | 4 | class Card(object):
def __init__(self, suit, value):
self.suit = suit
self.value = value
def __str__(self):
return f"{self.value} of {self.suit}"
if __name__ = "__main__":
var1 = Card(spades, ace)
print(var1)
|
09c0d47b6331b8c38cc09ce4f252020331a3aae7 | igormrocha/Machine-Learning | /Tensorflow/tf_iris_DNN_classification.py | 2,555 | 3.59375 | 4 | from __future__ import absolute_import, division, print_function, unicode_literals
import tensorflow as tf
import pandas as pd
CSV_COLUMN_NAMES = ['SepalLength', 'SepalWidth', 'PetalLength', 'PetalWidth', 'Species']
SPECIES = ['Setosa', 'Versicolor', 'Virginica']
train = pd.read_csv("https://storage.googleapis.com/d... |
c2123be019eca85251fbd003ad3894bb51373433 | jacobroberson/ITM313 | /hw2.py | 1,516 | 4.5 | 4 | '''
This program provides an interface for users to select a medium and enter a distance
that a sound wave wil travel. Then the program will calculate and display the time it
takes for the waveto travel the given distance.
Programmer: Jacob Roberson
Course: ITM313
'''
#Intialize variables
selection = 0
medium ... |
674efeb9c64a67cfd2c4d7787b1034d485c5ecef | jacobroberson/ITM313 | /hw4.py | 791 | 3.921875 | 4 | '''
This program takes integer inputs until the user enters -9999 and
then calculates and displays the smallest number entered, the largest
number entered, the total, and the average
Name: Jacob Roberson
Course: ITM313
'''
num = []
i = 0
total = 0
count = 0
i = int(input("Enter an integer. Enter -99999 to ... |
fd297908294c04f1aab9e4ac00fe2aab7b7cab03 | GoldCodeSensen/python_exercise | /digui.py | 680 | 4.125 | 4 | #递归算法关键点:1.调用函数自身的行为 2.有停止条件
#下面举一个计算阶乘的例子
def factorial(x):
if x>1:
return x*factorial(x-1)
else:
return 1
print(factorial(10))
#递归举例,计算斐波那契数列
def fabo(x):
if x > 2:
return fabo(x-1)+fabo(x-2)
elif x == 2:
return 1
elif x == 1:
return 1
print(fabo(20))
#用递归... |
ff62ce4e5ae2d83bed1443584040f831ab8ca9f0 | GoldCodeSensen/python_exercise | /oop_pool.py | 1,246 | 4.4375 | 4 | #类的组合:把类的实例化放在新的类中
class Turtle:
def __init__(self,x):
self.num = x
class Fish:
def __init__(self,x):
self.num = x
class Pool:#类Pool将Turtle类和Fish类实例化,作为自己的元素
def __init__(self,x,y):
self.turtle = Turtle(x)
self.fish = Fish(y)
def print_num(self):
print('There ar... |
0381c5af3048e3f0eedfca1f4854cb97fb512f7c | exojosh/NumPy-Practice | /Math 142 Homework 3 Probelm 3.py | 974 | 3.78125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sat Apr 24 15:18:34 2021
Code by Josh Limon
Student ID: 804-984-257
Homework 3 Problem 3 (System of Differential Equations)
"""
import numpy as np
import matplotlib.pyplot as plt
import math
"""
mx''(t) + c x'(t) + k x(t) = 0, 4mk < c^2 so overdamped, m = 1, k =... |
aa1c3f98455664b53beae9721363e490de6f3ccf | exojosh/NumPy-Practice | /Math 142 Homework 8 Problem 3.py | 1,980 | 3.90625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Fri May 28 12:07:50 2021
Josh Limon
Student ID: 804-984-257
Homework 8 Problem 3 (Gradient Descent via Forward Euler Method))
"""
import numpy as np
import matplotlib.pyplot as plt
import math
from mpl_toolkits import mplot3d
#Forward Euler on 3 different functions
... |
64ece2b9c1e4bc035dab79b5dfb2f1c3ba0a7e50 | deepupradeepm/deepu | /python3.7ex/list1.py | 176 | 3.71875 | 4 | list=[10,20,30,40,1,2,3]
for y in range(len(list)-1):
for x in range(len(list)-1):
if list[x]>list[x+1]:
list[x],list[x+1]=list[x+1],list[x]
print(list)
|
c2ab8d930c048df3db40485cfefbde61781287b0 | deepupradeepm/deepu | /python3.7ex/displaydupicate.py | 356 | 3.671875 | 4 | l=[1,3,4,56,2,3,4]
len=len(l)
i=0
while i<len:
j=i+1
while j<len:
if l[i]==l[j]:
print("duplicate index of a number:",j)
print("duplicate number in list",l[j])
del l[j]
len=len-1
j=j+1
i=i+1
print("list without duplic... |
1a1a6809dc06f905ee92fde58461f32ca44b58b8 | ET-CS/python-minimal-cli-template | /src/cli.py | 217 | 3.546875 | 4 | from argparse import ArgumentParser
def main():
parser = ArgumentParser(prog='My App')
parser.add_argument('name', help="The user's name.")
args = parser.parse_args()
print("Hello, %s!" % args.name)
|
be1088d23e844d228afef4282c3bb5e197de15c6 | mikebg95/CS50-Psets | /Pset6/DNA/dna.py | 1,508 | 3.890625 | 4 | from sys import argv
import csv
# ensure correct usage
if len(argv) != 3:
print("usage: ./dna database.csv sequence.txt")
# open files
database = csv.reader(open(argv[1], "r"))
sequence = open(argv[2], "r").read()
# check header of csv file
csv_header = next(database)
# create lists for str's and their counts
s... |
11dc368e0afae18b9b8827c893853a1d81a62d87 | KennethTBarrett/Data-Structures | /queue/queue.py | 4,248 | 4.40625 | 4 | """
A queue is a data structure whose primary purpose is to store and
return elements in First In First Out order.
1. Implement the Queue class using an array as the underlying storage structure.
Make sure the Queue tests pass.
2. Re-implement the Queue class, this time using the linked list implementation
as t... |
f1162f4ae5578d19c85dc906f63a2be271749148 | zer0-gl1tch/adventofcode2020 | /aoc2020day8.py | 1,257 | 3.515625 | 4 | #!python3
# https://adventofcode.com/2020/day/8
import re
import copy
FILENAME = 'day8input.txt'
puzzleInput = open(FILENAME, 'r')
instructions = puzzleInput.readlines()
def runAsembler(instructions):
opRegex = re.compile(r'(nop|acc|jmp)\s([+-]\d+)')
executedInstructions = []
pc = 0
acc = 0
whil... |
c175693f0f6c733ce47d8c8934a1198242a38e70 | zer0-gl1tch/adventofcode2020 | /aoc2020day5.py | 894 | 3.5625 | 4 | #!python3
# https://adventofcode.com/2020/day/5
FILENAME = 'day5input.txt'
puzzleInput = open(FILENAME, 'r')
seatList = puzzleInput.read().split('\n')
def getId(seat):
return getRow(seat) * 8 + getCol(seat)
def getRow(seat):
rows = list(range(128))
for char in seat[:7]:
if char == 'F':
... |
246bda1a142b722778c12628e7866fd14fe44e96 | Reedlee/devops | /hw6.py | 329 | 4.0625 | 4 | number = input("Введите целое число:\n")
is_palindrome_base_10 = (number == number[::-1])
binary = bin(int(number))
binary = binary[2:]
is_pandrome_base_2 = (binary == binary[-1::-1])
is_palindrome = is_palindrome_base_10 & is_pandrome_base_2
print(f"Это полный палидром? {is_palindrome}")
|
83f63708ba511ac1255df8056985f9ff2f49c843 | stshubham1820/Functionalpro | /Binarysearch.py | 620 | 3.890625 | 4 | List = [1,2,3,4,5,6,7,8,9]
ser = int(input("Enter a number You want to search :"))
def sar(Listo,ser) :
List3=[]
mid = int(len(Listo)/2)
s=ser
#print(mid)
if s == Listo[mid] :
print("Found :",Listo[mid])
elif s<Listo[mid] :
for i in range(mid):
... |
0c7c070753cf63c555335b31d7773222ce84e787 | yamaqo/PythonAlgorithm | /select_sort.py | 501 | 3.9375 | 4 | from random import randint
from typing import List
def select_sort(numbers: List[int]) -> List[int]:
numbers_len = len(numbers)
for i in range(numbers_len):
selected = i
for j in range(i + 1, numbers_len):
if selected > numbers[j]:
selected = numbers[j]
num... |
ad90d9bb763a81172ace179e4a77bcbf428a57ab | xuedong/leet-code | /Problems/Algorithms/1379. Find a Corresponding Node of a Binary Tree in a Clone of That Tree/clone_tree.py | 664 | 3.546875 | 4 | # Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def __init__(self):
self.ans = None
def getTargetCopy(self, original: TreeNode, cloned: TreeNode, target: TreeNode) -> TreeN... |
41ff5ee78abde30dcd3e02987bea84c073706786 | xuedong/leet-code | /Problems/Algorithms/93. Restore IP Addresses/restore_ip_addresses.py | 564 | 3.546875 | 4 | #!/usr/bin/env python3
import itertools
from typing import List
class Solution:
def leading_0(self, s: str):
return s[0] == "0" and s != "0"
def is_valid(self, s: str):
return not self.leading_0(s) and int(s) <= 255
def restoreIpAddresses(self, s: str) -> List[str]:
result = []
... |
a24cb60c07e0e480b7dc03b4d4094d1a607fe845 | xuedong/leet-code | /Problems/Algorithms/336. Palindrome Pairs/palindrome_pairs.py | 1,797 | 3.765625 | 4 | #!/usr/bin/env python3
from typing import Tuple
class TrieNode:
def __init__(self) -> None:
self.children = {}
self.end = False
self.idx = -1
class Trie:
def __init__(self) -> None:
self.root = TrieNode()
def insert(self, word: str, idx: int) -> None:
node = self... |
fa55b93a5f313f357d60effeaa5e156d37b6aec7 | xuedong/leet-code | /Problems/Algorithms/1704. Determine If String Halves Are Alike/alike_halves.py | 465 | 3.75 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
class Solution:
def halvesAreAlike(self, s: str) -> bool:
vowels = ['a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U']
n = len(s)
count_left, count_right = 0, 0
for i in range(n//2):
count_left = count_left + 1 if s[i] in v... |
c04aff14e0c7493ea930813170464eba83cf5c08 | xuedong/leet-code | /Contest/Biweekly Contest 83/Design a Number Container System/number_container2.py | 811 | 3.734375 | 4 | #!/usr/bin/env python3
from sortedcontainers import SortedList
class NumberContainers:
def __init__(self):
self.pairs = {}
self.map = {}
def change(self, index: int, number: int) -> None:
if index in self.pairs:
self.map[self.pairs[index]].discard(index)
self... |
e0a4bbf1f106622a38899f2f44421f9c18b7fa90 | xuedong/leet-code | /Problems/Algorithms/989. Add to Array-Form of Integer/add_to_array_integer.py | 286 | 3.53125 | 4 | #!/usr/bin/env python3
from typing import List
class Solution:
def addToArrayForm(self, num: List[int], k: int) -> List[int]:
for i in range(len(num) - 1, -1, -1):
k, num[i] = divmod(num[i] + k, 10)
return [int(i) for i in str(k)] + num if k else num
|
6bf4c01f8d9c52f5d12a2b43e214dfb649ce59e7 | xuedong/leet-code | /Problems/Algorithms/728. Self-Dividing Number/self_dividing_number.py | 427 | 3.921875 | 4 | #!/usr/bin/env python3
# coding: utf-8
from typing import List
class Solution:
def selfDividingNumbers(self, left: int, right: int) -> List[int]:
return [num for num in range(left, right + 1) if self.isSelfDividing(num)]
def isSelfDividing(self, num: int) -> bool:
for digit in str(nu... |
ff3df15a0fcd97f660baaec69eaf92369ef0590b | xuedong/leet-code | /Problems/Algorithms/150. Evaluate Reverse Polish Notation/evaluate_rpn.py | 773 | 3.65625 | 4 | #!/usr/bin/env python3
from typing import List
class Solution:
def evalRPN(self, tokens: List[str]) -> int:
stack = []
token = tokens[0]
stack.append(token)
ans = int(token)
for i in range(len(tokens)):
token = tokens[i]
if token not in ["+", "-", ... |
b43a488a6f7b1af3e30223d90f4827372c7a43f8 | xuedong/leet-code | /Problems/Algorithms/2029. Stone Game IX/stone_game_IX.py | 344 | 3.5 | 4 | #!/usr/bin/env python3
from collections import Counter
from typing import List
class Solution:
def stoneGameIX(self, stones: List[int]) -> bool:
counts = Counter(stone % 3 for stone in stones)
if counts[0] % 2 == 0:
return counts[1] > 0 and counts[2] > 0
return abs(counts[1] -... |
c239f5e70e8408e7fe2a72e759c16bd4501be153 | xuedong/leet-code | /Problems/Algorithms/108. Convert Sorted Array to Binary Search Tree/sorted_array_to_bst.py | 688 | 3.71875 | 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
class Solution:
def sortedArrayToBST(self, nums: List[int]) -> Optional[TreeNode]:
def aux(nums: List[int], start: i... |
57713959bf7b7f86db37c2db7b6c218865fb1682 | xuedong/leet-code | /Problems/Algorithms/20. Valid Parentheses/valid_parentheses.py | 641 | 3.796875 | 4 | #!/usr/bin/env python3
from collections import deque
class Solution:
def isValid(self, s: str) -> bool:
stack = deque()
for ch in s:
if ch in ['(', '[', '{']:
stack.append(ch)
else:
end = ''
if ch == ')':
... |
3bd82933bf55e00adcaf7f78f8f2f4811182de5f | xuedong/leet-code | /Problems/Algorithms/1533. Find the Index of the Large Integer/find_index_large_int.py | 962 | 3.515625 | 4 | #!/usr/bin/env python3
# """
# This is ArrayReader's API interface.
# You should not implement it, or speculate about its implementation
# """
class ArrayReader(object):
# Compares the sum of arr[l..r] with the sum of arr[x..y]
# # return 1 if sum(arr[l..r]) > sum(arr[x..y])
# return 0 if sum(arr[l..r]) == s... |
bfe81639c566df74f78b09b27dde1b34dd2b0c60 | narnt/grokking-algorithms | /binary_search/binarySearch.py | 463 | 3.859375 | 4 | def binary_search(list,item):
low = 0
high = len(list)-1
while low <= high:
middle = (low+high)//2
guess = list[middle]
if guess == item:
return middle
if guess > item:
high = middle - 1
else:
low = middle + 1
n_list = [1,2,3,4,5,... |
4c35fc09f2d145723b7119d1081bf2e97b905730 | Yash-Kr/SnakeGame | /main.py | 1,357 | 3.6875 | 4 | from turtle import Screen
import time
from snake import Snake
from food import Food
from score import Score
screen = Screen()
screen.setup(width=600, height=600)
screen.bgcolor("black")
screen.title("Snake Game - by YASH")
screen.tracer(0)
starting_pos = [(0, 0), (-20, 0), (-40, 0)]
segments = []
snake = Snake()
fo... |
8ff86507dc94de484d216b158cb7ec48580a566d | Qieclipkh/study-python | /study/study07/study07.py | 3,390 | 4.09375 | 4 | #更加抽象
#多态
#参数是支持加法的对象,都可以使用operater模块的add方法
import operator
print(operator.add(1,2))
print(operator.add('changle','le'))
#封装
#继承
#创建自己的类,参考study07_002
#特性、函数和方法
class Class:
def method(self):
print('I hava a self')
def function():
print('I don\'t...')
instance =Class()
instance.method()
instance.meth... |
9eb7cec14193b5c7cb83aa57ab0d65b457fc56cb | zach-wahrer/object-oriented-principles-course | /turtle_race/turtle_race.py | 977 | 3.984375 | 4 | from random import randint
from turtle import Turtle
def create_turtle(name, color, shape, turtles_dict):
turtles_dict[name] = Turtle()
turtles_dict[name].color(color)
turtles_dict[name].shape(shape)
def goto_loc(name, location, turtles_dict):
turtles_dict[name].penup()
turtles_dict[name].goto(l... |
f5cca4c212b53b7db5c6dd530ba7af2f8097f5e2 | florenceloi/calculator-2 | /arithmetic.py | 1,044 | 3.890625 | 4 | def add(lst):
total = 0
for item in lst[1:]:
total += item
return total
def subtract(lst):
total = lst[1]
for item in lst[2:]:
total -= item
return total
def multiply(lst):
total = lst[1]
for item in lst[2:]:
total *= item
return total
def divide(lst):
... |
cbed8e40f548a4a950350a5ce31354d61552d35a | Alcarynn/poepython | /hello.py | 596 | 3.9375 | 4 | x = "Hello World!"
print(x)
n = 3.14
print(f"Ceci est le nombre pi :{n}");
def add(i,j):
return i+j
x = add(3,2)
print(x)
i = 0
while i < 10:
print(i)
i+=1
for i in range(10):
if i % 2 == 0:
print(i)
def isPrime(n):
res = True
if n < 2:
res = False
else:
for i in... |
df2bdf275ac2e87d7570db76370c08e6361dfca6 | danma9023/Leetcode_SQL | /1613. Find the Missing IDs.py | 1,571 | 3.78125 | 4 | # 1613. Find the Missing IDs
# Medium
# 77
# 10
# Add to List
# Share
# SQL Schema
# Table: Customers
# +---------------+---------+
# | Column Name | Type |
# +---------------+---------+
# | customer_id | int |
# | customer_name | varchar |
# +---------------+---------+
# customer_id is the primary key ... |
7901450763ad3cff74b340143e83eca1c64afa1a | danma9023/Leetcode_SQL | /1112. Highest Grade For Each Student.py | 2,001 | 3.515625 | 4 | # 1112. Highest Grade For Each Student
# Similar to 184. Department Highest Salary*********
# Medium
# 126
# 4
# Add to List
# Share
# SQL Schema
# Table: Enrollments
# +---------------+---------+
# | Column Name | Type |
# +---------------+---------+
# | student_id | int |
# | course_id | int ... |
65a1b5d592c86e26d2ba60a2482b4b5d4837ce5f | dimonimmortal/immortal | /README.py | 491 | 3.515625 | 4 | # immortal
# dump calculator v1
from colorama import init
from colorama import Fore, Back, Style
init()
print(Fore.GREEN)
print( Back.YELLOW)
what = input( " what doing? (+ , - )")
print( Back.RED)
a =float( input("write first letter:"))
b =float( input("write second letter:"))
print( Back.CYAN)
if what == "+":
c = ... |
48167586c1044ea8f1f451c5c247f54b6cdd5677 | DanielMoscardini-zz/python | /pythonProject/Curso Em Video Python/Mundo 1/ex008.py | 347 | 3.765625 | 4 | """
Faça um software que receba um valor em metros e converta para centimentros e milimetros
"""
valorMetros = float(input('Qual o valor em metros? '))
valorCentimentros = valorMetros * 100
valorMilimetros = valorMetros * 1000
print(f'Valor em: \nMetros: {valorMetros} \nCentimentros: {valorCentimentros:.0f} \nMilimetro... |
b927d3a715909e49b61a08a9e60390ce6e0f609a | DanielMoscardini-zz/python | /pythonProject/Curso Em Video Python/Mundo 3/Aula 16.py | 1,363 | 4.59375 | 5 | """
Listas são definidos por colchetes => []
Listas podem ser mutaveis
Para adicionar valores a uma lista(ao final da lista), utilize o metodo .append(x)
Para adicionar valores em alguma posição selecionada, utilize o metodo .insert(0, x)
# 0 é a posição e x é o valor, nesse caso, os outros valores da lista iriam "an... |
75d620685d1b50902ca262484eb1a2f10ed611e2 | DanielMoscardini-zz/python | /pythonProject/Curso Em Video Python/Mundo 3/ex078.py | 703 | 3.953125 | 4 | """
Faça um programa que leia 5 valores numericoes e guarde-os em uma lista. No final, mostre qual foi o maior
e o menor valor digitado e as suas respectivas posições na lista.
"""
listanum = []
for c in range(0, 5):
listanum.append(int(input(f'Digite um valor para a posição {c}: ')))
print(f'Você digitou os valor... |
5a1a4d0b4ed010532c09e407ceba96d326674a8b | DanielMoscardini-zz/python | /pythonProject/Curso Em Video Python/Mundo 1/ex027.py | 353 | 4.03125 | 4 | """
Faça um software que leia o nome completo de uma pessoa, mostrando em seguida, o primeiro e o ultimo nome separadamente.
ex: Ana Maria de Souza
Primeiro: Ana
Ultimo: Maria
"""
n = str(input('Digite seu nome: ')).strip()
nome = n.split()
print(f'Seu nome é: {nome}\n'
f'Seu primeiro nome é: {nome[0]}\n'
f... |
8809e28bc92ebe7edbbc9ba0021ae499acfaf1fe | DanielMoscardini-zz/python | /pythonProject/Curso Em Video Python/Mundo 1/ex012.py | 264 | 3.578125 | 4 | """
Faça um software que leia o preço de um produto e mostre seu novo preço, com 5% de desconto
"""
preco = float(input('Digite o preço original: '))
NovoPreco = preco - (preco * 5 / 100)
print(f'Preço original: {preco} Preço desconto: {NovoPreco}')
|
f79f614e0fbbf5f3af4661c2799ccfd161c85839 | DanielMoscardini-zz/python | /pythonProject/Curso Em Video Python/Mundo 2/Aula 14.py | 182 | 3.890625 | 4 | #Parando uma repetição "continúa" com o break
s = n = 0
while True:
n = int(input('Digite um numero: '))
if (n == 999):
break
s += n
print(f'A soma vale {s}')
|
9185b03e8ca8eb1fd6fea13816e65e70b5ef3a18 | DanielMoscardini-zz/python | /pythonProject/Curso Em Video Python/Mundo 1/ex020.py | 519 | 3.796875 | 4 | """
O professor do exercício anterior, quer sortear a ordem de apresentação de trabalho dos alunos. Faça um software que
leia o nome dos quatro alunos e mostre a ordem sorteada.
"""
import random
aluno1 = str(input('Qual o nome do 1ºaluno: '))
aluno2 = str(input('Qual o nome do 2ºaluno: '))
aluno3 = str(input('Qual o n... |
3adce69a39a43e3475c65718edcd16207e87f3ba | DanielMoscardini-zz/python | /pythonProject/Curso Em Video Python/Mundo 2/ex041.py | 849 | 4.03125 | 4 | """
A confederação nacional de natação precisa de um programa que leia o ano de nascimento de um atleta e mostre sua
categoria de acordo com a idade:
-até 9 anos: MIRIM
-até 14 anos: INFANTIL
-até 19 anos: JUNIOR
-até 25 anos: SENIOR
-acima: MASTER
"""
#Entrada de dados:
import datetime
anoNasc = int(input('Em que ano ... |
01b3e06f560ba3a7dd9e33c9b81180ee1a110b38 | DanielMoscardini-zz/python | /pythonProject/Curso Em Video Python/Mundo 1/ex002.py | 144 | 3.734375 | 4 | # Faça um software que leia um nome e retorne uma mensagem de boas vindas
nome = input('Digite seu nome:')
print('Bem Vindo, {}'.format(nome))
|
95b6486f659b86d6f330a5cb1e5d53a5e201bf19 | lindong4067/python-demo | /practice/SQLite_02.py | 1,368 | 3.625 | 4 | # -*- coding: utf-8 -*-
import os, sqlite3
# 清库
db_file = os.path.join(os.path.dirname(__file__), '../test.db')
if os.path.isfile(db_file):
os.remove(db_file)
# 初始化数据
conn = sqlite3.connect(db_file)
cursor = conn.cursor()
cursor.execute('create table user(id varchar(20) primary key, name varchar(20),... |
962a2bd9503dca164277c99202bde083dd21d27c | UCHMS19-20/final-project-animal-crossing | /examples/pygame-basics/events.py | 669 | 3.6875 | 4 | import sys
import pygame
# Initialize pygame so it runs in the background and manages things
pygame.init()
# Create a display. Size must be a tuple, which is why it's in parentheses
screen = pygame.display.set_mode( (200, 150) )
print(pygame.QUIT)
# Main loop. Your game would go inside this loop
while True:
# do ... |
00e2144a76b9f36e6b797e8640bc81dd09c8928d | anonymouscollective/minihack-ued | /envs/minihack/adversarial.py | 14,265 | 4.03125 | 4 |
"""An environment which is built by a learning adversary.
Has additional functions, step_adversary, and reset_agent. How to use:
1. Call reset() to reset to an empty environment
2. Call step_adversary() to place the goal, agent, and obstacles. Repeat until
a done is received.
3. Normal RL loop. Use learning agent ... |
8fa817f658b41429432afb54b087f4fc14b5e322 | ters81/codeforces.com | /A. Петя и строки (elif).py | 151 | 3.78125 | 4 | a = str(input())
b = str(input())
a = a.lower()
b = b.lower()
if a == b:
print('0')
elif a < b:
print('-1')
else:
print('1')
|
f88e9607cde3cd0629bf184b5755a656ce2513f1 | ters81/codeforces.com | /A. Выращиваем бактерии.py | 89 | 3.765625 | 4 | x = int(input())
y=0
while x>0:
last=x%2
y=y+last
x=x//2
print(y)
|
c1d2ead5ebc74b978187480779f5b88387632fef | dwemple/IncrementalDemo_py | /runnable.py | 5,075 | 3.53125 | 4 | # %%
# Little something to try out and test the calculations for possible future incremental games
# Press Spacebar to simulate a "click",
# "b" to buy items, "u" to see all upgrades,
# press "X" to exit (have to press Enter to confirm the input)
# Tested on VSCode interactive mode for python
import time as t
import... |
bd1457cf855018859a1f0ea37a49f192eaf8c7ed | oobazuaye/CS-Research-Summer-2011 | /hw4pr4/hw4pr4.py | 2,194 | 3.515625 | 4 |
# createBinaryImages.py
from cs5png import *
def testBinaryImage():
""" run this function to create an 8x8 alien image
named binary.png
"""
ALIEN = "0"*8 + "11011011"*2 + "0"*8 + "00001000" + \
"01000010" + "01111110" + "0"*8
# this function is imported from cs5png.py
NUM_ROW... |
5ca25ed614f555aafea6e99d039ae06c3e73a9b5 | taingmat/pokemonss-autobreeder | /bin2c.py | 1,223 | 3.515625 | 4 | #!/bin/python
import sys, getopt
def main(argv):
opts, args = getopt.getopt(argv, "hi")
invertColormap = False
for opt, arg in opts:
if opt == '-h':
usage()
sys.exit()
elif opt == '-i':
invertColormap = True
data = open(args[0], 'rb').read()
str_out = "#include ... |
14b04389a9bd3ccbaabac59233037fd5dbb84ac4 | sputnikW/algorithm | /leetcode/94.py | 598 | 3.78125 | 4 | # Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def inorderTraversal(self, root: TreeNode) -> List[int]:
nodes = []
curNode = root
stack = []
while stack... |
cec2971a12c15d500932fc39f44f4ae6188e3eb6 | sputnikW/algorithm | /leetcode/35.py | 434 | 3.5625 | 4 | class Solution:
def searchInsert(self, nums: List[int], target: int) -> int:
import sys
nums.append(sys.maxsize)
for i in range(len(nums) - 1):
num = nums[i]
nextBiggerNum = nums[i + 1]
if target == num:
return i
elif num < ta... |
fdf878e27d23e8c106d0eb65a2328292cfe4c160 | sputnikW/algorithm | /leetcode/58.py | 791 | 3.671875 | 4 | class Solution:
def lengthOfLastWord(self, s: str) -> int:
count = 0
showAlphabet = False
for i in range(len(s) - 1, -1, -1):
if (not showAlphabet) and s[i] == ' ':
continue
if s[i] == ' ':
break
else:
coun... |
aea315799c3f8a8164f3030225330996a7746197 | malgorzata-madej/Pola-figur-plaskich | /obliczenia.py | 1,261 | 3.8125 | 4 | from pola import *
while True:
print("""
Wybierz, figurę, której pole chcesz obliczyć:
1)Kwadratu
2)Prostokąta
3)Trójkąta
4)Trapezu
5)Rombu
6)Koła
7)Zakończ działanie programu
""")
wybor = input("Podaj nr dzialania: ")
print()
i... |
d1c7543bc62d0392e9bf528d8a90db8d4731720a | A-GHOSH-dev/ProgrammingHub | /Python/palindrome.py | 168 | 4.03125 | 4 | str=input("Enter the string:")
rev=""
l=len(str)
for i in range(l-1,-1,-1):
rev=rev+str[i]
if rev==str:
print ("Palindrome")
else:
print ("not palindrome")
|
9df40a92a11d13c4c2df8b305099d622b642585f | A-GHOSH-dev/ProgrammingHub | /Python/RockPaperScissorsGame.py | 1,648 | 4.09375 | 4 | #This is all about the Rock Paper Scissors Game using simple if,elif and else statements
#initializing a symbol for rock, paper and scissors to make it vizualize better
#at places i have added emojis like this (\U0001F44A) to make it much more interesting
#u can run this code in any python ide compiler
rock = '''
... |
633d7893e19b9f2ff7b2c870975de24be916e7dd | MargoGrinch/ITTS_test_1 | /6.py | 189 | 3.765625 | 4 | a = int(input("input a: "))
b = int(input("input b: "))
sum = 0
index = 0
for i in range(a, b, 1):
if (i % 3 == 0):
sum += i
index += 1
print(int(sum / index))
|
155764d274212572493fc23559acc86fb8033bc9 | mahespunshi/maheshpunshi | /file handling.py | 646 | 3.9375 | 4 | f = open('/Users/maheshkumar/Desktop/rsi.txt', 'r')
# print(f.readlines(2))
# print(f.readline())
#
#
# f1 = open('abc', 'a')
# f1.write("\nsomething\n")
# f1.write("Laptop\n")
# following example is reading lines one by one.
# for data in f:
# print(data)
# What if we want to write something line by line to anot... |
dde672e716965db7d837075d82cbb07eeb36327f | oagboghi2/Graphs | /projects/graph/src/graph.py | 1,505 | 3.640625 | 4 | #!/usr/bin/python
"""
Simple graph implementation compatible with BokehGraph class.
"""
class Graph:
"""Represent a graph as a dictionary of vertices mapping labels to edges."""
def __init__(self):
self.vertices = {}
def add_vortex(self, vertex, edges=set()):
if vertex not in self.vertic... |
dc4f58be511664af4da9228312aacaddd740fe57 | BlakeFreer/Chaotic-Growth-Simulation | /application.linux64/source/Population_Simulation.pyde | 2,925 | 3.796875 | 4 | # Created by Blake Freer, February 4, 2019
# Inspired by Veritasium's video: "This equation will change how you see the world"
# https://www.youtube.com/watch?v=ovJcsL7vyrk
# The simulation shows how a "population" changes according to the logistic mapfunction
# x_{n+1} = r*x_n(1 - x_n)
# Where x_{n+1} is the next gen... |
ee3615b1612d3340005a8b07a6e93bc130153591 | JanJochemProgramming/basic_track_answers | /week3/session/dicts.py | 338 | 4.25 | 4 | capitals = {"The Netherlands": "Amsterdam", "France": "Paris"}
capitals["Japan"] = "Tokyo"
for country in reversed(sorted(capitals)):
print(country, capitals[country])
fruit_basket = {"Apple": 3}
fruit_to_add = input("Which fruit to add? ")
fruit_basket[fruit_to_add] = fruit_basket.get(fruit_to_add, 0) + 1
pr... |
b3911866de644fab92a2c061c2a8a7d4535d3820 | JanJochemProgramming/basic_track_answers | /week1/exercises/exercise_1_7_1-5.py | 724 | 4.5 | 4 | # I don't expect you to put in all the extra print statement
# they are there to help follow my train of though
print(9 * "*", " + ", 9 * "*")
print(3 + 5)
print("Hello " + "world!")
print(9 * "*", " - ", 9 * "*")
print(5 - 3)
print(9 * "*", " * ", 9 * "*")
print(3 * 5)
print(3 * "Hallo")
print(9 * "*", " / ", 9 * "... |
58825a291904bde055a2ebc482ad595f0ee34a1c | oreqizer/pv248 | /01/rpn_un.py | 1,836 | 3.984375 | 4 | # In the first (short) series of exercises, we will implement a
# simple RPN (Reverse Polish Notation) evaluator. The entry point
# will be a single function, with the following prototype:
def rpn_eval(rpn):
stack = []
for e in rpn:
if e == "neg":
stack[-1] *= -1
continue
... |
8ec7c46f57e44354f3479ea02e8e0cf34aaec352 | oreqizer/pv248 | /04/book_export.py | 1,691 | 4.1875 | 4 | # In the second exercise, we will take the database created in the
# previous exercise (‹books.dat›) and generate the original JSON.
# You may want to use a join or two.
# First write a function which will produce a ‹list› of ‹dict›'s
# that represent the books, starting from an open sqlite connection.
import sqlite3... |
da7b671842c42852cffb35d863205175d305d2d4 | oreqizer/pv248 | /12/outliers.py | 5,478 | 4.03125 | 4 | # Write a function that removes outliers from an otherwise normally
# distributed data set, given as a list of 2-tuples (x, y). You can
# create random inputs for testing with ‹numpy.random.normal( mean,
# stddev, count )› and then add a few outliers manually.
import numpy as np
# What exactly constitutes an outlier ... |
069550cc3af24be180730803b35cf12504c73285 | oreqizer/pv248 | /11/volume.py | 575 | 3.9375 | 4 | # Compute the volume of an n-dimensional simplex, given as a list of
# n + 1 points. A 2D simplex is a triangle, given by 3 points, a 3D
# simplex is a 3-sided pyramid given by 4 points and so on.
# Go on to ‹histogram.py›.
def volume( pts ):
pass
from math import isclose
def test_main():
assert isclose( vo... |
e12329cc4c890015554cf9c066e17dccb8fc1f21 | oreqizer/pv248 | /reviews/hw6.from.xbrablik/numeval.py | 11,347 | 3.53125 | 4 | ## Good order of methods -- starting from 'evaluate', then adjacent methods,
## then classes. It makes it very easy to find the way around the code.
##
## Greate usage of f-strings in you error messages. They are also very
## detailed which would be great in real-world usage if this was a small
## library.
##
## You se... |
8b24ef52b3172fc4b1d348f1b4d7a48639fd4345 | oreqizer/pv248 | /hw1/shelter.py | 10,221 | 3.59375 | 4 | # Write your solution into this file.
class Exam:
def __init__(self, *, vet, date, report):
self.vet = vet
self.date = date
self.report = report
def __repr__(self):
return "Exam(vet={vet}, date={date})".format(vet=self.vet, date=self.date)
class Adoption:
def __init__(self,... |
2e2c99175d04bf9db5d0c2f7d107a52419e81ded | Gadom654/AlienInvasionGame | /Alien_invasion/ship.py | 2,043 | 3.703125 | 4 | import pygame
from pygame.sprite import Sprite
class Ship(Sprite):
"""Spaceship that will be made for player usage"""
def __init__(self, ai_settings, screen):
"""Spaceship initialization and his starting position"""
super(Ship, self).__init__()
self.screen = screen
self.ai_settings = ai_settings
#Load... |
aa95a70e97fcc084edf59e4ad7e6031c31a93dee | ankgitk/6.001-pset-answers | /pset2/paying-the-minimum.py | 1,131 | 4.0625 | 4 | balance = 4842
annualInterestRate = 0.2
monthlyPaymentRate = 0.04
def minMonthlyPayment (balance, min_rate):
'''
balance (int) -- the current unpaid balance in the account
min_rate (float) -- the minimum monthly payment rate
returns the minimum monthly payment to 2 decimal places
'''
return bal... |
b7f9602c6bfcb70c58102bef5f414559812b8353 | ankgitk/6.001-pset-answers | /pset1/counting-vowels.py | 206 | 3.828125 | 4 | s = 'azcbobobegghakl'
vowels = 'aeiou'
count = 0
for char in s:
for v in vowels:
if (char == v):
count += 1
continue
print 'Number of vowels: ' + str(count) |
a0151ddb3bc4c2d393abbd431826393e46063b89 | zachacaria/DiscreteMath-II | /q2.py | 1,356 | 4.15625 | 4 | import itertools
import random
def random_permutation(iterable, r):
"Random selection from itertools.permutations(iterable, r)"
pool = tuple(iterable)
r = len(pool) if r is None else r
return tuple(random.sample(pool, r))
# Function to do insertion sort
def insertionSort(arr):
# Traverse through... |
e30ab6055538ba45d3557ece4937d947d9891f61 | SimplyDanny/advent-of-code | /2016/day-03.py | 536 | 3.8125 | 4 | from common import print_results, read
def is_triangle(possible_triangle):
a, b, c = sorted(possible_triangle)
return a + b > c
#### Main part.
sides = list(map(int, read(__file__).split()))
row_triangles = [
sides[i:i + 3]
for i in range(0, len(sides), 3)
]
column_triangles = [
sides[i + j:i ... |
b64407a36ae8559bad4041da2c723b541c1acbee | frosty04/PythonExampleAndSimpleCode | /sasso_carta_forbici.py | 963 | 3.59375 | 4 | import random
user = None
CPU = random.choice(['sasso','carta','forbici'])
while user == None:
user = input('Scegli tra sasso, carta, forbici : ')
if user not in ['sasso','carta','forbici']:
print('Devi scegliere tra sasso, carta, forbici !')
user = None
if user == CPU:
prin... |
3a331968bd8914bd997df991366a633187396972 | mqq-marek/ProjectEuler-254 | /euler/euler_00_naive.py | 5,214 | 3.890625 | 4 | """
Euler challenge from HackerRank https://www.hackerrank.com/contests/projecteuler/challenges/euler254/problem
Initial design - Day 0
"""
import time
import math
DEBUG = False
def digits_sum(n):
"""
Returns sum of digits of number n.
For example:
digits_sum(245) = 2 + 4 + 5
:param n: n
... |
0bd555cf153d0b45898e72b125e7b1be50e2b6ca | crummy/exercism | /python/word-count/word_count.py | 369 | 3.640625 | 4 | from collections import Counter
import re
def count_words(sentence):
words = re.split(r"[\s,_]+", strip(r"\W", sentence.lower()))
stripped = list(map(lambda word: strip(r"\W", word), words))
return Counter(stripped)
def strip(regex, word):
stripped = re.sub(f"^{regex}+", "", word)
stripped = re.su... |
b89578c2f52fc9a1fdb05005d2ca8aecd3425fe1 | guffy020/ideration | /problem2.py | 740 | 3.796875 | 4 | #Uhhh, DAT WAY
from random import randrange
low=1
high=1001
secret=int(raw_input("We are going to play high or lower again but this time the computer is guessing!\nInput a secret number from 1 to 1000\n>"))
numberguess=randrange(1,1000)
if(secret<1 or secret>1000):
secret=int(raw_input("Error 403: Enter a number betwee... |
c01fb6553cc8b60009b41100d98400a2fe92213b | heidecjj/advent-of-code-2020 | /day02/password.py | 832 | 4 | 4 | import argparse
from collections import namedtuple
import re
parser = argparse.ArgumentParser()
parser.add_argument('fname')
args = parser.parse_args()
password = namedtuple('password', 'min max letter password')
def parse_password(line):
mi, ma, letter, passwd = re.match(r'([0-9]+)-([0-9]+) ([a-zA-Z]): (.*)\s*'... |
b9a4bac7f3ea3bff6e834a9354a3d7911a9647ed | swapnilg77/bricksmash | /main.py | 5,437 | 3.6875 | 4 | import pygame
class paddle:
def __init__(self,x_pos,y_pos,width,height,velocity):
self.x = x_pos
self.y = y_pos
self.w = width
self.h = height
self.v = velocity
def draw(self):
pygame.draw.rect(window,(255,255,255),(self.x,self.y,self.w,se... |
0c4614bfe4fe8df78d1d95b09c0944c2971fd99e | ehzawad/pythonThree | /mario.py | 557 | 3.953125 | 4 | def mario(n=2):
for row in range(n):
for col in range(n):
if row + col < n - 1:
print(' ', end='')
else:
print('#', end='')
print('#')
# mario(10)
# If you want to call like C
if __name__ == '__main__':
mario(10)
# python magic
print('\... |
65501be0829befc69fdbd4c8e0b310b2c4d801a4 | ehzawad/pythonThree | /matrix.py | 276 | 3.546875 | 4 | import numpy
x = numpy.ones(3)
m = numpy.eye(3)
print(x)
print(m)
print(x @ m)
# this is actually list
y = [[1, 2, 3],
[2, 3, 4],
[5, 6, 9]]
print(y)
l = [[2, 2, 2]]
print(l)
# TypeError: unsupported operand type(s) for @: 'list' and 'list'
# print( y @ l)
|
eb8bd623a2b482318fafd7ffb7772bca195514a1 | annarazgulova/Python | /count_words.py | 745 | 4.09375 | 4 | '''
find frequency of word in text:
'''
str = "aaa bbb ccc aaa bbb kkk aaa"
def count_words(str):
list = str.split(" ");
dic = {}.fromkeys(list,0)
for word in list:
dic[word]+=1
print(dic)
count_words(str)
"""
Find sum of all numbers in the string 'sdf2tg dff234hh d999njk1hj'
sum = 1236 (2 + ... |
49a02e54c4e4d95e4fb06ef8a85ecc4c0534c2f7 | Ianashh/Python-Testes | /Curso em vídeo/Ex060.py | 665 | 4.34375 | 4 | # Obs.: usar # nas linhas do "for" (Passo 2.1) ou nas linhas do "while" (Passo 2.2) para anular um ou outro programa e obter o resultado correto.
# Passo 1: Criar variáveis
n = int(input('Digite um número para descobrir seu fatorial: '))
cont = n
esc = n
# Passo 2.1: Usar o "for" para o fatorial
for n in range(n,1,-1... |
6075c78fa5543566fe71c4cefb3b444ac9c7a35e | tanyastropheus/holbertonschool-higher_level_programming | /0x04-python-more_data_structures/102-complex_delete.py | 167 | 3.625 | 4 | #!/usr/bin/python3
def complex_delete(my_dict, value):
for (k, v) in list(my_dict.items()):
if v == value:
del my_dict[k]
return (my_dict)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.