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 |
|---|---|---|---|---|---|---|
6cf28a3c64d1f78d924310f72eaa3356971b26d0 | Skotmak/Homeworks | /hw6/hw6.py | 1,210 | 3.90625 | 4 | class First:
color = "red"
def out(self):
print (self.color + "!")
obj1 = First()
obj2 = First()
print (obj1.color)
print (obj2.color)
obj1.out()
obj2.out()
class Second:
color = "red"
form = "circle"
style = "cool"
def changecolor(self,newcolor):
self.color = newcolor
de... |
9a754b62a6605515a498d0bb3257c3348d29f838 | jdgsmallwood/ProjectEuler | /project_euler_solutions/problem_3.py | 944 | 3.75 | 4 | import math
target_num = 600851475143
#target_num = 10
def get_primes(n):
primes = [False,False]+[True for i in (range(2,n+1))]
for num in range(2,n+1):
print(num)
if primes[num]:
control = True
i=0
while control:
if num**2+i*num <= n:
... |
cb6d20c4cdb6afa7fedda5930b77e027aa690ed5 | jithendra9582/code | /Deduplicate.py | 397 | 3.71875 | 4 | my_str = input("Enter a string: ")
my_str = my_str.lower();
words = my_str.split(" ");
print("Duplicate words in a given string : ");
for i in range(0, len(words)):
count = 1;
for j in range(i+1, len(words)):
if(words[i] == (words[j])):
count = count + 1;
words[j... |
0c0e2de9c441f338169c5d08b4e8de78e4f2f01f | mehwaffle10/sdp-group-3 | /Hub/get_mac_addresses.py | 292 | 3.5 | 4 |
import bluetooth
# Scan for nearby devices
print('Scanning for nearby devices')
nearby_devices = bluetooth.discover_devices()
# Printout all found devices
for bluetooth_device_address in nearby_devices:
print(bluetooth.lookup_name(bluetooth_device_address), bluetooth_device_address)
|
4e783c391c9455c813790339864fc12e82c68d41 | ruchirbhai/Trees | /N-aryTreeLevelOrderTraversal_429.py | 2,719 | 3.90625 | 4 | # https://leetcode.com/problems/n-ary-tree-level-order-traversal/
# Given an n-ary tree, return the level order traversal of its nodes' values.
# Nary-Tree input serialization is represented in their level order traversal, each group of children is separated by the null value (See examples).
# Example 1:
# Input: ro... |
2c49ef300a9d5a6b783f103e064132f222fe4977 | ruchirbhai/Trees | /PathSum_112.py | 2,125 | 4.15625 | 4 | # https://leetcode.com/problems/path-sum/
# Given a binary tree and a sum, determine if the tree has a root-to-leaf path such
# that adding up all the values along the path equals the given sum.
# Note: A leaf is a node with no children.
# Example:
# Given the below binary tree and sum = 22,
# 5
# / \
# ... |
d1e2289b0a0658e47724d1e2112afe0127244a5e | 44858/variables | /adding 4 integers.py | 437 | 3.90625 | 4 | #Lewis Travers
#12/09/14
#Revision Exercises
first_integer = int(input("Please enter your first integer: "))
second_integer = int(input("Please enter your second integer: "))
third_integer = int(input("Please enter your second integer: "))
fourth_integer = int(input("Please enter your second integer: "))
fin... |
58118aa6dac147138a91cdfb393ddf328be961b0 | 44858/variables | /multiplication and division.py | 484 | 4.34375 | 4 | #Lewis Travers
#12/09/2014
#Multiplying and dividing integers
first_integer = int(input("Please enter your first integer: ")
second_integer = int(input("Please enter an integer that you would like the first to be multiplied by: "))
third_integer = int(input("Please enter an integer that you would like the total... |
3c0415d43f319d0be4a8b69f161f23cfeb2e66af | georgeholt1/epoch-generate-particles-files | /distributions/d2.py | 547 | 3.515625 | 4 | # Author: George K. Holt
# License: MIT
# Version: 0.1
"""
Part of EPOCH Generate Particles Files.
This file should contain a 2-dimensional particle number density distribution as
a Python function called number_density_2d.
"""
import numpy as np
def gaussian(x, x0, w):
'''A simple Gaussian function centred on x... |
03bbea5bd2bdb8d59c55821227706bd7f826e494 | MarLisiecki/markdown_table_gen | /markdown_gen/markdown_gen.py | 4,343 | 3.609375 | 4 | from pathlib import Path
class MarkDownTableGenerator:
def get_project_root(self) -> Path:
"""
Function which return a path for the project, which will help to generate markdown output file.
Returns:
object: Path
"""
return Path(__file__).parent.parent
def... |
85ca773d54ae7f71606b29e2188629a3a217b0e2 | AshwinHarish/Algorithms | /BFS.py | 606 | 3.609375 | 4 | # BFS
graph={
1:[2,3],
2:[1,3,4,5],
3:[1,2,6,7],
4:[2,5,8,9],
5:[2,4,9],
6:[3,7],
7:[3,6],
8:[4,9],
9:[4,5,8,10],
10:[9]
}
visited = [0]*10
queue = []
def bfs(source):
visited[source-1] = 1
queue.append(source)
... |
e039903ad841d8e4d5acc50e12bb727c633d23de | ElinaKatariina/Salary | /month_salary.py | 483 | 3.75 | 4 | import os
import re
def monthly_sal():
count_file = 'counted.txt'
x = []
file_in = open('counted.txt', 'r')
for y in file_in.read().split('\n'):
x.append(float(y))
sal = sum(x)
month = input("Enter month (Jan-Dec): ")
month_sum = open("months_sal.txt", "a")
month_sum.... |
991771e030841ddb0b2c6164c5774245626c44cf | LeonardoSaes/Exercicios-python-basico | /python básico/desafio08.py | 343 | 3.765625 | 4 | # calcula quantos livros prrecisará para pintar uma parede
largura = float(input('Digite a largura da sua parede em metros: '))
altura = float(input('Digite a altura da sua parede em metros: '))
area = largura * altura
litros = area / 2
print('A área da sua parede mede {} m² e precisará de {} litros para pinta-la '.for... |
dd828f26fae4e184e8ecf3626aba2d114a007e9a | LeonardoSaes/Exercicios-python-basico | /python básico/desafio33.py | 869 | 3.734375 | 4 | # empréstimo bancário
from time import sleep
print('-' * 40)
print(' {}EMPRESTIMO BANCÁRIO{}'.format('\033[1;34m', '\033[m'))
print('-' * 40)
casa = float(input('Digite o valor da casa:R$ '))
salario = float(input('Digite o seu salário:R$ '))
salario30 = (salario * 30) / 100
anos = int(input('Digite em quantos a... |
df74d838b70e1f47905aeea2f96e1be1c784e8f5 | LeonardoSaes/Exercicios-python-basico | /python básico/desafio42.py | 2,450 | 3.75 | 4 | # PEDRA, PAPEL OU TESOURA
from random import choice
from time import sleep
print('-' * 33)
print('{}{:^32}{}'.format('\033[1;34m', 'JOKENPÔ', '\033[m'))
print('-' * 33)
n1 = str(input('{}PEDRA, PAPEL OU TESOURA?{} '.format('\033[1;36m', '\033[m'))).upper()
lista = ['PEDRA', 'PAPEL', 'TESOURA']
# sorteia um elemento da... |
f3ca92b9d98e40f4618fbbd47b12ddf2a6c7bbdb | LeonardoSaes/Exercicios-python-basico | /python básico/desafio24.py | 379 | 3.78125 | 4 | # mostra seu primeiro e último nome
nome = str(input('Digite seu nome completo: ')).strip()
n = nome.split()
print('-' * 60)
print('Muito prazer em te conhecer, {}{}{}'.format('\033[1;34m', nome, '\033[m'))
print('Seu primeiro nome é {}{}{}'.format('\033[1;33m', n[0], '\033[m'))
print('Seu último nome é {}{}{}'.format(... |
5abcbb478ce5d05bc54e892bbedc105313932415 | LeonardoSaes/Exercicios-python-basico | /python básico/desafio19.py | 490 | 4.03125 | 4 | # mostra seu nome em maiusculo, minusculo, quantidade de letras total e do 1º nome
nome = input('Digite o seu nome completo: ')
maiusculo = nome.upper()
minusculo = nome.lower()
letras = len(nome.replace(' ', ''))
nprimeiro = nome.split()
letrasq = len(nprimeiro[0])
print('-' * 40)
print('Nome em maiúsculo: {}\nNome em... |
c61ef63f6e6ec0e3de7967c3dd42eda5d06531b2 | LeonardoSaes/Exercicios-python-basico | /python básico/desafio50.py | 482 | 3.984375 | 4 | # verifica se o número digitado é um número primo ou não
numero = int(input('Digite um número inteiro: '))
mult = 0
for c in range(1, numero + 1):
if numero % c == 0:
print('\033[33m', end='')
mult += 1
else:
print('\033[31m', end='')
print('{} '.format(c), end='')
print('\n\033[mO n... |
5c1297fea61c8bd18de6034e912e4acb21977d13 | LeonardoSaes/Exercicios-python-basico | /python básico/desafio49.py | 402 | 3.859375 | 4 | # lê o primeiro número de uma progressão aritmética e sua razão, depois mostra os primeiros 10 números dessa PA
print('=' * 51)
print('{:^50}'.format('10 TERMOS DE UMA PA'))
print('=' * 51)
primeiro = int(input("Digite o 1º termo: "))
razao = int(input('Razão: '))
decimo = primeiro + (10 - 1) * razao
for c in range(pri... |
9995de8314efb0c98d03f0c893bb7b7ddbbfd239 | jjsherma/Digital-Forensics | /hw1.py | 2,967 | 4.3125 | 4 | #!/usr/bin/env python
import sys
def usage():
"""Prints the correct usage of the module.
Prints an example of the correct usage for this module and then exits,
in the event of improper user input.
>>>Usage: hw1.py <file1>
"""
print("Usage: "+sys.argv[0]+" <file1>")
sys.exit(2)
def getFi... |
efe8c655b0258b5953b68dcf403bb271ee94f776 | tday93/txtadv | /game/helpers/input_parse.py | 1,895 | 3.765625 | 4 | """ this translates the players input into a call to an action
do_action should take form:
do_action(self, act-er, target, use_text, *args, **kwargs)
example player input:
"move door"
"use item_name"
"attack enemy_name"
Action Tar... |
2f9c1a23384af6b52ab218621aa937a294a6b793 | bainjen/python_madlibs | /lists.py | 895 | 4.125 | 4 | empty_list = []
numbers = [2, 3, 5, 2, 6]
large_animals = ["african elephant", "asian elephant", "white rhino", "hippo", "guar", "giraffe", "walrus", "black rhino", "crocodile", "water buffalo"]
a = large_animals[0]
b = large_animals[5]
# get the last animal in list
c = large_animals[-1]
# return index number
d = lar... |
571cd36dbc353930e982ee81290bbdadb7acbe94 | rosekairu/Password-Locker | /user.py | 1,825 | 4.0625 | 4 | from credential import Credential
class User:
"""
a class that generates new instances of users
"""
pass
users_list = []
def __init__(self, first_name, last_name):
'''
__init__ method that helps us define properties for our users.
'''
self.first_name = first_... |
d47fa402e4d6f2d6bd148cb424c1a9cd34e4b2cd | acunit/try-python-codeschool | /level2.py | 3,556 | 4.46875 | 4 | # Level 2 of Intro To Python (CodeSchool.com)
# First script made to test on terminal
first_name = 'Monty'
last_name = 'Python'
full_name = first_name + ' ' + last_name
print(full_name)
# Describe the sketch comedy group
name = 'Monty Python'
description = 'sketch comedy group'
year = 1969
# Introduce them
sentence ... |
718e8aec118b7aaafe59d9c70370ed5893a1d19f | ravenusmc/aleppo_main | /platforms.py | 3,085 | 3.96875 | 4 | #The code in this file will be dealing with the platforms in the game.
#Importing other modules that will be used in this file.
import pygame
from spritesheet_functions import SpriteSheet
#These are the platforms that will be used in the game. The first two numbers
#are the x,y location of the image on the sprite she... |
423fce215596d87146dd016ad3cd9b7a51cf9895 | dasha108219/PROGR | /hw6/try-random.py | 2,872 | 4.21875 | 4 | print('ВАРИАНТ 2')
print('Текст должен представлять собой стихотворение на русском языке из четырёх строк без рифмы, но написанное с соблюдением одной метрической схемы, кроме трёхстопного анапеста- трехстопный дактиль')
print()
import random
with open('noun_sg.txt') as file:
file = file.read().split(' ')
... |
844b8d7658a864f6ab5cf517671571d2e26a41bb | dasha108219/PROGR | /hw5/6lesson.py | 445 | 3.75 | 4 | print('ВАРИАНТ 2')
print()
print('Введите свои слова: ')
with open("new.txt", "w", encoding = "utf - 8") as file:
word = input()
while word != "":
if len(word) > 5:
file.write("\n") #чтобы new word записывалось с новой строки
file.write(word)
word = input()
wi... |
ecaf3ad9e1612a38c4de7430bfcccfa6c4b00ce2 | dasha108219/PROGR | /bonus/bonus5.py | 544 | 3.984375 | 4 | print('ЗАДАЧА 5 - Aigy Paigy')
a=input('Введите слово или фразу: ')
result=''
cons='abcdfghjklmnpqrstvwxyz'
for letter in a:
if (letter == ' ') or(letter == 'a') or (letter == 'e') or (letter == 'i') or (letter == 'o') or (letter == 'u') or (letter == 'y'):
result += letter
else: ... |
bfb8a959363a312f0e88f4c7e9a067ba845cf395 | gy15rt/Assignment1 | /Model_home.py | 4,102 | 3.75 | 4 | # -*- coding: utf-8 -*-
"""
Created on Thu Sep 21 09:03:12 2017
@author: gy15rt
"""
import csv
import random
import operator
import matplotlib.pyplot
import agentframework_home as agentframework
import sys
import matplotlib.animation
# a new empty list to contain the environment data from the csv file
... |
f4f4fdd6a78137cf1bd6d0a381de5d658614a07f | prog1821/jypter-lab | /recursion.py | 147 | 3.90625 | 4 | def fact (n) :
if n==0 :
return 1
return n*fact(n-1)
m=int(input("enter the number : "))
result=fact(m)
print(result) |
cc63213498ca770ec1d16a561b299fc5306c84c6 | prog1821/jypter-lab | /count.py | 321 | 3.890625 | 4 |
def count(lst):
even =0
odd=0
for i in lst :
if i%2==0 :
even=even+1
else :
odd=odd+1
return even,odd
lst=[12,13,16,54,22,56,43,445,333,5667]
even,odd=count(lst)
print("even : {} and odd : {} ".format(even,odd))
print(even)
print(odd... |
14d704450e5f8716cf0d555a815ca58e3e845bd5 | KapplDw/CS362_inclass_activity_2 | /T2/unittests.py | 360 | 3.5625 | 4 | import unittest
import wordCount
class wordCountTestCase(unittest.TestCase):
def test_count(self):
self.assertEqual(wordCount.lengthSent("This is an activity"), 4)
self.assertEqual(wordCount.lengthSent("Testing a longer senctence than four words long."), 8)
self.assertEqual(wordCount... |
5d1eeaba8820480afa2e45d7a05eea158fec6c24 | LosLoboDev/DailyCodingProblem | /DCP1/SumFromList.py | 1,506 | 3.859375 | 4 | #date:7.24.18
#LosLoboDev
#returns a list of sums of the numbers in paramlist
def initSumsList(paramlist):
list_of_sums = []
i=0
j=i+1
while i < len(paramlist)-1:
while j < len(paramlist):
list_of_sums.append(paramlist[i] + paramlist[j])
j+=1
i+=1
j=i+1... |
81b98f26ad88cc71887ec483e96930213881e665 | longpengcs/leetcode | /python/strMatch/sunday.py | 809 | 4.03125 | 4 | """sunday is a very easy algorithm,same as brute force,it match every character
in pattern and target,when it find two different character,it find a character
from right to left which same as the match target's next character.
abcdefg ==> abcdefg
cde ==> cde
a != c and we find a 'd' in 'cde'... |
b58792c36e47b8ed9fd2f0faf508a9c2e233379c | shubhamshahajipol/193010036_webdev_app | /Database.py | 338 | 3.671875 | 4 | import sqlite3
db = sqlite3.connect('Registration')
rs = db.cursor()
#rs.execute('''create table Register(name varchar(50), email varchar(100), password varchar(10))''')
#db.commit()
rs.execute('''insert into Register values('shubh', '@gmail.com', 'shubham1234#')''')
db.commit()
rs.execute('select * from Register')
fo... |
2ebcd8e6816a0ebc9d4026482961c0461ac2f336 | onesuper/Easylab | /example/fib2.py | 457 | 4.03125 | 4 | #!/usr/bin/python
# O(2^N) fibonacci
import sys
import easylab.easylab as e
# read argumeny
if len(sys.argv ) < 2:
print "wrong arguments"
sys.exit(1)
N = int(sys.argv[1])
easylab = e.Easylab("fib2")
easylab.start()
# go
def fibonacci(n):
return n>=2 and fibonacci(n-2)+fibonacci(n-1) or n
r = fibonac... |
007be9e408ef9879531848eca536c26c3766021f | wesleyrodrigues/linguagens_programacao | /002.Python/integer_and_ float.py | 1,403 | 3.796875 | 4 | x = 10
y = 5
x + y == 15 # Adição
x - y == 5 # Subtração
x * y == 50 # Multiplicação
x / y == 2.0 # Divisão (float)
x // y == 2 # Divisão (inteira)
x % y == 0 # Resto da divisão
-x == -10 # operador negativo
+x == 10 # operador positivo
x ** y == 10... |
4703b6f68f79771e8d90022fa2a4584b47c5c169 | Elevationacademy/python-class-and-home-flow-control-Yazanabbasi96 | /cards.py | 380 | 3.625 | 4 | import random
class Card:
def __init__(self):
card_color = ['red', 'blue', 'green', 'yellow']
self.type = random.choice(card_color)
card_number = [x for x in range(1, 10)]
self.number = random.choice(card_number)
def __iter__(self):
return self.type , self.number
... |
7879e0dd0734511f2c5abc2e65b1b065ed4bc5d8 | trungtv4597/Python_Exercises | /chapter3.py | 4,149 | 3.96875 | 4 | # 1: Qui đinh các ngày trong tuần từ cn tới t7 là 0,1,2,3,4,5,6. Việt một chương trình hỏi số của một ngày vè in ra tên của ngày đó.
day_number = int(input("từ 0 tới 6, số thứ tự của một ngày trong tuần bạn yêu cầu là bao nhiêu: "))
if day_number == 0:
print('câu 1: sunday')
elif day_number == 1:
print('câu 1... |
4bcd2c50b92f753bbe9507245575b053750820a2 | alexeimarcilio/GBC | /week02/PPractice4.py | 2,979 | 3.515625 | 4 | # Info:
# Author:
# Date
# Purpose:
# inputs:
# outputs:
# Version control:
import numpy as np
#------------------------------------------------------------------------------
# Mean, Median and mode
x = np.array([1, 2, 3, 4, 5])
y = np.array([2.3, 2.1, 30, 4.1, 6.6, 13])
a_mean = np.mean (y)
print ("the mean i... |
f4a270fac679cc176b09b24b9925ff3876e1930c | 10639780/proti | /testing/testelements.py | 121 | 3.875 | 4 | list1 = [1, 2, 3, 4, 5]
list2 = [6, 7, 8, 9, 10]
list3 = list(zip(list1, list2))
print(list3)
print(list3.index((4, 9))) |
36e830aa4a52c6f8faa1347722d1dab6333088c8 | tom1mol/core-python | /test-driven-dev-with-python/refactoring.py | 1,197 | 4.3125 | 4 | #follow on from test-driven-development
def is_even(number):
return number % 2 == 0 #returns true/false whether number even/not
def even_number_of_evens(numbers):
evens = sum([1 for n in numbers if is_even(n)])
return False if evens == 0 else is_even(evens)
""" this reduc... |
e8967d61c40fbad78ea14947609433398cd69e29 | Ken10A/python-security-programming | /chapter05/common_mod_atk.py | 758 | 3.625 | 4 | #!/usr/bin/python
# -*- coding:utf-8 -*-
import click
def ex_gcd(a, b):
if a == 0:
return (b, 0, 1)
else:
gcd, x, y = ex_gcd(b % a, a)
return (gcd, y - int(b / a) * x, x)
def solve(c1, c2, e1, e2, N):
_, s1, s2, = ex_gcd(e1, e2)
if s1 < 0:
_, c1, _ = ex_gcd(c1, N)
... |
cb9daa0c0a006e72d73a5009991d50058a813af5 | Ken10A/python-security-programming | /chapter05/low_e_atk.py | 558 | 3.515625 | 4 | #!/usr/bin/python
# -*- coding:utf-8 -*-
import click
def solve(cipher, e):
plaintext = []
for c in cipher:
m = int(round(c ** (1. / e)))
plaintext.append(chr(m))
return ''.join(plaintext)
@click.command()
@click.argument('e', type=int)
def run(e):
cipher = [
373248, 1157... |
b2e1fe269cbae3db8a2c8ad0bb88342e66385898 | dispatchedx/Challenges | /codewars/6 kyu/Count_characters_in_your_string.py | 242 | 3.671875 | 4 | def count(string):
if string == '':
return {}
else:
dict_alpha = {}
for c in string:
if c in dict_alpha:
dict_alpha[c] +=1
else:
dict_alpha[c] = 1
return dict_alpha |
96628dbf0a4f24070753f8eebe15f29a0c5fa7f2 | dispatchedx/Challenges | /codewars/5 kyu/Pascal's_Diagonals.py | 609 | 3.890625 | 4 | def generate_diagonal(n, l):
"""
really slow cause it sums array in a nested for
better to just generate the last array by definition like:
return [factorial(n+i) // (factorial(n) * factorial(i)) for i in range(l)]
:param l: line we end at (start from 0)
:param n: number of diagonal (start from... |
8ce5910a28d550db26b9634a2e9b2863e75cf9e3 | dispatchedx/Challenges | /codewars/1 kyu/Faberge_easter_eggs_crush_test_[linear].py | 1,768 | 3.6875 | 4 | import time
MOD = 998244353
def height(n, m):
"""
:param n: number of eggs
:param m: number of tries
:return: total number floors
"""
floor = 1 # recurrence variable
total_floors = 0 # sum variable
inverse_arr = [1] # array of inverses till n
# calculate first floor here so th... |
4c70bb91c0e2537c07864c9e5407a09e4b82c0a5 | dispatchedx/Challenges | /codewars/4 kyu/Human_readable_duration_format.py | 1,933 | 3.984375 | 4 | import math
def format_duration(seconds):
time = ''
year = 31536000
day = 86400
hour = 3600
minute = 60
if seconds == 0:
time = 'now'
if seconds >= 2 * year:
time += str(seconds // year) + ' years'
seconds = seconds % year
if seconds > 0:
time +=... |
bc547b6f91f5f3133e608c4aa479eb811ddf7c58 | sgspectra/phi-scanner | /oldScripts/wholeFile.py | 835 | 4.40625 | 4 | # @reFileName is the name of the file containing regular expressions to be searched for.
# expressions are separated by newline
# @fileToScanName is the name of the file that you would like to run the regex against.
# It is read all at once and the results returned in @match
import re
#reFileName = input("Please ente... |
ab715c78d5ef039c4d74546d01c545d6a8e3dded | ramongonze/ufmg-practical-assignments | /natural-computing/genetic-programming/constants.py | 2,302 | 3.734375 | 4 | import math
import operator
import random
# Seed used to control the tests
random.seed()
# A set of nodes composes a binary tree
class Node(object):
def __init__(self, item, right=None, left=None, level=1):
self.right = right # Right child
self.left = left # Left child
self.item = item
self.level = level # T... |
59c0563a84d4152d82a9df3aed6266ead80ea67a | juicyslew/TextMining | /TutorialTest.py | 768 | 3.6875 | 4 | import requests
import pickle
import wikipedia
#print(requests.get('http://google.com').text)
#oliver_twist_full_text = requests.get('http://www.gutenberg.org/ebooks/730.txt.utf-8').text
#print(oliver_twist_full_text)
"""olin = wikipedia.page("Olin College")
# Save data to a file (will be part of your data fetching ... |
f4353e98ea3dc3b5d1893a4c25be0b88b5c132e8 | s2012975/pygame | /shoot/shoot.py | 573 | 3.59375 | 4 | from random import randint
apple = Actor("apple")
banana = Actor("banana")
def draw():
screen.clear()
apple.draw()
banana.draw()
def place():
apple.x = randint(100, 700)
apple.y = randint(100, 500)
banana.x = randint(100, 700)
banana.y = randint(100, 500)
def on_mou... |
4173f1396378914b87aa5e79f11ea5e54c66384b | mojd1234/yes | /grggeteg.py | 70 | 3.953125 | 4 | name = input("Hey, what's you're name?")
print("hello, " + name + "!") |
2b75d7efda15ae7ff70cb803b1d1ac6f85486c21 | masimpson123/portfolio | /sketches/python/pythonHelloWorld.py | 310 | 4.03125 | 4 | name = input("What is your name? ")
def checkName(name):
checkName = input("Is your name " + name + "? ")
if checkName.lower() == "yes":
print("Hello,", name)
else:
print("We're sorry about that.")
def occupation():
name = input("What is your job? ")
occupation()
checkName(name) |
fedda3bd5f7e45025d91e87c2f80c1ee4dd59a61 | GustavoMarks/n-recursive-mergesort | /mergesort.py | 1,026 | 3.875 | 4 | # Implementação de um algoritmo não recursivo de mergesort
def mergesort(vetor):
block = 1
n = len(vetor)
while block < n:
i1 = 0
i2 = block
while i2 < n:
outputvetor = join(vetor[i1:i2], vetor[i2:(i2 + block)])
# sobrescrevendo vetor original
i = 0
x = i1
while x < i2 +... |
b28a938c098b5526fb6541b41f593d30a665b185 | elguneminov/Python-Programming-Complete-Beginner-Course-Bootcamp-2021 | /Codes/StringVariables.py | 1,209 | 4.46875 | 4 | # A simple string example
short_string_variable = "Have a great week, Ninjas !"
print(short_string_variable)
# Print the first letter of a string variable, index 0
first_letter_variable = "New York City"[0]
print(first_letter_variable)
# Mixed upper and lower case letter variable
mixed_letter_variable = "ThI... |
e43192f5cbcc6f13c910435746a78154721f79c8 | DanielYTChen/python-code | /2_iO/sum.py | 364 | 3.5625 | 4 | import sys
def sum_lines():
for line in sys.stdin:
line = line.strip() #??
print(line)
token = line.split() #??
#print(token)
#print(len(token))
total=sum([float(token) for token in token])
total=0
for i in range(0,len(token)):
total+=floa... |
2edd0f82377edb20cf6de9c3a9c7a9f3f8dd2eb7 | DanielYTChen/python-code | /2_iO/number.py | 378 | 3.9375 | 4 | def readInput():
line1 = input()
line2 = input()
line3 = input()
num1= int(line1)
num2= int(line2)
num3= int(line3)
print(num1 + 1)
print(num2 + 1)
print(num3 + 1)
readInput()
def readInput2():
line = input()
cnt = int(line)
for i in range (0,cnt):
line = input()... |
a674accdcb9a0081f6ebf7f506c886c4a65fb575 | vernor1/carnd_advanced_lane_finding | /binary_thresholding.py | 5,269 | 3.828125 | 4 | import cv2
import numpy as np
def GetSobelBinary(channel, orient='x', sobelKernel=3, thresh=(0, 255)):
""" Applies the Sobel-function to a channel image and generates the binary image.
param: channel: 2D array of the image channel
param: orient: Axis for the derivative, 'x' or 'y'
param: sobelKernel:... |
54c1993be182e323a7b9018fe0a63ac7d98330c4 | saniaahmad9/Ahmad_DataBootCampHW | /Homework 03/PyPoll/main.py | 1,130 | 3.53125 | 4 | import csv
poll_data = "/Users/saniaahmad/Desktop/GWARL201906DATA1/02-Homework/03-Python/Instructions/PyPoll/Resources/election_data.csv"
votes = 0
winner_votes = 0
candidates = 0
candidate_choice = []
candidate_votes = {}
with open(poll_data) as poll_data:
reader = csv.DictReader(poll_data)
for row in rea... |
7f2f13af9d3a45194a769b70948fcd4df6cacd42 | SuryankDixit/LeetCode_Algorithms | /Python/Binary_Tree_Inorder_Traversal.py | 733 | 3.90625 | 4 | #LeetCode problem link: https://leetcode.com/problems/binary-tree-inorder-traversal/
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution(object):
def in... |
8826271e0cf66090ab024a4d1d4c535fdc8158b3 | SuryankDixit/LeetCode_Algorithms | /Python/Linked_List_Cycle_II.py | 427 | 3.6875 | 4 | #LeetCode problem link: https://leetcode.com/problems/linked-list-cycle-ii/
class Solution:
def detectCycle(self, head: ListNode) -> ListNode:
node = head
val_holder = []
while(node.next is not None):
temp = node.val
val_holder.append(temp)
if node.next.... |
8f54025bdc638ce49f949af4b01c7a7d2560fa60 | tdnzr/project-euler | /Euler030.py | 687 | 3.6875 | 4 | # Solution to Project Euler problem 30 by tdnzr.
# What's the largest number I need to check? 9**5 = 59049, and 6 * (9**5) = 354294. I'll take that as my upper bound.
def run():
power_sum = 0
for testNum in range(2, 354294+1): # 1 = 1**5 is specifically excluded by the problem description.
current_s... |
86b235636779969ed5dc3317d68251421dc9ae38 | tdnzr/project-euler | /Euler098.py | 4,680 | 3.828125 | 4 | # Solution to Project Euler problem 98 by tdnzr.
from math import sqrt
from itertools import permutations # combinations returns r length subsequences of elements from the input iterable.
def is_square(n):
"""Returns True if n is a perfect square, False otherwise."""
return sqrt(n).is_integer()
def large... |
7af6c0c2499e5fca35122e558790b3c29985f515 | tdnzr/project-euler | /Euler091.py | 1,709 | 3.640625 | 4 | # Solution to Project Euler problem 91 by tdnzr.
# Pythagoras: The length of a line from (x1, y1) to (x2, y2) is equal to: sqrt((x2 - x1)**2 + (y2 - y1)**2)
# I suspect the algorithm I've used could still be somewhat improved if I could consider
# some more cases of symmetry, but it's already pretty good due to itert... |
2a2ca773cb44e1f00a3d66acd5adc6a6621f61a3 | tdnzr/project-euler | /Euler058.py | 1,576 | 3.671875 | 4 | # Solution to Project Euler problem 58 by tdnzr.
# This problem is related to problem 28.
# Instead of going through the pain of generating the spiral again,
# here I use the insight that beginning with the center (spiral side length 1),
# the corner numbers in the next spiral (side length 3) can be reached by adding ... |
7a109aa20d6831dfddf71a829089acba827adb70 | tdnzr/project-euler | /Euler038.py | 1,380 | 3.734375 | 4 | # Solution to Project Euler problem 38 by tdnzr.
# Upper limit: We need to obtain a 9-digit number by concatenating the products of a number with 1, 2, ...
# Even if we begin with the smallest possible result from a 5-digit number, namely,
# 10000 concatenated with 10000*2, we still end up with 1000020000, a 10-digit ... |
bb22470130bd2cea397fadf679bd8cb5b1726f2f | tdnzr/project-euler | /Euler034.py | 1,074 | 3.9375 | 4 | # Solution to Project Euler problem 34 by tdnzr.
# I was initially confused how I could possibly do an existence proof / identify *all* the numbers,
# without being given any bounds. However, there is a method to the madness:
# The largest factorial of a digit is 9! = 362 880, so once a number has 7 digits, its value ... |
23f11179a570b181eabb4d4955783dba610e8506 | tdnzr/project-euler | /Euler059.py | 1,718 | 3.828125 | 4 | # Solution to Project Euler problem 59 by tdnzr.
# cipher.txt is a text file in which the bytes were converted to ASCII,
# then each byte was XORed "with a given value, taken from a secret key".
from string import ascii_lowercase
def run():
# Load the cipher file and save it as a list of ordinals:
with ope... |
3a83c88d48ca19d36df0778c9212d847f3d523ce | tdnzr/project-euler | /Euler001b.py | 276 | 3.6875 | 4 | # Solution to Project Euler problem 1 by tdnzr.
# Solution with list comprehension.
def run():
total_sum = 0
for i in [j for j in range(1000) if (j % 3 == 0) or (j % 5 == 0)]:
total_sum += i
return total_sum
if __name__ == "__main__":
print(run())
|
43028ad12ed09b859606286a15909d58e1f53443 | tarushisingh/HackerRank- | /Python If-Else.py | 227 | 3.875 | 4 | #!/bin/python3
import math
import os
import random
import re
import sys
n=int(input())
if n%2!=0:
print("Weird")
elif 2<=n<=5:
print("Not Weird")
elif 6<=n<=20:
print("Weird")
elif n>20:
print("Not Weird")
|
5a1b69b57245e5852bb652d1d5829d5cdbf16f2e | jeiizou/leetcode-note | /113.路径总和-ii.py | 1,229 | 3.625 | 4 | #
# @lc app=leetcode.cn id=113 lang=python3
#
# [113] 路径总和 II
#
from typing import List
import collections
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
# @lc code=start
# Definition for a binary tree node.
getSum = sum
class Solution:
def path... |
242878924583f92c5951dbbb697ca6c205b97f51 | jeiizou/leetcode-note | /297.二叉树的序列化与反序列化.py | 2,110 | 3.8125 | 4 | #
# @lc app=leetcode.cn id=297 lang=python3
#
# [297] 二叉树的序列化与反序列化
#
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
# @lc code=start
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.va... |
1558b37db93acee36b777659133fd7f58d9ac631 | jeiizou/leetcode-note | /71.简化路径.py | 675 | 3.640625 | 4 | #
# @lc app=leetcode.cn id=71 lang=python3
#
# [71] 简化路径
#
# @lc code=start
class Solution:
def simplifyPath(self, path: str) -> str:
# 分割
pathList = path.split('/')
ans = []
# 栈
for name in pathList:
if not name:
continue
else:
... |
700c875c0347e296ec39987a32514355b59808bf | jeiizou/leetcode-note | /117.填充每个节点的下一个右侧节点指针-ii.py | 2,068 | 3.890625 | 4 | #
# @lc app=leetcode.cn id=117 lang=python3
#
# [117] 填充每个节点的下一个右侧节点指针 II
#
# class Node:
# def __init__(self, val: int = 0, left: 'Node' = None, right: 'Node' = None, next: 'Node' = None):
# self.val = val
# self.left = left
# self.right = right
# self.next = next
# @lc code=star... |
91e46798642c94a4032d095b691e829def5c965b | qrana/wordbook-console | /translation.py | 1,366 | 3.921875 | 4 | """
This module defines the Translation class.
"""
class Translation:
"""
The point of this class is to define a clear interface to access different
information about the translation.
This is a class for a single word and its forms and translations. It has all
the forward translations,... |
c26a9e57105e486a9de4ef9360654b6dc36d4ca7 | rimbafrida/rimba | /login.py | 1,965 | 3.65625 | 4 | import socket
import random
import operator
import os
import time
import datetime
import sys
class Timer(object):
"""A simple timer class"""
def __init__(self):
pass
def start(self):
"""Starts the timer"""
self.start = datetime.datetime.now()
def stop(self):
"""Stops t... |
3ea7c6c95dd6d68f2a6ffe9b4b0d0451c334d21b | stranger9811/spoj | /ABSYS.py | 507 | 3.765625 | 4 | test = int(raw_input())
to_find="machula"
for i in range(test):
z=raw_input()
y=raw_input()
index=y.find(to_find)
if (index+6)!=(len(y)-1):
y=y[:index] + "12" +y[index+7:]
else:
y=y[:index] + "12"
equal_to=y.find("=")
plus=y.find("+")
s=y.split(" ")
number1=int(s[0])
number2=int(s[2])
number3=int(s[4])
... |
790f0a18006d43c66e14f3f99372a9a546f9e568 | stranger9811/spoj | /SUM1.py | 205 | 3.515625 | 4 | x=int(raw_input())
for i in range(0,x):
n=int(raw_input())
n=n-1
n_3=n/3;
val_3=(3*n_3*(n_3+1))/2;
n_5=n/5
val_5=(5*n_5*(n_5+1))/2
n_15=n/15
val_15=(15*n_15*(n_15+1))/2
print val_5+val_3-val_15
|
201a2b05930cd4064623156c2b9248665d378647 | Dumacrevano/Dumac-chen_ITP2017_Exercise2 | /3.1 names.py | 234 | 4.375 | 4 | #Store the names of a few of your friends in a list called names .
# Print each person’s name by accessing each element in the list, one at a time .
names=["Suri", "andy", "fadil", "hendy"]
print(names[0],names[1],names[2],names[3]) |
193b863808b268a954f6fedd7cc8780b610ee187 | Dumacrevano/Dumac-chen_ITP2017_Exercise2 | /2.3 personal messages.py | 114 | 3.59375 | 4 | name="Andy"
print("hello "+name+", would you like to learn some python today")
friend = ["dumac", "Hendy", "suri"] |
42627250cb4d940216afbfd63631af391c8df4f9 | Dumacrevano/Dumac-chen_ITP2017_Exercise2 | /3.10 every function.py | 328 | 4.15625 | 4 | list=["Indonesia","singapore","Thailand","Kamboja"]
print(list[1])
print(list[-2])
list[1]="Vietnam"
list.append("Laos")
list.insert(0,"Malaysia")
del list[3]
winner=list.pop()
print("the winner is "+winner)
list.remove("Malaysia")
print(list)
print(sorted(list,reverse=True))
list.sort()
print(list)
list.reverse()
prin... |
23ec80544a38b38806c5377e088ea03f9bbec278 | Dumacrevano/Dumac-chen_ITP2017_Exercise2 | /Dumac chen_ITP2017_Exercise 2/Dumac Revano Chen (palindrome).py | 222 | 4.09375 | 4 | word1="nakikan"
word1=word1.casefold()#make it less sensitive for better comparison
Reverse1=reversed(word1)
if list(word1) == list(Reverse1):
print("it is palindrome word")
else:
print("it is not palindrome word") |
1baeb9bb9396e0a4c29a9a63cb5c201fd96c6228 | Dumacrevano/Dumac-chen_ITP2017_Exercise2 | /4.15 Code Review.py | 206 | 3.625 | 4 | buffet = ("prawn", "tofu", "chicken", "vegetable", "fish")
for buffet in buffet:
print(buffet)
print("\n")
buffet = ("prawn", "clam", "chickhen", "beef", "fish")
for buffet in buffet:
print(buffet)
|
06cd4ddfebc65980451815ebfff13d9773459015 | EPCJC-LP10/turma | /M6/loja.py | 4,006 | 4 | 4 | # -*- coding: utf-8 -*-
#
# Exemplo utilização de array de registos
# Os elementos da lista são mantidos ordenados (por código de artigo)
# © EPCJC
#
def menu():
print("\n\n")
print("1: Inserir novo artigo")
print("2: Pesquisar por um artigo")
print("3: Modificar quantidade em stock de um artigo")
... |
7d5db04a437bc727e9e88d425384f2f825126c35 | vvhanxing/skill-upgrade | /data_structure/traverse_binary_tree.py | 2,063 | 3.65625 | 4 | # -*- coding: utf-8 -*-
class BinNode(object):
def __init__(self, value, left_child=None, right_child=None):
self.lChild = left_child
self.rChild = right_child
self.value = value
def addLeft(self, lChild):
self.lChild = lChild
def addRight(self, rChild):
se... |
f8a9d9284d2ff9563c835089e385330784ff9d44 | vvhanxing/skill-upgrade | /learn_note/framewoek/pygame/demo.py | 1,650 | 3.6875 | 4 | #-*- coding: utf-8 -*-
import sys
import time
import pygame
from maze import MAZE, search_path, start_point, end_point
from pygame.locals import QUIT, K_q
#color define
BLACK = (5 ,5, 5)
WHITE = (255, 255, 255)
GREEN = (0, 255, 0)
RED = (200, 50, 20)
#size
SCREEN = (402, 402)
REC = (40, 40)
iter_point = search_path... |
b94d182bf54bd9d1b9a6c9674eaef1b97e3c1f80 | Dengis2/project | /Lesson_9.py | 3,651 | 3.546875 | 4 | #Задача №1
import time
class TrafficLight:
__color = ["Red", "Yellow", "Green"]
def method_running(self):
color = self.__color
print(f"{color[0]}")
time.sleep(7)
print(f"{color[1]}")
time.sleep(2)
print(f"{color[2]}")
time.sleep(7)
a = ... |
86187983415babb074d629b15d0a3b5d644cfd92 | PauloGunther/Python_Studies | /Teorias/4.2_Exemplos_LISTAS2.py | 3,025 | 3.859375 | 4 |
#LISTA DE PESSOAS E PESOS
l1 = []
pessoas = []
maior = menor = 0
while True:
pessoas.append(str(input('Nome: ')))
pessoas.append(int(input('Peso: ')))
if maior == 0:
maior = menor = pessoas[1]
else:
if pessoas[1] >= maior:
maior = pessoas[1]
elif pessoas[1] <= menor:... |
60ac2210df6235c0e3468538ffe6d28825dce63e | PauloGunther/Python_Studies | /Teorias/5.1_Exemplos.py | 1,755 | 3.90625 | 4 | from time import sleep
from random import randint
# AREA DO TERRENO
def area(x, y):
a = x * y
print(f'A area de um terreno {x}x{y} é de {a:.2f}m².')
a = float(input('Comprimento: '))
b = float(input('Largura: '))
area(a, b)
# FORMACATAO ACOMAPNHA TEXTO
def form(texto): # funcao
tamanho = len(texto)
... |
70bff1130064e823077c47b62fe29a207661fa73 | PauloGunther/Python_Studies | /Teorias/2.1_Exemplos.py | 1,362 | 4.125 | 4 | # POR TUDO MAIUSCULO E MINUSCULO, CONTA NUMERO DE LETRAS
nome = input('Digite seu nome completo: ')
print(nome.upper())
print(nome.lower())
rep = nome.replace(' ', '')
print('O número de letra é: {}' .format(len(rep)))
n1 = nome.split()
print('Seu primeiro nome tem {} letras' .format(len(n1[0])))
# MOSTRAR DEZENAS CEN... |
67273fff67eddca6bcfa367c5532a612562eb38b | balonovatereza/Pyladies-repository | /02/if.py | 358 | 3.515625 | 4 | strana = float(input('Zadej stranu ctverce v centimetrech: '))
kladne_cislo = strana > 0
if kladne_cislo:
print('Obvod ctverce se stranou ', strana, ' je ', 4 * strana, 'cm')
print('Obsah ctverce se stranou ', strana, ' je ', strana ** 2, 'cm')
else:
print('Strana ctverce musi byt kladna.')
print('Dekujeme... |
98fefe1e93305417425464cc3b01710dee97c549 | balonovatereza/Pyladies-repository | /03/Ukol 4.py | 411 | 3.640625 | 4 | from turtle import shape, left, right, forward, exitonclick
from math import sqrt
shape('turtle')
for i in range(4): # nakresli ctverec
forward(50)
left(90)
left(45)
forward(sqrt(2)*50) # nakresli sikmou caru v domecku
left(90)
forward(sqrt(2)*50/2) # nakresli strisku
left(90)
forward(sqrt(2)*50/2) # nak... |
4b7e9a35789e3be0bc65975fc94cb7a46732017d | balonovatereza/Pyladies-repository | /07/Ukoly z hodiny/seznamy.py | 3,218 | 3.953125 | 4 | cisla = [1, 1, 2, 3, 5, 8, 13]
print(cisla) # vypise seznam na jeden radek, tak jak je zapsany vyse
for cislo in cisla:
print(cislo) # vypise kazdou polozku na novy radek
seznam = [1, 'abc', True, None, range(10), len]
print(seznam)
print(cisla[2])
print(cisla[2:-3])
prvocisla = [2, 3, 5, 7, 11, 13, 17]
print... |
d51198015d5d7ef44db5c76c1124eb95e96f957e | balonovatereza/Pyladies-repository | /09/piskvorky/piskvorky.py | 2,152 | 3.640625 | 4 | from ai import tah_pocitace
from util import tah
def vyhodnot(pole, symbol_hrace, symbol_pocitace):
"""
Podle stavu herního pole vrátí:
řetězec "x", když vyhraje hráč,
řetězec "o", když vyhraje počítač,
řetězec "!", když dojde k remíze nebo
řetězec "-", když je možné ještě pokračovat ve hř... |
752626c1314c482e195bec357be5f28142a69c51 | bquillas/Learning-Python | /codigo_python/listas.py | 742 | 4.125 | 4 | # LISTAS
# Las listas son mutables
# Puedo quitar y añadi9r alementos a la lista
objetos = ["Hola", 2, 4.5, True]
objetos[0]
#'Hola'
objetos[3]
# True
objetos.append(False)
# ["Hola", 2, 4.5, True, False]
objetos.pop(1) #Pasa como parámetro el índice de la lista
# 2
# Elimina el valor de la pos 2
# ["Hola", 4.5, T... |
d1fb66129450d2f1ea98981cff0b6a75c2283390 | lodi-jesse/aula_python | /desafio047.py | 233 | 4.03125 | 4 | '''Faça um programa que mostre na tela todos os números (pares) que estão no intervalo entre 1 e 50.'''
for c in range(1, 50):
if c % 2 == 0:
print(c, end=' ')
for cont in range(2, 51, 2):
print(cont, end=' ') |
28062d6a6348bfc18f5e2ba51a3600357ecca66e | lodi-jesse/aula_python | /desafio087.py | 879 | 3.9375 | 4 | '''Aprimore o desafio 86 mostrando no final
-> a soma de todos os valore pares digitados
-> a soma do valores da terceira coluna
-> P maior valor da segunda linha f'''
from os import system
from random import randint
system('cls')
matriz = [[0,0,0],[0,0,0],[0,0,0]]
soma = soma3 = 0
for i in range(0,3):
f... |
5a98de9302cd36107a5bd2c3e7bba4218f817ba6 | lodi-jesse/aula_python | /desafio042.py | 744 | 4.125 | 4 | # Refaça o desafio 035 dos triângulos, acrescentando o recurso de mostrar que tipo de triângulo será formado:
# Equilátero: todos os lados iguais
# Isósceles: dois lados iguais
# Escaleno: Todos os lados diferentes
r1 = int(input('Digite a primeira reta: '))
r2 = int(input('Digite a segunda reta: '))
r3 = int(in... |
fc8596af1d7e3c5bd1939cbafe8dc8cb44c686af | lodi-jesse/aula_python | /desafio054.py | 636 | 3.75 | 4 | ''' Crie um programa que leia o ano de nascimento de sete pessoas. No final mostre quantas pessoas ainda não atingiram a maioridade e quantas já são maiores.(considerar maior idade 21) '''
from datetime import date
ano_atual = date.today().year
menor = 0
maior = 0
for c in range(1, 7 +1):
ano = int(input('Dig... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.