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 |
|---|---|---|---|---|---|---|
6d01c4de665058cfe9bcd91674d4adbc116ce1e2 | vicious987/old_uni_assignments | /python_basic/l3/zad1/failed_rec_tree.py | 522 | 3.90625 | 4 | import turtle
def draw_tree(turtle, initial_length = 100, angle = 45):
if (initial_length < 10):
return
turtle.forward(initial_length)
turtle.right(angle)
reset_position = turtle.position()
draw_tree(turtle, initial_length/2, angle)
turtle.setposition(reset_position)
#turtle.left(2*... |
4a76bf483c6f8abb15dac38b739a4fa2176e14c4 | nbyoung/nuPy | /demo_tmp.py | 246 | 3.546875 | 4 | import tmp
def main():
with tmp.Path('hello.txt') as path:
with open(path, 'w') as file:
file.write('Hello, world!')
with open(path) as file:
message = file.read()
print(path, message)
main()
|
0d325f859b3ba9a5f185e6538d567dd4d0233080 | DunjaPet/Rosalind | /ApproximatePatternCount.py | 617 | 3.84375 | 4 | # Input: Strings Pattern and Text, and an integer d
# Output: The number of times Pattern appears in Text with at most d mismatches
def ApproximatePatternCount(Pattern, Text, d):
count = 0 # initialize count variable
for i in range(len(Text)-len(Pattern)+1):
mismatch=HammingDistance (Text[i:i+len(... |
fcb46077435aa6bfcaa022eb8036d26f43a963be | brunsgaard/datanet | /assignment1/source/client.py | 3,312 | 3.71875 | 4 | import socket
import sys
import readline
import errno
class Client:
BUFFER_SIZE = 1024
def __init__(self, port=50000, serverip='localhost'):
"""
Initialize the variables required by the client
"""
self.serverip = serverip
self.port = port
self.socket = None #use... |
484caa024d988e03be4af0a12e35004864f4c9b6 | john0714/KimuPracticeCode | /CodePractice/Python/basic/QueuePractice.py | 1,190 | 3.75 | 4 | # coding:utf-8
import time
import random
class Queue:
def __init__(self):
self.items = []
def is_empty(self):
return self.items == []
#queueに入れる
def enqueue(self, item):
self.items.insert(0, item)
#queueから出せる
def dequeue(self):
return self.items.pop()
def s... |
7dda80968959f651c1bd5bb6c990b1b2738d2ba6 | john0714/KimuPracticeCode | /CodePractice/Python/DataAnalysisPractice/matplotlibPractice.py | 627 | 3.65625 | 4 | import numpy as np
import matplotlib.pyplot as plt
# 파스텔 톤의 삼각함수에 대해 양의 구간과 음의 구간에 다른 색상을 사용한 것
n = 256
X = np.linspace(-np.pi,np.pi,n,endpoint=True)
Y = np.sin(2*X)
# 선1
plt.figure(figsize=(10,8))
plt.plot(X, Y+1, color='blue', alpha=1.00)
plt.fill_between(X, 1, Y+1, color='blue', alpha=.25)
# 선2
plt.plot(X, Y-1, c... |
e06a58db596ef0c4d471f534ad3ea39bc0b11076 | john0714/KimuPracticeCode | /CodePractice/Python/DataAnalysisPractice/contact.py | 3,194 | 3.953125 | 4 | # -*- coding: utf-8 -*-
# Run : shift + F10
# ===============정보 보기, 입력, 출력, 삭제 함수 및 클래스=================
class Contact:
def __init__(self, name, phone_number, e_mail, addr):
self.name = name
self.phone_number = phone_number
self.e_mail = e_mail
self.addr = addr
# 연락처 출력 받기(inpu... |
9d21a3a35b3dd91cd1214ec1519cd6b68de2dc01 | igormusinov/Orchestra | /users.py | 1,927 | 3.515625 | 4 | import os
import random
import string
import argparse
from pathlib import Path
from passlib.hash import sha512_crypt
passwd_folder = Path("jupyterhub/passwords")
def get_users(file: str) -> list:
user_file: str = file
user_list = []
with open(user_file, 'r') as f:
for line in f:
user = line.strip('\n')
... |
430b68071ca27fe75bdf4f02d6a09ff89888d95a | Seanie55/UCDProject | /Loop with ITERROWS.py | 217 | 3.578125 | 4 | import pandas as pd
file = 'forbes_billionaires_geo.csv'
data = pd.read_csv(file, index_col=0)
top50 = data[0:50]
for name, country in top50.iterrows():
print(name + ":" + str(country['Country'].upper()))
|
b2683443c25c165b86088b646c0625a6aaf1397d | n1k-n1k/python-algorithms-and-data-structures--GB-interactive-2020 | /unit_04_empirical_evaluation/hw/hw_04_1.py | 1,649 | 3.875 | 4 | """
Проанализировать скорость и сложность одного любого алгоритма
из разработанных в рамках домашнего задания первых трех уроков.
Модуль-2 задача-3
3. Сформировать из введенного числа обратное по порядку входящих в него цифр
и вывести на экран. Например, если введено число 3486, надо вывести 6843.
"""
import cProfile... |
decf9cf2ac7372098793fcda557b53b07d8111e0 | n1k-n1k/python-algorithms-and-data-structures--GB-interactive-2020 | /unit_04_empirical_evaluation/hw/hw_04_2.py | 2,334 | 3.921875 | 4 | """
Написать два алгоритма нахождения i-го по счёту простого числа.
Функция нахождения простого числа должна принимать на вход натуральное
и возвращать соответствующее простое число.
Проанализировать скорость и сложность алгоритмов.
Первый — с помощью алгоритма «Решето Эратосфена».
Второй — без использования «Решета Эр... |
a5bc6fe234953c5a427c52edef0bcfa9174d1bd5 | n1k-n1k/python-algorithms-and-data-structures--GB-interactive-2020 | /unit_03_arrays/hw/hw_03_1.py | 443 | 3.546875 | 4 | """
1. В диапазоне натуральных чисел от 2 до 99 определить,
сколько из них кратны каждому из чисел в диапазоне от 2 до 9.
Примечание: 8 разных ответов.
"""
count = {}
for i in range(2, 100):
for j in range(2, 10):
if i % j == 0:
count[j] = count.get(j, 0) + 1
for k, v in count.items():
pri... |
49ff70c58a4cea2e7d01358a8869753a48a6365a | n1k-n1k/python-algorithms-and-data-structures--GB-interactive-2020 | /unit_07_sort_algorythms/hw/hw_07_3.py | 1,963 | 4.0625 | 4 | """
Массив размером 2m + 1, где m — натуральное число, заполнен случайным образом.
Найдите в массиве медиану.
Медианой называется элемент ряда, делящий его на две равные части:
в одной находятся элементы, которые не меньше медианы, в другой — не больше медианы.
Примечание: задачу можно решить без сортировки исходного... |
3b1778872c9c7cf1a01f97d34413637fbd846720 | n1k-n1k/python-algorithms-and-data-structures--GB-interactive-2020 | /unit_01_algorithms_intro/hw/hw_01_5.py | 311 | 4.125 | 4 | """
Пользователь вводит номер буквы в алфавите.
Определить, какая это буква.
"""
letter_pos = int(input('Введите номер латинской буквы в алфавите: '))
print(f'Ваша буква: {chr(letter_pos + ord("a") - 1)}')
|
7ca3f0abd9aefe8b958e30e9d6f5137600812ca8 | n1k-n1k/python-algorithms-and-data-structures--GB-interactive-2020 | /unit_02_loops_recursion_functions/lessons/lesson_02_3.py | 1,032 | 3.84375 | 4 | """
Алгоритм Евклида.
Задача. Найти наибольший общий делитель (НОД, greatest common divisor, gcd) пары чисел.
Вариант 1. Простейший циклический алгоритм основанный на вычитании.
Вариант 2. Рекурсивный алгоритм основанный на нахождении остатка от деления.
Вариант 3. Циклический алгоритм основанный на нахождении остатк... |
73febf1c1bf6a8d35dc50afbedd76b2df8bb2da4 | RohanNankani/Computer-Fundamentals-CS50 | /Python/mad_lib_theatre.py.py | 2,357 | 4.25 | 4 | # Author: Rohan Nankani
# Date: November 11, 2020
# Name of Program: MadLibTheater
# Purpose: To create a mad lib theater game which ask user for input, store their input using list, and print the story.
# Intializing the list
grammar = []
# List of prompts that describe the category of the next word
# to be substit... |
4da586d75600a358747c41c1acb67ef299edb46c | velpuri1035/My-Solutions | /adhoc/largest_rectangle_amoung_buildings.py | 2,428 | 4.0625 | 4 | # This was very intersting problem.
# Question:
# Given a list of building heights in order from left to right, assuming the buildings are adjacent,
# calculate the largest rectangle you could form choosing any segment of the line of buildings.
# Clue for O(n) solution:
# If we have l_index and r_index, which are le... |
51609dcf0232e509510fcab1fa99c16b2548a232 | RiddhimanSaha/guessing-game-python | /guessinggame.py | 666 | 3.796875 | 4 | import random
print("----------------------------")
print(" M&M guessing game!")
print("----------------------------")
print('Try to guess the number of M&M and get a free luch and shoutout on the house)
print()
mm_count = random.randint(1, 100)
attempt_limit = 5
attemps = 0
while attemps < attempt_limit:
... |
07609ac2d6b8568a4f0a67f7b556e18c2dcc6618 | sp3arm4n/OpenSource-Python | /assignment_01/src/p18_1.py | 336 | 3.65625 | 4 | from p18 import *
# letter 'a'
print(">>> q[0][0]\n", q[0][0])
# the list ['d','e','f']
print(">>> q[1]\n", q[1])
# the 'd' element
print(">>> q[1][0]\n", q[1][0])
# q[-1][-2] has the value 'g'
print(">>> q[-1][-2]\n", q[-1][-2])
# the last element 'h'
print(">>> h")
q.append('h')
# final
print... |
17856f57c910a767dfc433a16fbe31b365e3e870 | sp3arm4n/OpenSource-Python | /assignment_01/src/p10.py | 364 | 4.46875 | 4 | # step 1. asks the user for a temperature in Fahrenheit degrees and reads the number
number = float(input("please enter Fahrenheit temperature: "))
# step 2. computes the correspodning temperature in Celsius degrees
number = (number - 32.0) * 5.0 / 9.0
# step 3. prints out the temperature in the Celsius scale.
... |
c0b0285370c355e0ea4e95c3b6d3346884facd9e | recheej/Data-Structures-In-Python | /hash_table.py | 1,348 | 3.78125 | 4 | __author__ = 'recheejozil'
from linked_list import Node, LinkedList
class HashData(object):
def __init__(self, key, value):
self.key = key
self.value = value
class HashTable(object):
def __init__(self, size):
self.list = []
for i in range(0, size):
self.list... |
6a71f962d24be5f788596ea692911af6ba5c32dc | lykkin/rosalind-and-euler | /rosalind/2sum.py | 375 | 3.5 | 4 | def find_opposites(li):
for i in xrange(len(li)):
for j in xrange(i + 1, len(li)):
if li[i] == -li[j]:
return i+1, j+1
return -1, None
f = open('rosalind_2sum.txt')
f.readline()
for line in f:
first, second = find_opposites(map(int, line.split(' ')))
print first if s... |
09c68c1fc5e26fd5609bcd286f7500c458a36551 | ravi4all/PythonDecMorning | /Functions/03-NestedFunctions.py | 294 | 3.859375 | 4 | def outer(x):
print("This is outer...")
def inner():
print("This is inner...")
return x + 1
def inner2():
print("This is inner2...")
return x - 1
# print(inner())
return inner2
# print(outer(12)())
x = outer(12)
print(x())
|
45497bbe4e6c706c4f79e8be82bc586cc78331e3 | DarkCodeOrg/python-learning | /list.py | 288 | 4.21875 | 4 | #!/bin/python python3
""" creating an empty list and adding elements to it"""
list = []
list.append(200)
list.append("salad")
list.append("maths")
print(list)
print("this is your initial list")
new = input("Enter something new to the list: ")
list.append(new)
print(list)
|
e5f71f85794cf0fd9f9966d6559f8ad0bcd7130a | DarkCodeOrg/python-learning | /file_handling_4.py | 1,621 | 3.78125 | 4 | ## updating in a binary file
#
# tell() and seek()
#
import pickle
from sys import flags
infile = open("trial.txt",'r')
print("initially the file_pointer is at = ",infile.tell())
print("reading 4 bytes : ",infile.read(4))
print("now the file pointer is art :",infile.tell())
## the tell function gives the current p... |
5185824aa1b10360a213b2b09466fa7c77540f74 | issackj1/CompetitiveProgrammingClub | /pot.py | 207 | 3.703125 | 4 |
num= int(input())
counter = 0
for i in range(num):
num1 = input()
num2 = len(num1)
pw = int(num1[num2-1])
num3 = int(num1[:num2-1])
counter = counter + pow(num3, pw)
print (counter)
|
be930a3a8ab7fa405f4970dc9e84653e6ef96d4e | issackj1/CompetitiveProgrammingClub | /boss.py | 159 | 3.765625 | 4 | def find(pillars):
if(pillars <= 3):
return 1
else:
return 1 + find(pillars - 1)
num = int(input())
result = find(num)
print(result) |
253372ce42dd5c9da5143f936acd4ba9a75c0028 | issackj1/CompetitiveProgrammingClub | /wood.py | 514 | 3.578125 | 4 | cases = int(input())
for i in range(cases):
waitTime = 0;
currentTime = 0;
customers = int(input())
order = [0 for _ in range(customers)]
for j in range(customers):
nums = list(map(int, input().split()))
pieces = nums[0]
nums.remove(pieces);
nums.sort()
for k... |
9e5f10af7534986b51024c4ca4ff592f649799f1 | deniseicorrea/Aulas-de-Python | /python/ex070.py | 749 | 3.609375 | 4 | total = totmil = menor = cont = 0
barato = ' '
while True:
produto = str(input('Nome do produto: '))
preço = float(input('Preço do produto: R$'))
cont += 1
total += preço
if preço > 1000:
totmil += 1
if cont == 1:
menor = preço
barato = produto
else:
if preço ... |
d3c1de18d9f513d3e41f005f711690a202a9c660 | deniseicorrea/Aulas-de-Python | /python/ex035.py | 267 | 4.03125 | 4 | r1 = float(input('Primeiro seguimento: '))
r2 = float(input('Segundo seguimento: '))
r3 = float(input('Terceiro seguimento: '))
if r1 < r2 +r3 and r2 < r1+ r3 and r3 < r1 +r2 :
print('Podem formar um TRIÂNGULO')
else:
print('Não podem formar um TRIÂNGULO') |
4f7ee085ab854bcc7c8d2b6b7ddddb5f358daca8 | deniseicorrea/Aulas-de-Python | /python/ex028.py | 366 | 3.78125 | 4 | from random import randint
from time import sleep
computador = randint(0,5)
print('++_++'* 20)
print('Tente adivinhar um número entre 0 e 5')
jogador = int(input('Em que número eu pensei? '))
print('PROCESSANDO...')
sleep(2)
if jogador == computador:
print('Parabéns, voce ganhou!!!')
else:
print(f'Haha você per... |
b9ed6df20fd0bb619fbcbaf9ab3b254b2de2bb86 | deniseicorrea/Aulas-de-Python | /python/ex49.py | 98 | 3.90625 | 4 | num = int(input('Digite um número: '))
for c in range (1,11):
print(f'{num} x {c} = {num*c} ')
|
2dddfc5ee0cdc18561aa5d53336eb470317f1973 | coral0723/python_study | /이분탐색 알고리즘.py | 545 | 3.765625 | 4 | #리스트에서 특정 숫자 위치찾기
#입력:리스트a,찾는 값x
#출력:찾으면 그 값의 위치, 찾지 못하면 -1
def binary_search(a,x):
#탐색할 범위를 찾는 변수 start,end
#리스트 전체를 범위로 탐색 시작(0~len(a)-1)
start=0
end=len(a)-1
while start<=end:
mid=(start+end)//2
if x==a[mid]:
return mid
elif x>a[mid]:
start=mid+1
... |
198ffdba85af4c0b2f132fbf712b1dbac42264c2 | coral0723/python_study | /삽입 정렬 알고리즘.py | 844 | 3.515625 | 4 | d=[2,4,5,1,3]
#리스트 r에서 v가 들어가야할 위치를 돌려주는 함수
def find_ins_idx(r,v):
#이미 정렬된 리스트 r의 자료를 앞에서부터 차례로 확인하여
for i in range(0,len(r)):
#v값보다 i번 위치에 있는 자료값이 크면
#v가 그 값보다 앞에 위치해야 정렬 순서가 유지됨
if v<r[i]:
return i
#적절한 위치를 못찾았을 땐
#v가 모든 자료보다 크다는 뜻이므로 맨뒤에 위치
return len(... |
192af36327e7984ba16c57dac945182bc92de21a | 2u6z3r0/automate-boaring-stuff-with-python | /inventory.py | 1,171 | 4.1875 | 4 | #!/usr/bin/python3
#chapter 5 exercise
stuff = {'gold coin': 42, 'rope': 1}
def displayInventory(stuff):
'''
:param stuff: It takes a dictionary of item name as key and its quantity as value
:return: Nothing, but it prints all items and respective quantity and total quantity(sum of all itmes qty)
'''
... |
9221ef7205ac64c859725a339f306f95a9698c64 | 2u6z3r0/automate-boaring-stuff-with-python | /tablePrinter.py | 403 | 4.0625 | 4 | #!/usr/bin/env python3
#Chapter 6 practice project
tableData = [['apples', 'oranges', 'cherries', 'banana'],
['Alice', 'Bob', 'Carol', 'David'],
['dogs', 'cats', 'moose', 'goose']]
def printTable(tableData):
for i in range(len(tableData)+1):
for j in range(len(tableData[0])-1):
... |
accbc433a0e9f011744137e849a20587b05be513 | yttan/smallProjs | /analyze_code_in_folder.py | 2,635 | 3.671875 | 4 | """Check all the Python code files in a folder and its subfolders.
Count code lines, blank lines and annotation lines of every file.
Write results into a txt file
Note:
This code takes all files into consideration, but it is correct only when the file
is in Python code, which means you can not use it to count a Java co... |
a767fd70f5fedac106f3aca0b8b48b41d38a2a8e | NATHAN76543217/BtCp_D00 | /ex03/count.py | 1,005 | 4.28125 | 4 | import string
def text_analyzer(*text):
"""
This function counts the number of upper characters,
lower characters, punctuation and spaces in a given text.
"""
if len(text) > 1:
print("ERROR")
return
if len(text) == 0 or isinstance(text[0], str) == 0:
text = []
t... |
ea759c1fa27b70321d298e539c3e564f3f8927ae | jonghyuk/python_report | /python/메소드/method.py | 593 | 4 | 4 | class Human():
"""인간"""
def create(name, weight):
person = Human()
person.name = name
person.weight = weight
return person
def eat(self):
self.weight += 0.1
print("{}가 먹어서{}kg이 됨".format(self.name, self.weight))
def walk(self):
self.weight -= 0.1
... |
5e3e050c459e17da566e0548572ca524b38405d7 | jonghyuk/python_report | /python/list/list2.py | 426 | 3.671875 | 4 | #list = str.split() 문자열에서 리스트로
#"Hello world".join(list)리스트에서 문자열으로
word = "아 집에 가고싶다"
word = word.split()
print(word) #문자열에서 리스트로
characters = list("abcdef")
print(characters)#각글자가 들어있는 리스트
time_str = "10:35:27"
time_list = time_str.split(":")#자르는 기준이 :콜론
time_list = ":".join(time_list)#리스트에서 문자열
print(time_list)
|
97e79b1807ef79f8f8fd250ffa80165f728870fa | jonghyuk/python_report | /python/논리연산/logicc.py | 812 | 3.859375 | 4 | a =10
if a < 0 and 2**a>1000and a%5==2and rouns(a)==a:
print("복잡한식")#논리식 틀려서 출력안댐
def return_false():
print("함수 return_false")
return False
def return_ture():
print("함수 return_true")
return True
print("*************")
# print("테스트1")
# a = return_false()
# b = return_true()
# if a and b: #a는 false... |
fe276d786219f5a4fd2c6c53f970e1e11ed409da | jonghyuk/python_report | /python/패킹 언패킹.py | 210 | 3.953125 | 4 | c = (3,4)
d,e=c#c의 값을 언패킹해서 d와e에 넣음
print(d)
f = d,e
print(f)#변수de를 f에 패킹
x = 5
y=4#x와y를 바꾸려면
x,y=y,x
print(x,y)
def func():
return 1,2
q,w= func()
print(q,w) |
1747d239b2aef9f680a52a83cd178b2bca73a03a | viktoriashandybina/prog7 | /LR/1.py | 921 | 3.8125 | 4 | def squareSequenceDigit(n):
i = 1
sq = 1
while n > 0:
sq = i * i
i += 1
t = sq # переменная для подсчета разрядности квадрата
a = 0
if (sq / 10) > 1: # будет ли разрядность квадрата больше 1
while t >= 1:
t /= 10
a += 1 # разрядность
else:
a = 1
n -= a
... |
35b691df2020853a0be2debaa1d4d585cfc4e06f | Agirivasan/Slack-Technical-Assignment | /weather_check.py | 1,234 | 3.640625 | 4 | from slackclient import SlackClient
import requests
import json
import sys
#Function to validate the zip code
def zipcode_validate(zipcode):
if type(zipcode) != int:
sys.exit("Invalid Zipcode")
elif zipcode < 10001 or zipcode >= 99500:
sys.exit("Invalid Zipcode")
else:
valid_zip = s... |
75e70e3300181dfb1dd71800fa0bc5d7ca4f2aa2 | valdialva/Topicos-1 | /Labs/Lab1.py | 1,610 | 4.1875 | 4 | #1. Create first name and add last name with join
print ("1")
n = "Alvaro"
print (n)
n = ''.join([n, " Valdivieso"])
print (n)
#2. convert tu uppercase
print ("2")
n = n.upper()
print (n)
#3. create list with n
print ("3")
l = list(n)
print (l)
print (len(l))
#4. create string from l
print ("4")
m = ''.join(l)
print... |
cf2553bafad225366a58d08ab9a8edc6b4daa9d2 | Ayush900/django-2 | /advcbv2/basic_app/templates/basic_app/pythdjango/oops.py | 807 | 4.40625 | 4 | #class keyword is used to create your own classes in python ,just like the sets,lists,tuples etc. .these classes are also known as objects and this type of programming involving the creation of your own classes or objects is known as object oriented programming or oops....#
class football_team: #Here the ... |
2113627ef5467c4bf8ca300d18a78d05989f4da9 | Deonlin/stanCode | /breakoutgraphics.py | 6,772 | 4.28125 | 4 | """
This is a simple brick-our game for python learning
"""
from campy.graphics.gwindow import GWindow
from campy.graphics.gobjects import GOval, GRect
from campy.gui.events.mouse import onmouseclicked, onmousemoved
import random
BRICK_SPACING = 5 # Space between bricks (in pixels). This space is used for horizontal ... |
ef4f36bc94539f89ee822fa7e7472bd11847318e | SRCinVA/The_Python_Mega_Course | /Sentence_maker.py | 1,279 | 4.03125 | 4 |
# My solution
# def sentenceGlue(string):
# sentence = input("Say something: ")
# paragraph = []
# for sentence in paragraph:
# sentence.capitalize() + "."
# paragraph.append(sentence)
# if sentence == "end":
# print(paragraph)
# sentenceGlue()
# You don't need to cra... |
fcde3951ead62eb75fa691e75e927832c423707b | synac1/CIS166pring2019 | /Solutions/Homework project/HomeWorkProject.py | 10,376 | 4.4375 | 4 | '''
file : HomeWorkProject.py
@Author: Yanilda
Created: 5.4.19
Desc : Solution to the Homework Project
'''
#Chap2
# 1
#Modify convert.py to print an introduction
def convert():
print("Welcome to temperature convertor")
print("This Program will convert from celsius to farenhei... |
dde15a4cf2172b34f8dc756a87bd9e8a0934226b | Toaster192/advent_of_code | /2018/day4.py | 1,863 | 3.546875 | 4 | day = str(__file__).find("day") + 3
with open("input" + str(__file__)[day:-3], "r") as f:
data = f.readlines()
log = []
data.sort()
for line in data:
words = line.split()
date = int(words[0][1:].replace('-', ''))
time = int(words[1][:-1].replace(':', ''))
if words[2] == "falls":
fromtime... |
c5464c86391048a902b2586610a345f9b3afa961 | flvSantos15/pythonExercicies | /Mundo1/Exercicios/ex002.py | 155 | 3.859375 | 4 |
#Faça um programa que leia o nome de uma pessoa e
#mostre uma mensagem de boas vindas
nome = input('Digite seu nome: ')
print(f'Seja bem-vindo {nome}') |
66648749eb3c6031410e6ca212077b7274a2c023 | flvSantos15/pythonExercicies | /Mundo1/Exercicios/ex015.py | 118 | 3.578125 | 4 | k = float(input('Kilometros? '))
d = int(input('Quantos dias? '))
vd = 60 * d
kr = 0.15 * k
print('Valor: ', vd + kr)
|
54234c814a9406c98279f07fd34561120f658c95 | flvSantos15/pythonExercicies | /Mundo1/Exercicios/ex018.py | 247 | 3.765625 | 4 | from math import cos, sin, tan, radians
ang = float(input('Angulo: '))
seno = sin(radians(ang))
coseno = cos(radians(ang))
tangente = tan(radians(ang))
print(f'Seno {seno:.2f}')
print(f'Cosseno {coseno:.2f}')
print(f'Tangente {tangente:.2f}')
|
e98ba84add2519f4c3858cef105c6e5de54f57fb | jonathangriffiths/Euler | /Page1/SumPrimesBelowN.py | 612 | 4.15625 | 4 | __author__ = 'Jono'
from GetPrimeN import isPrime
#basic method to estimate how long it will take like this
def get_sum_primes_below_n(n):
sum=2
for i in range(3, n+1, 2):
if isPrime(i):
sum+=i
return sum
print get_sum_primes_below_n(2000000)
#note: Erastosthenes seive useful for ... |
01b65e8649885ff28bcc876c503caee5f1c67459 | shekrunk/thinkcspy | /lab04_draw_circle.py | 630 | 4.0625 | 4 | import turtle
def drawPolygon(t, sideLength, numSides):
turnAngle = 360 / numSides
for i in range(numSides):
t.forward(sideLength)
t.left(turnAngle)
def drawCircle(anyTurtle, radius):
circumference = 2 * 3.1415 * radius
sideLength = circumference / 360
drawPolygon(anyTurtle, sideLe... |
0bdf054fd362ae2ade3bbbd435d2169917e601fc | stroooooom/Python-game | /BTB/btb_v4.pyw | 13,619 | 4.0625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Thu June 17 22:54:41 2017
@author: Stroom
"""
"""""
## DESCRIPTION ##
'Break The Brain'
Rules of the game:
Player is needed to choose color, which displayed word means.
For example, on the screen will be word 'GREEN' (this word can be any color) which painted pin... |
53964b7716c2acba36fe8bf9a93fc71685f17532 | GorillaFu/holbertonschool-higher_level_programming | /0x04-python-more_data_structures/12-roman_to_int.py | 513 | 3.5625 | 4 | #!/usr/bin/python3
def roman_to_int(roman_string):
if roman_string is None or isinstance(roman_string, str) is False:
return 0
conv = {'I': 1, 'V': 5, 'X': 10, 'L': 50, 'C': 100, 'D': 500, 'M': 1000}
result = 0
i = 0
while i < len(roman_string):
if i > 0 and conv[roman_string[i]] > c... |
cee663527079896dd231ceb244316b8e3d6d3d7a | GorillaFu/holbertonschool-higher_level_programming | /0x02-python-import_modules/2-args.py | 374 | 3.59375 | 4 | #!/usr/bin/python3
if __name__ == "__main__":
import sys
j = len(sys.argv) - 1
if j == 0:
print("{} arguments.".format(j))
elif j == 1:
print("{0} argument:\n{0}: {1}".format(j, sys.argv[j]))
else:
print("{} arguments:".format(j))
for i, str in enumerate(sys.argv[1:],... |
7cc31ea448f364b59f2ba08e8003d461e34a94d9 | ntapiam/dsig-poc | /iss/basis.py | 2,575 | 3.59375 | 4 |
'''
Interprets a binary number as a partition by intervals and
return the corresponding composition.
A 0 in the i-th position means i and (i+1) belongs to the same partition
'''
def binary_to_composition( binNum , L ):
comp = []
y = 1
for i in range(L) :
if not ( binNum & (1<<i... |
9a7ea68032e05ce285e15738ad6957fecb196c8d | everlyneMueni/Quiz-2 | /quiz.py | 996 | 3.703125 | 4 | def tens(numbers):
d=[]
for number in numbers:
numbers=[1,2,3,4,5,6,7,8,9]
r=number*10
d.append(r)
return(a)
def squares(squares):
even=[2,4,6,8,10,12]
for x in squares:
squares.append(x)
return(squares)
def sorted(a,b):
a=[9,1,4,7,3]
b=[5,2,6,8,0]
z="a"+"b"
sort.sorted(z)
def range_sum(num... |
7729b532379ca5600646d346e62af7851a466fc9 | armour-code/study_practice | /分形树.py | 833 | 3.890625 | 4 | # author: fzb
# time: 2020/3/30
# function: 分形树
# method: 直接运行
# completion:100%
from turtle import *
Draw = Turtle()
MyDraw = Draw.getscreen()
def DrawTree(DrawPin, PinLine, Linesize):
if PinLine > 5:
if Linesize > 1:
DrawPin.pensize(Linesize)
DrawPin.pencolor("brown")
... |
159217ec339147e0fcd38480ef5dc48ad515563b | nlhowell12/scraper2 | /scraper.py | 1,773 | 3.671875 | 4 | import argparse
import requests
import re
import sys
from bs4 import BeautifulSoup
def create_parser():
"""Creates an argument parser for this file"""
parser = argparse.ArgumentParser(
description='Scrapes a url for urls, emails, and phone numbers'
)
parser.add_argument('url', help='URL to scr... |
d47643b52db3233c9f50c703d6a28ab73ae45f28 | bd52622020/appSpaceRhys | /task_01 _python_coding_challenges/re_assignment.py | 181 | 3.75 | 4 | import re
pattern= r"^We.*Data$"
txt = "We love programming with Big Data"
x = re.search(pattern,txt)
if x:
print("found: " + x.group() )
else:
print("not found")
|
389a2891e9eb3b2ece304131e49d2c4cacac57b3 | bd52622020/appSpaceRhys | /task_02_python_coding_challenges/name_sort.py | 324 | 3.921875 | 4 | #!/usr/bin/env python
from collections import OrderedDict
def main(dict1):
print("Dict sorted by surname:")
dict2 = (OrderedDict(sorted(dict1.items())))
print(dict2)
if __name__ == "__main__":
test_dict = {"John":"Doe","Amy":"Brooks","Ranjit":"Sambi","Julia":"Cortez","Robert":"Locke"}
main(test_d... |
478c64df3e1ed56143fb3c021991e81fdf6a3572 | bd52622020/appSpaceRhys | /task_04_python_coding_challenges/leap_year.py | 429 | 4 | 4 | #!/usr/bin/env python
def main(year):
if not year % 4:
if not year % 100:
if not year % 400:
print("Is a leap year.")
else:
print("Not a leap year.")
else:
print("Is a leap year.")
else:
print("Not a leap year.")
... |
f7a7448c843003973e080bbf999ba7a099b05285 | bd52622020/appSpaceRhys | /task_10_python_coding_challenges/task_10.2_two_lambda_functions.py | 249 | 3.875 | 4 | #/usr/bin/env python
def main(a):
plus_fifteen = lambda x: x+15
times_two = lambda x,y: x*y
b = plus_fifteen(a)
print(times_two(a,b))
if __name__ == "__main__":
a = int(input("Please enter a number: "))
main(a) |
509200c08b1dfb38d8edbaf0ac2a2f3108dc6ee9 | sivomke/Numerical-methods-for-solving-boundary-problem | /adaptive.py | 934 | 3.609375 | 4 | def simpson(func, left, right):
return (right - left)*(func(left) + 4*func(0.5*(left + right)) + func(right))/6
# here we check the tolerance by Runge rule
# the result is enhanced by Richardson extrapolation formula
# p = 4 (accuracy by step)
def adaptive_simpson(func, left, right, tol):
mid = 0.5*(l... |
ca8a6aba26653571a1271a0c2db13332ef179a12 | acasallas/6860-final-project | /plot_loss.py | 1,499 | 3.5 | 4 | import numpy as np
import matplotlib.pyplot as plt
from sys import argv
iteration = []
loss = []
accuracy = []
with open(argv[1]) as the_file:
content = the_file.readlines()
for line in content:
if 'iteration' in line:
iteration.append(float(line[11:]))
if 'accuracy' in line:
accuracy.ap... |
af1a943dc43532abd581144d24ef53a08fae0eab | rpsmaini/sample | /digitcount.py | 172 | 4 | 4 | a = int(input("enter a number :"))
count = 0
while(a>0) :
count+=1
a=a//10
print("the number of digits are:",count)
input("press enter to exit :")
|
1fcee4132b33a78a7ffc51225eaab6ace5a8d08a | rpsmaini/sample | /digisum.py | 112 | 3.921875 | 4 | n=int(input("enter your number :"))
sum=0
while(n>0):
sum += int(n%10)
n = int(n/10)
print(sum) |
7b625580904471c575b7f57d21f5eb48b5b81bfa | Voland2578/CourseraDataStructuresAndAlgorithms | /Algorithms Toolbox/week4_divide_and_conquer/2_majority_element/majority_element.py | 617 | 3.515625 | 4 | # Uses python3
import sys
def get_majority_element(a):
a.sort()
max_appearances = 0
prev_element = None
counter = 0
for x in a:
if x != prev_element:
counter = 1
prev_element = x
else:
counter += 1
if counter > max_appearances:
... |
77eb60690b7e8a5cb55a3855f82009496bdcb6b0 | Voland2578/CourseraDataStructuresAndAlgorithms | /Algorithms Toolbox/week2_algorithmic_warmup/1_fibonacci_number/fibonacci.py | 307 | 3.875 | 4 | # Uses python3
def calc_fib(n):
if n <= 1:
return n
previous = 0
current = 1
for _ in range(n-2):
# this is actually great as it does not require temp variable
previous, current = current, previous + current
return current
n = int(input())
print(calc_fib(n))
|
d11a7e25b1973a43ce699f6f8e969f2926663eff | lom360/python-programming | /3) AccessWebData/Week6-JsonAndRest/json1.py | 690 | 3.796875 | 4 | import urllib.request, urllib.parse, urllib.error
import json
def char_count(file) :
temp = json.dumps(file)
print("Retrieved", len(temp), " characters")
# read() turns file into a string.
# decode() wile turn the file into an object
url = input("Enter location: ")
json_url = urllib.request.urlopen(url)
# S... |
752a562f0b38123b627b9c1e7d047fe51f625d62 | tchaitanya2288/pyproject01 | /dictionaries methods/set_remove_discard.py | 469 | 4.09375 | 4 | # 11 Remove Specified Element from Set = a_set.remove(), a_set.discard()
# Syntax:
#a_set.remove(x)
#a_set.discard(x)
# Example:
s = set([1, 2, 3, 4, 5,9,6,7])
s.remove(5)
print(s)
s.discard(7)
print(s)
s.discard(3)
print(s)
s.discard(9)
print(s)
#Output:
#set([1, 2, 3, 4])
#set([1, 2, 3, 4])
#set([1, 2, 4])
... |
af32475e446f1ddc7e65cb90040a567a21ac5d85 | tchaitanya2288/pyproject01 | /Simple if.py | 421 | 4.15625 | 4 | #1. The 1. if 2. if..else , 3. elif and 4. neasted elif
#1. IF Statement:
my_var=50
#50 < 100:
if my_var<100:
print(my_var,'is less then 100')
print ("We are out of the if statement")
#The if statement is used for conditional execution:
#if_stmt ::= "if" expression ":" suite
#(or)
my_var=50
if my_var<... |
b56b960935ab97dafde60ce25f80f2bd44126a8e | tchaitanya2288/pyproject01 | /List Methods/List_methods.py | 5,616 | 4.1875 | 4 | '''
1. a_list.append # Methods
2. a_list.extend # Methods
3. a_list.insert # Methods
4. a_list.remove # Methods
5. a_list.pop # Methods
6. a_list.reverse # Methods
7. a_list.sort # Methods
8. a_seq.index # Methods
9. a_seq.count # Methods
10. a_str.join # Methods
'''
# 1. a_list.append # Methods
# !/usr/b... |
c5b641ade29483e2e8c51c52d7b7ee50b0f7706e | tchaitanya2288/pyproject01 | /Sets_Methods/set_intersection_update.py | 346 | 3.9375 | 4 | #7 Set Intersection with Mutation = a_set.intersection_update()
# Syntax: a_set.intersection_update(an_iter)
# Example:
s = set([1, 2, 3, 4, 5,6,12,6])
s.intersection_update(set([3,5, 6, 7,9,8]))
print(s)
#Output : set([5])
'''Mutates a_set to be the intersection of set a_set and
the set of elements in iterable... |
f7aa3779022e264148662b6baa50efcabd1889d6 | tchaitanya2288/pyproject01 | /Mysql_Db/DBTest.py | 522 | 3.53125 | 4 | #!/usr/bin/python
import MySQLdb as sqldb
# Open database connection
db = sqldb.connect(host="localhost", user="root", password="P@ssw0rd", db="mysql")
# prepare a cursor object using cursor() method
cursor = db.cursor()
sql = "select * from emp where emp_age=25"
# execute SQL query using execute() method.
cursor.ex... |
6f5e0be8179eee4ea15eeb31baf53954cf803678 | tchaitanya2288/pyproject01 | /simple Elseif.py | 699 | 4.15625 | 4 | """
3. NESTED IF-ELSE STATEMENT :
>>> ord('A')
65
>>> ord("Z")
90
>>> ord('a')
97
>>> ord("z")
122
"""
char=input("Please enter any charcter : ")
if ord(char)>=65 and ord(char)<=90:
print ("You entered an upper case alphabet")
if char in ['A','E','I','O','U']:
print ("You entered A vowel.",char)
el... |
70254b54016e86245f50e27d972602ca3239f516 | tchaitanya2288/pyproject01 | /Functions/Find no of upper&lower.py | 237 | 3.90625 | 4 | def up_low(string):
upper = 0
lower = 0
for char in string:
if char.islower():
lower += 1
elif char.isupper():
upper +=1
else:
pass
return(upper, lower)
print(up_low('Python World And AWS Cloud'))
|
e18b5b5225528bdb43b72779517fc1eb1a6fb0c1 | chizel/BunchOfGames | /battleship.py | 5,503 | 4.21875 | 4 | #! /usr/bin/env python3
# -*- coding: utf-8 -*-
import random
class Board():
def __init__(self, size=10):
'''Board is square'''
self.size = 10
self.generate_board()
def generate_board(self):
self.board = [[0,] * self.size for _ in range(self.size)]
def place_ship(self, sh... |
cbb934f9c52f24a1a3cf2a4b867b6b9d604bc4fb | manasa1463/program | /p2.22.py | 114 | 3.75 | 4 | def gcd(x,y):
while(y):
x,y=y,x%y
return x
n2,n3=map(int,input().split())
print(gcd(n2,n3)) |
bb9ef29a6160d5e6e7100a3f9b73725c5c89d8bd | manasa1463/program | /p36.py | 166 | 3.734375 | 4 | count1=0
l=input()
count=len(l)
for i in l:
if (i.isalpha()) or (i.isspace()) or (i.isnumeric()):
count1=count1+1
count=count-count1
print(count)
|
a6698f8398c2199e7b374fa86a3bc5a31b0ec5f8 | manasa1463/program | /p66.py | 139 | 3.5625 | 4 | k=int(input())
sum1=0
for i in range(2,k//2):
if k%i==0:
sum1=sum1+1
if(sum1>0):
print("no")
else:
print("yes") |
c5147e20f05cff0ae251f27466b5fa6ba703ddc8 | manasa1463/program | /p2.43.py | 91 | 3.71875 | 4 | a,b=input().split()
if b in a:
print("yes",end='')
else:
print("no",end='') |
68325a1975f3033fa6cfbd19c1c121b1558d6eb6 | manasa1463/program | /p89.py | 125 | 3.671875 | 4 | str1=input()
l=[]
for i in range(0,len(str1)):
l.append(ord(str1[i]))
l.sort()
for i in l:
print(chr(i),end='') |
cefb147d123a81b24a88fa738487e69825035a8b | manasa1463/program | /p2.34.py | 78 | 3.640625 | 4 | s=input()
for i in range(len(s)):
if i%3==0:
print(s[i],end='') |
1aa599d70db416c8f9559ad93c557fe708b2cb3b | clcatalan/KNearestNeighbors | /KNN.py | 1,469 | 3.625 | 4 | import sklearn
from sklearn.utils import shuffle
from sklearn.neighbors import KNeighborsClassifier
import pandas as pd
import numpy as np
from sklearn import linear_model, preprocessing
def cleanData(colName):
#clean data via sklearn, put column values into a list, then fit_transform automatically changes it t... |
7bf7417c385f9b4f0e8c9671b7f1db4748525053 | za-webdev/Python-practice | /newstars.py | 497 | 3.859375 | 4 |
# takes a list of numbers and prints out
def draw_stars(my_count):
for x in range(len(my_count)):
x = "*"*my_count[x]
print x
draw_stars([4,6,1,3,5,7,25])
# when a string is passed instead of displaying * displays the first letter of the string as small letter
def new_stars(my_arr):
for x in range(len(my_... |
3dbaed02def20cc1c27d7ed07cce6be97942b78b | za-webdev/Python-practice | /score.py | 425 | 4.25 | 4 |
#function that generates ten scores between 60 and 100. Each time a score is generated,function displays what the grade is for a particular score.
def score_grade():
for x in range(1,11):
import random
x=(random.randint(60,100))
if x >60 and x<70:
z="D"
elif x>70 and x<80:
z="C"
elif x>80 and x<90:
... |
a2d0d1fdb6f98ed2786d0edb5e56c32fb1caaf82 | berkeley-agenright/w205-fall-17-labs-exercises | /exercise_2/topcounts.py | 707 | 3.84375 | 4 | #
# Aaron Enright
# Exercise 2
#
# topcounts.py - print the top words in the twitterstream
#
import sys
import psycopg2
def ShowTopWordCounts(limitNumber):
conn = psycopg2.connect(database="tcount", user="w205", password="", host="localhost", port="5432")
cur = conn.cursor()
cur.execute('SELECT word, count FROM t... |
b892b62a23788bbdf0d66f538003cdfc7fe596dc | paulbaumgarten/pti-timer | /app/timer.py | 2,826 | 3.53125 | 4 | import tkinter as tk
from datetime import datetime
import threading, time, math
####################################
# Intialise
####################################
class Timer():
def __init__(self, parent):
self.window = parent
self.keep_ticking = True
self.window.title("Parent teacher i... |
6495197764e8d1356c8fc39ccb482a0bb322ab0b | TalmSnir/Python_Mini_Projects | /randomgame.py | 558 | 3.984375 | 4 | import random as rnd
import sys
first_num, second_num = sys.argv[1], sys.argv[2]
keep_playing = 'y'
while keep_playing == 'y':
try:
user_guess = input(
"Please enter a number between {} to {}: ".format(first_num, second_num))
except
random_num = rnd.randint(int(first_num), int... |
db6dab9bcdd27f7f93d6cb617f45bc83b5681161 | Steve-Pham/DSA-Python | /hashTable.py | 3,051 | 3.875 | 4 | # Hash table implementation in Python
# With linear probing, going up by 1
class HashTable:
def __init__(self):
# Initial size of hash table
self.size = 11
#This is where the keys are stored
self.slots = [None] * self.size
#This is wehre the values are stored
se... |
55231fce836e008bd90cf83f4f7774f0937388cd | Steve-Pham/DSA-Python | /binaryTree.py | 11,088 | 4.28125 | 4 | class BinarySearchTree:
# Initialize the Binary Tree
def __init__(self):
self.root = None
self.size = 0
# Size of the Binary Tree
def length(self):
return self.size
# Private operator of the obtaining the size of the Binary Tree
def __len__(self):
ret... |
ce3e0d0eee7e215cbedd71e2b79ab4f8cc42f631 | sakuya9t/hack_assembler | /labelList.py | 746 | 3.65625 | 4 | class labelList:
list={}
def __init__(self):
self.add("SP", 0)
self.add("LCL", 1)
self.add("ARG", 2)
self.add("THIS", 3)
self.add("THAT", 4)
self.add("R0", 0)
self.add("R1", 1)
self.add("R2", 2)
self.add("R3", 3)
self.add("R4", 4)
self.add("R5", 5)
self.add("R6", 6)
self.add("R7", 7)
self.... |
9a36a5bee0211b57afbfcd62ce4e5f20b4bc2a36 | viktoriashandybina/PythonIVT | /4sem/4. Встроенные коллекции/ИСР.py | 725 | 3.640625 | 4 | from random import randint
def sort(nums):
for i in range(1, len(nums)):
k = nums[i]
j = i - 1
while j >= 0 and nums[j] > k:
nums[j + 1] = nums[j]
j -= 1
nums[j + 1] = k
z = []
for i in range(10):
z.append(randint(-10, 10))
sort(z)
pri... |
9fa6394bc5864aaa4cae5d5ee9e2997126290e8d | jsouza/text_utils | /src/avg_sent_len.py | 356 | 3.625 | 4 | #!/usr/bin/env python
import sys
import codecs
from nltk import FreqDist
def main():
args = sys.argv
input_file = codecs.open(args[1], 'r', 'utf-8')
fd = FreqDist()
for line in input_file:
tokens = line.split(" ")
for token in tokens:
fd[token.lower()] += 1
print "Number of unique occurrences = ", fd.B()... |
204e14b56d6dcea7aab5bbb43a8bc07943fe5f2a | vijay-arya/AIX360 | /aix360/algorithms/rule_induction/trxf/core/feature.py | 5,076 | 3.75 | 4 | import numbers
import tokenize
from io import BytesIO
from typing import Dict, Any
OPERATORS = ['+', '-', '*', '/']
PARENTHESES = ['(', ')']
def is_number(s):
try:
float(s)
return True
except ValueError:
return False
class Feature:
def __init__(self, expression: str):
""... |
1f6c593563dcdc03ac655c7efbf4d236ed5807e0 | jayanth-holalkeri/TIC_TAC_TOE | /tictactoe.py | 2,098 | 3.78125 | 4 | import os
arr = [x for x in range(0, 10)]
def print_board():
i = 0
# 7 8 9
# 4 5 6
# 1 2 3
os.system('cls')
k = 7
while k > 0:
i = k
j = k + 3
while i < j - 1:
print(arr[i], end=" |")
i += 1
print(arr[i]... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.