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 |
|---|---|---|---|---|---|---|
270590eb2edfe48f5eafa4737b292ba8d8a1f1df | Lexkane/PythonPractice | /Python Yandex/Lesson 8 Functional/IterateIterator.py | 1,475 | 3.65625 | 4 | import functools
import itertools
def main():
pass
def all_equal(iterable):
iterator=iter(iterable)
first_element=next(iterator)
for element in iterator:
if element !=first_element:
return False
return True
sequence =[1,2,3,4,5,6,7,8,9,10]
map(str,[1,2,3])... |
7a69b048b176bf2d02892d0d4f3314c83320c45b | Lexkane/PythonPractice | /Python Yandex/Lesson 9 Context/GettAttribute.py | 225 | 3.5 | 4 | def main():
pass
class A(object):
def __init__(self):
self.x = 1
def __getattribute__(self, name):
return(super(A, self). __getattribute__('x')+1)
a = A()
print(a.x)
print(a.y)
|
a34b1ff29b6a6d213e4509e90b791ab142632fc9 | jokfun/astrocalc | /priority.py | 681 | 3.578125 | 4 | def createPriority(tab):
"""
Convert the input priority into an array
Default : [1,1,1,1,1]
"""
try:
tab = tab.replace(",",".")
if(" " in tab and ";" in tab):
tab = tab.replace(" ",";")
if(";" in tab):
tab = tab.split(";")
else:
... |
db05ddb5fe9ca717fd6b5451c415d441d85400d0 | marutaku/spring_study | /fvnc.py | 215 | 3.671875 | 4 | #fvnc.py
def sumfvnc(fvnc):
return fvnc[-1] + fvnc[-2]
number = int(input())
fvnc = []
for i in range(number):
if i <= 1:
fvnc.append(i)
else:
fvnc.append(sumfvnc(fvnc))
print(fvnc) |
c367afa8c699ded53da9352f64822cd0538a51ac | Adrian-P0gar/CodeWars | /6.py | 726 | 4 | 4 | '''Implement the function unique_in_order which takes as argument a sequence and returns
a list of items without any elements with the same value next to each other and preserving the original order of elements.'''
# test.assert_equals(unique_in_order('AAAABBBCCDAABBB'), ['A','B','C','D','A','B'])
def unique_in_orde... |
796be8f59f2f8f18b62e9da41ecffdfb16176761 | 0-one/AM207_Project_Deep_Learning_Uncertainties_Calibration | /report/code/calibration.py | 6,245 | 3.71875 | 4 | import numpy as np
from sklearn.isotonic import IsotonicRegression
import dask
import dask.array as da
def calculate_quantiles(samples, y):
""" Function to compute quantiles of y within the given samples.
For efficiency, this function does not distinguish even and odd
number of samples, N. This should no... |
f192c195a612a86fd663f743a3a2e283ad868e46 | OleksiiBondarr/evo2018_2 | /start.py | 3,693 | 3.59375 | 4 | import random
class ServerSimulation:
"""
type_id - int тип заполнения серверов (1 - рандомное, 0 - зеркальное)
server_amount - int кол-во серверов
data_amount - int кол-во кусков данных
data_chunks - словарь: key - номер сервера, value - список кусков данных
"""
data_chunks = {... |
f087183fb7d71ba9d79176f6ebdce5ca876c9d52 | florianrougier/learn_python_the_hard_way | /ex15.py | 268 | 3.9375 | 4 | from sys import argv
script, filename = argv
prompt = '> '
txt = open(filename)
print "Here's your file %r" % filename
print txt.read()
print "Type the filename again please"
filename = raw_input(prompt)
# Read the file again
txt = open(filename)
print txt.read()
|
f20cd578d70ad8d3286f48fde61dcff2561df099 | DrDavxr/Water-Rocket-Simulator | /Integration.py | 6,194 | 3.671875 | 4 | """
Integration module.
"""
# Import the modules.
import numpy as np
from Water_Forces import Water_Forces
import Equations_of_Motion as EOM
import Water_Equations as WE
import Air_Equations as AE
def Simulation(x, state_vector, step, alpha, delta, g, D, d, m_tot, P_amb, P_1,
T_init, V=2e-3):
"""
... |
dbd366d6ab9e7286b11d5c4d8b2025ecc4c982c9 | UR-INF/pylab3-razor9869 | /Zadanie 4.py | 295 | 3.671875 | 4 | import numpy
def arr(first_row):
size = len(first_row)
array = numpy.zeros((size, size), dtype=numpy.longlong);
array[0] = first_row
for i in range(1, size):
array[i] = numpy.power(array[i - 1], 2)
return array
first_row = (2, 3, 4, 5, 6)
print(arr(first_row))
|
78b6eb4b69f8355797a6a657ab2fd60b702c04c5 | mikematic/utilities | /mydict.py | 3,513 | 3.5625 | 4 | #!/usr/bin/python
#===============================================================================
# @Mikematic
# 01.31.2011
#
# Extending the dictionary class to implement filtering methods.
# Dictionary filtering methods like minus, absoluteMinus, intersection,
# absoluteIntersection etc
#==========================... |
444815c498461b5183c5551a83407367d3008b3e | Dgama/Eric-Matthes-Python-Programming | /alien_invasion/ship.py | 1,408 | 3.71875 | 4 | #飞船的特性,绘制以及特性更新
import pygame
from pygame.sprite import Sprite
class Ship(Sprite):
def __init__(self,ai_settings,screen):
super().__init__()
#初始化飞船并设置初始位置
self.screen = screen
#加载飞船图像,并获取外接矩形
self.image=pygame.image.load('images/fly_object.bmp')
self... |
37b40482ffb0f3a1a2202945a2fb16e9dec71a73 | itsvanshchavda/Addition | /Addition.py | 104 | 3.921875 | 4 | num1=int(input("Enter no 1:"))
num2=int(input("Enter no 2:"))
print(num1,"+",num2,"=",num1+num2)
|
33425414dba3936ba29521dd2e2678767e8b4be8 | Kaue-Romero/Crie_seu_minigame | /Jogo/Codigo.py | 843 | 3.609375 | 4 | from time import sleep
def Escolha():
valido = False
while not valido:
entrada = str(input("Sua escolha: ")).strip()
if entrada != '1' or entrada == '':
if entrada != '2' or entrada == '':
print(f'\033[:31mERRO: \"{entrada}\" não é uma escolha válida!\033[m')
... |
818f452713e6fce3908f59df610f6a9e4dd073b9 | mo2274/CS50 | /pset7/houses/import.py | 1,508 | 4.375 | 4 | from sys import argv, exit
import cs50
import csv
# check if the number of arguments is correct
if len(argv) != 2:
print("wrong argument number")
exit(1)
# create database
db = cs50.SQL("sqlite:///students.db")
# open the input file
with open(argv[1], "r") as characters:
# Create Reader
reader_csv ... |
f6993e4df0bcd0037e1cbb4a2446e8fdcd9e2f28 | AuthenticAungZinMyint/Python_Basics | /python Ch5/proj1.py | 4,010 | 4.21875 | 4 | Python 3.8.2 (tags/v3.8.2:7b3ab59, Feb 25 2020, 22:45:29) [MSC v.1916 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license()" for more information.
>>> #hero iventory 3.0
>>> #demo lists
>>> #create list with some items and display with a for loop
>>> iventory = ["sword", "armor", "shield", "healing... |
f21ecbbaa094aac6229251e9800f7e3d7a26b5dd | AuthenticAungZinMyint/Python_Basics | /python Ch5/proj5.py | 2,216 | 4.03125 | 4 | #Hangman game
# The classic game of Hangman.The computer picks a random word
# and the player wrong to guess it, one letter at a time. If the player
# can't guess the word in time, the little stick figure gets hanged.
# imports
import random
#constants
HANGMAN = (
"""
------
| |
|
|
|
|
|
|________
""",
"""
------... |
b3f7e58d676b63a24bd35813ca53964ad55f22e5 | pydev101/LibarySystem | /studentAPI.py | 1,781 | 3.796875 | 4 | class student():
def __init__(self,lastName,firstName, mInit,grade,redeemCode):
self.lName = lastName
self.fName = firstName
self.mInit = mInit
self.grade = grade
self.redeemCode = redeemCode
self.booksOut = []
listOfStudents = []
def illiterate(funct):
for ... |
3ea90c286f9ed0609d83ec7b1493aa59013318b7 | jingyus/localhub | /mytest/list.py | 816 | 3.703125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Mon Jan 08 15:28:50 2018
@author: jcy
"""
#1
print "------------------1----------------------"
list1 = ['physics', 'chemistry', 1997, 2000];
list2 = [0,1, 2, 3, 4, 5, 6, 7 ];
print "list1[0]: ", list1[0]
print "list2[1:5]: ", list2[1:5]
#2
print "------------------2------------... |
6d471c072a7c4971cefa6d45566a209c0d581711 | celvro/sigcomp_sp15 | /Problem3/prob3.py | 365 | 3.671875 | 4 | def max_subarray(l):
test_max = l[0]
curr_max = l[0]
for x in l[1:]:
test_max = max(x, test_max+x)
curr_max = max(curr_max, test_max)
return curr_max
n = int(raw_input())
while n:
l = list()
for i in range(n):
l.append(int(raw_input()))
print... |
2b8fc8350dee8dc5807cd7737c49d79320518a2e | ManInBlue917/Advent-Of-Code-2020 | /Day2Part2.py | 838 | 3.53125 | 4 | lines = []
valid_passwords = 0
#read and parse lines
with open('Day2PuzzleInputs.txt', 'r') as file:
lines = file.readlines()
for i in range(len(lines)):
lines[i] = lines[i].replace('-', " ")
lines[i] = lines[i].replace(':', '')
lines[i] = lines[i].split(' ')
lines[i][3] = line... |
b42156bf15c05c14614df2e69610adc5dd0ec035 | AlexChew97/Create-Spotify-Playlist-by-Scraping-Billboard-hot-100-Charts | /main.py | 1,676 | 3.625 | 4 | from bs4 import BeautifulSoup
import requests
import spotipy
from spotipy.oauth2 import SpotifyOAuth
import os
date = input("Which year do you want to travel to? Type the date in this format YYYY-MM-DD: ")
url = f"https://www.billboard.com/charts/hot-100/{date}"
response = requests.get(url)
soup = BeautifulSo... |
372093f9d5abcae4468f51b5dbc53cd3f86ade51 | Maxclayton/cs1400 | /main2.py | 532 | 3.859375 | 4 | name = input("What is your name? ")
flavor = input("What is your favorite flavor of ice cream? ")
th = int(input("What is the tub Height? "))
td = float(input("What is the tub Diamater? "))
sd = int(input("What is the scoop Diameter? "))
tr = (td/2) #tubRadius
tv = (th*(tr*tr)*3.14159265359) #tubVolume
sr = (sd/2)... |
4428f4dbe33b2ea1f148fcdbf171d68864f8cc77 | vincom2/11411-project | /answer_files/answer.py | 2,602 | 3.53125 | 4 | #!/usr/bin/env python
"""TODO:
identify if question is a yes/no question. if it's a yn question, after extracting the most relevant sentence,
check if it's negative. If it is, say no. Otherwise, say yes. We probably want to be a lot more careful about this,
but this will do for a start."""
from nltk.tokenize... |
09cf4d7aa49637aa3945786fb49ca9623df40c56 | Anastasiya999/Python | /zestaw6/test_points.py | 1,509 | 3.6875 | 4 | import unittest
import math
from points import *
class TestPoint(unittest.TestCase):
def setUp(self):
self.point1=Point(1,2)
self.point2=Point(-5,2)
self.zero=Point(0,0)
def test_print(self):
self.assertEqual(str(self.point1), "(1, 2)")
self.assertEqual(repr(s... |
606c6db0d96fdd877bfb4fdcd05c44706d7c09ac | Anastasiya999/Python | /zestaw2/zad_12.py | 695 | 3.59375 | 4 | line="\tLooking out my window\n\tIn October's golden light,\n\tI see a beauty unsurpassed,\n\tA truly lovely sight"
line_list=line.split()
sentenceOfFirstChar=""
sentenceOfLastChar=""
#pierwszy sposób
for item in line_list:
sentenceOfFirstChar+=item[0]
sentenceOfLastChar+=item[-1]
#print("expression built from ... |
a5845928e0ed9d57d3db3f7269cbfed5de59d918 | Anastasiya999/Python | /zestaw7/triangles.py | 2,750 | 3.890625 | 4 | from points import Point
import math
class Triangle:
"""Klasa reprezentująca trójkąt na płaszczyźnie."""
def __init__(self, x1, y1, x2, y2, x3, y3):
"""Konstruktor"""
if self.check_collinear(x1, y1, x2, y2, x3, y3):
raise ValueError("Punkty leżą na jednej prostej")
self.pt1 ... |
90a04af7f0c783296d7f7f16e79ac2e40d5be965 | Anastasiya999/Python | /zestaw8/zad_1.py | 1,533 | 3.625 | 4 | # 8.1
# SPECYFIKACJA
# Problem: Rozwiązywanie równania liniowego a x + b y + c = 0.
#
# DANE WEJŚCIOWE
# Trzy liczby a, b i c, będące współczynikami równania.
#
# DANE WYJŚCIOWE
# Rozwiązanie równania, w postaci komunikatu
#
# LISTA KROKÓW
# K01: jeżeli a=0 oraz b=0 przejdż do K03, w przeciwnym wypadku do K02
# K02: je... |
97d5785174b040ee5a24a2b76bb648a63d7601d5 | Anastasiya999/Python | /zestaw3/zad_8.py | 245 | 3.65625 | 4 | seq1=list(range(1,7))+list(range(2,10,2))
print(seq1)
seq2=list(range(2,7))+list(range(3,10,3))
print(seq2)
#a)
print("Elementy wspólne: "+str(set(seq1).intersection(set(seq2))))
#b)
print("Suma elementów: "+str(set(seq1).union(set(seq2)))) |
84e26d7e7af669cb1d7e8cbe5e2ae727c1220b2e | funkmaster-hex/pythonstuff | /final.py | 4,800 | 3.59375 | 4 | #!/usr/bin/env python3
import math
def getfilename():
file = input("Enter the absolute path to your file: ")
return file
def getcodetype():
print ("Enter the algorithm you wish to use: ")
print ("1)Base2 ")
print ("2)Base16 ")
print ("3)Base32 ")
print ("4)Base64 ")
codechoice = int(in... |
c0c0111f66cd6874b296e2dc3ec34cc4261c90c3 | ekdus1203/Python_Lecture0802 | /연산자오버라이드.py | 419 | 3.78125 | 4 | #연산자 오버라이드
class NumBox:
#초기화
def __init__(self, num):
self.Num = num
#+연산자 ==> 일반 인스턴스 메서드
def __add__(self, num):
self.Num += num
#-연산자
def __sub__(self, num):
self.Num -= num
#인스턴스 생성
n = NumBox(40)
n.add(100)
print(n.Num)
n.remove(110)
print(n.Num)
#인스턴스 생성
#n = NumBox(40)
#n + 100
#print(n.Num)
#n... |
b1c8a998d27d4ab788ebb99e5bcab4ecb62bf981 | jhonatang1988/holbertonschool-machine_learning | /supervised_learning/0x08-deep_cnns/5-dense_block.py | 2,015 | 3.625 | 4 | #!/usr/bin/env python3
"""
builds a dense block as described in Densely Connected Convolutional Networks
https://arxiv.org/pdf/1608.06993.pdf
DenseNet-B implementation
"""
import tensorflow.keras as K
def dense_block(X, nb_filters, growth_rate, layers):
"""
builds a dense block as described in Densely Connect... |
a2e604538d3d3456effff4c01c6d907ff87e9456 | jhonatang1988/holbertonschool-machine_learning | /supervised_learning/0x04-error_analysis/4-f1_score.py | 703 | 3.515625 | 4 | #!/usr/bin/env python3
"""
calculates the F1 score of a confusion matrix
"""
sensitivity = __import__('1-sensitivity').sensitivity
precision = __import__('2-precision').precision
def f1_score(confusion):
"""
calculates the F1 score of a confusion matrix
:param confusion: numpy.ndarray of shape (classes, c... |
24e77e47b501b9a8a050668246d917c37c1e0e5b | jhonatang1988/holbertonschool-machine_learning | /supervised_learning/0x04-error_analysis/3-specificity.py | 744 | 3.9375 | 4 | #!/usr/bin/env python3
"""
calculates the specificity for each class in a confusion matrix
"""
import numpy as np
def specificity(confusion):
"""
calculates the specificity for each class in a confusion matrix
:param confusion: is a confusion numpy.ndarray of shape (classes, classes)
where row indices... |
25ee03275f1cc2337007e7e4b7de9556c8213115 | jhonatang1988/holbertonschool-machine_learning | /supervised_learning/0x06-keras/13-predict.py | 660 | 3.953125 | 4 | #!/usr/bin/env python3
"""
makes a prediction using a neural network
"""
import tensorflow.keras as K
def predict(network, data, verbose=False):
"""
makes a prediction using a neural network
:param network: the network model to make the prediction with
:param data: the input data to make the predictio... |
ba22430afdb378c2d90fe82951eb335c1225ccb9 | jhonatang1988/holbertonschool-machine_learning | /supervised_learning/0x03-optimization/1-normalize.py | 318 | 3.625 | 4 | #!/usr/bin/env python3
"""
normalize (standardizes) a matrix
"""
import numpy as np
def normalize(X, m, s):
"""
normalize (standardizes) a matrix
:param X: (d, nx) data to normalize
:param m: mean
:param s: stddev
:return: the normalized matrix
"""
Norm = (X - m) / s
return Norm
|
44c75d28f3551eaf1adc3cfca064c71567a869c8 | jhonatang1988/holbertonschool-machine_learning | /math/0x02-calculus/10-matisse.py | 696 | 4.09375 | 4 | #!/usr/bin/env python3
"""
derivatives for polys
[5, 3, 0, 1]
"""
# poly = [-5, 0, 0, 0, 2, 0, 0, 1]
# = [0, 0, 0, 8, 0, 7]
# x7 + 2x4 - 5
# 8x3 + 7x6
def poly_derivative(poly):
"""
main
:param poly: polynomial
:return: derivative of polynomial
"""
if type(poly) is not list or len(poly) == 0... |
4693c2c9aa161fa1cc59e5d5a6e2e7f8d0594977 | raghunath-v/RRT | /Obstacle.py | 1,608 | 3.5625 | 4 | from graphics import Polygon
import numpy as np
from g_tools import ray_intersects_segment, gen_point_list, scale_points, segments_intersect, segment_intersects_circle
class Obstacle:
"""
An obstacle has both a graphical and a
numerical representation
"""
def __init__(self, points, win):
... |
569ead1aa28662ed9e9318caf335ba380969946d | lexic92/SPOJ | /1_LifeTheUniverseAndEverything.py | 184 | 4.0625 | 4 | # Repeat indefinitely until you read the number 42.
while True:
inputNumber = int(raw_input())
if inputNumber == 42:
break
else:
print inputNumber
exit(0) |
ea1f78216920dd773c336204846792b2b68f1642 | create92/CodingTestPractice | /Implementation/Implementation4-4.py | 858 | 3.53125 | 4 | '''
<문제> 문자열 재정렬
알파벳 대문자와 숫자(0 ~ 9)로만 구성된 문자열이 입력으로 주어집니다.
이때 모든 알파벳을 오름차순으로 정렬하여 이어서 출력한 뒤에, 그 뒤에 모든 숫자를 더한 값을 이어서 출력
<문제 해결 아이디어>
1. 문자열이 입력되었을 때 문자를 하나씩 확인
- 숫자인 경우 따로 합계를 계산
- 알파펫의 경우는 별도의 리스트에 저장
2. 결과적으로 리스트에 저장된 알파벳을 정렬해 출력하고, 합계를 뒤에 붙여 출력하면 정답
'''
input_data = input()
alphabet = ""
total_sum = 0
for ch i... |
84fa805056762931dad006a0106944eb7b15699c | CarowlCarvalho/Exercicios_Python | /aula06a.py | 143 | 3.8125 | 4 | n1 = int (input('Digite um valor: '))
n2 = int (input('Digite outro: '))
s = n1 + n2
print ('A soma entre {} e {} vale, {}'.format(n1, n2, s))
|
023a6304cb8a89abf19b594446db3a9fdb7704d4 | TheDocTrier/personal | /school/memorize.py | 706 | 3.640625 | 4 | import random
diff = input('Diff: ')
diff = int(diff)
assert(diff > 0)
while True:
pairs = [0 for i in range(diff)]
for i in range(2 * diff):
print('\n' * 50)
ran1 = random.randint(1, diff)
ran2 = random.randint(1, diff)
pairs[ran1 - 1] = ran2
print(str(ran1) ... |
d14dac451049f0544acb9256acfc815fa7695b57 | Yash27112006/C98-swap-contents | /swappingFile.py | 723 | 3.90625 | 4 | def swapFileData():
print("!! Welcome to Swap The Data Program !!")
name = input("Enter your first name: ")
print("Hi!", name)
print("Please tell me the name of the files whose data you want to swap :- ")
firstFile = input("Enter the name of first file: ")
secondFile = input("Enter the... |
aab750a2a0ee25fd1a8f8f3c171c84d70a38aa78 | m-bojenko/cs102 | /exam1/waaay.py | 3,905 | 3.78125 | 4 | from typing import Tuple, List
def read_map(filename: str) -> List[List[str]]:
""" Прочитать карту из указанного файла """
grid = [[]]
line = 0
for c in open(filename).read():
if c in 'hxc.12345':
grid[line].append(c)
elif c == '\n':
grid.append([])
... |
5ba6c39cdc9994bb6c1917a9897c813df6ff7184 | LeoJMaro/python-games | /squr.py | 156 | 4.34375 | 4 | #!/usr/bin/env python3
num = float(input("Number to know the square root of "))
num_s = num**0.5
print("the squre root of {} is {:.3}".format(num, num_s)) |
cc15758c3077198d858c5fa708ba49ad63bffa0b | gavinpppeng/COMP9021 | /Quiz/quiz_7.py | 2,279 | 4 | 4 | # Defines two classes, Point() and Disk().
# The latter has an "area" attribute and three methods:
# - change_radius(r)
# - intersects(disk), that returns True or False depending on whether
# the disk provided as argument intersects the disk object.
# - absorb(disk), that returns a new disk object that represent... |
6e4b97d54fe11b41c16f0cc897451b6c60c30b21 | gavinpppeng/COMP9021 | /Exams/final/sample_2.py | 995 | 3.9375 | 4 |
def f(N):
'''
>>> f(20)
Here are your banknotes:
$20: 1
>>> f(40)
Here are your banknotes:
$20: 2
>>> f(42)
Here are your banknotes:
$2: 1
$20: 2
>>> f(43)
Here are your banknotes:
$1: 1
$2: 1
$20: 2
>>> f(45)
Here are your banknotes:
$5: 1
... |
46ce1ce4c1f1bd02d259d36aa102978bf6a5b563 | HarryC145/PythonBits | /PythonRateCalculator.py | 1,466 | 3.84375 | 4 | # Do our import
import subprocess, sys
# This is a script that is going to work out the hourly rate of pay for an employee
# Introduce the script
print("Welcome to the Hourly Rate Calculator for Example Company")
# Collect Employee information - also declares some of our variables
EmployeeNumber = input("What is ... |
7a6a951ecdc4780754d439cb69a9839e573b58d7 | sannezijlstra/timesavers | /code/algorithms/beam_search.py | 2,773 | 3.5625 | 4 | from .breadth_first import BreadthFirst
from code.classes import board, cars
from code import helpers
import queue
import copy
import time
import bisect
class BeamSearch(BreadthFirst):
"""
The Beam Search algorithm is a heuristic based algorithm, where the queue(list) is pruned on the arbitrary count of 10.000... |
0ad987d77b1ed6793f8dbda50fa447d9d04edda9 | Halliom/AdventOfCode2016 | /3/part1.py | 365 | 3.921875 | 4 | # Converts every line into an array of 3 integers
data = [map(int, line.split()) for line in open("input.txt")]
possible = 0
for tri in data:
# Check if the sum of any combination of two sides is less than then third
if tri[0] + tri[1] <= tri[2] or tri[0] + tri[2] <= tri[1] or tri[1] + tri[2] <= tri[0]:
... |
92ba77a1651b2da2a26d064fc55691bf0e66f31e | circlecookies/PYTHON | /question5.py | 309 | 3.515625 | 4 | import random
a=random.sample(range(1,100),10)
b=random.sample(range(1,100),10)
#a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
#b = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]
new_list = []
for i in a:
for x in b:
if i == x:
new_list.append(i)
print a
print b
print new_list
|
d56d83109a66b60b73160c4a45d770d01ef76274 | Stuff7/stuff7 | /stuff7/utils/collections/collections.py | 1,021 | 4.1875 | 4 | class SafeDict(dict):
""" For any missing key it will return {key}
Useful for the str.format_map function when
working with arbitrary string and you don't
know if all the values will be present. """
def __missing__(self, key):
return f"{{{key}}}"
class PluralDict(dict):
""" Parses keys with the form "k... |
6f40579a5b7310605a5644540de3b6658ce4c8d1 | leonardoalvesprodepa/python_para_zumbis | /Lista de Exercicios/Lista_de_Exercicios_2/exercicio2.py | 256 | 3.875 | 4 | ano = int(input('Digite o ano para saber se é bissexto: '))
if ano % 4 == 0 and ano % 100 != 0:
print 'O ano de %d é bissexto' % ano
elif ano % 400 == 0:
print 'O ano de %d é bissexto' % ano
else:
print 'O ano de %d não é bissexto' % ano
|
eede20498acf4df8271fe110482ecfe884739686 | SamNgigi/Contact-List | /contact_test.py | 4,761 | 4.0625 | 4 | #!/usr/bin/env python
# Importing the unittest module
import unittest
# Importing Contact class
from contacts import Contact
# Importing pyperclip
import pyperclip
class TestContact(unittest.TestCase):
"""
We define the TestContact sub-class that defines our test for the
Contact class.
Args:
unitt... |
6bde90d948d676711c7e0117cd0ce2b57858c979 | shrutikiran/datastructures-algorithms-practice | /merge-sort.py | 1,039 | 3.796875 | 4 | import sys
def merge(arr, startIx, endIx, mid):
mergeIx = startIx
lIx = 0
rIx = 0
lArr = arr[startIx:mid]
rArr = arr[mid:endIx]
while (lIx < len(lArr) and rIx < len(rArr)):
if (lArr[lIx] <= rArr[rIx]):
arr[mergeIx] = lArr[lIx]
lIx += 1
else:
... |
c6dd0ae43898d215e204e7c065366e0d797ed090 | jordisoler/dmpsArDrone | /utils/coordMouse.py | 248 | 3.5 | 4 | # -*- coding: utf-8 -*-
"""
Created on Thu Jan 21 17:56:55 2016
@author: jordi
"""
import Tkinter as tk
root = tk.Tk()
def motion(event):
x, y = event.x, event.y
print('{}, {}'.format(x, y))
root.bind('<Motion>', motion)
root.mainloop() |
c7b5890292c7d2aae005d9d2e3c58396acaf9fce | JuddLunt/Pygame-Arcade | /GAME BASE.py | 3,197 | 3.921875 | 4 | # This file provides some code for you to get started with your game.
# Hopefully you understand the basics of python and pygame by now.
#
# If you have any questions, please feel free to ask Will or Kian for help.
#
# Also, please remeber to change this file to be the name of your game.
import pygame, os
from pygame.... |
bb2642db8f5384ad42a82a6f6d31d7defe960236 | vinaud/Exercicios-Python | /Matrizes/dimensoes_matriz.py | 183 | 3.6875 | 4 | #Função que receb uma matriz e retorna suas dimensões
def dimensoes(matriz):
dimensoes = ''
dimensoes = str(len(matriz)) + 'x' + str(len(matriz[0]))
print(dimensoes)
|
91ef738a2c53cbe0c007aa87e8a886982b8e206c | vinaud/Exercicios-Python | /Condicionais/ordenacao.py | 319 | 4.03125 | 4 | # recebe tres numeros inteiros e verifica se foram inseridos em ordem crescente
a = int(input(" insira o primeiro valor: "))
b = int(input(" insira o sgundo valor: "))
c = int(input(" insira o terceiro valor: "))
if a <= b and a <= c and b <= c:
print("crescente")
else:
print("não está em ordem crescente")
|
7d166dc20bebd7674ada71119a26190da372d140 | vinaud/Exercicios-Python | /Repeticoes/digitos_adjacentes.py | 330 | 3.9375 | 4 | #verifica se um numero tem dois digitos adjacentes iguais
n = int(input("Insira um numero natural"))
n2 = n
digito1 = 0
digito2 = 0
igual = False
while n2 != 0:
digito1 = n2 % 10
n2 = n2 // 10
digito2 = n2 % 10
if digito1 == digito2:
igual = True
if igual:
print("sim")
else:
print(... |
6d9bb4bd2fbe887e3919e82d9abefda7ad6547e4 | vinaud/Exercicios-Python | /Listas/remove_reptidos.py | 222 | 3.578125 | 4 | def remove_repetidos(lista):
lista2 =[]
for i in lista:
if i not in lista2:
lista2.append(i)
lista2.sort()
return lista2
print(remove_repetidos([7,3,33,12,3,3,3,7,12,100])) |
5ac7451d71c83f54514a31b232eda2be68de5abc | vinaud/Exercicios-Python | /Repeticoes/primalidade.py | 238 | 3.890625 | 4 | #verifica se um número é primo
n = int(input("Insira um numero natural"))
isPrimo = True
i=1
while i!=n:
if i>1 and n % i == 0:
isPrimo = False
i = i + 1
if isPrimo:
print("primo")
else:
print("não primo")
|
5fdd9607564a70b74cbab892584f6c9f6a83d532 | vinaud/Exercicios-Python | /Recursividade/elefantes.py | 1,044 | 4.15625 | 4 | """
Implemente a função incomodam(n) que devolve uma string contendo "incomodam "
(a palavra seguida de um espaço) n vezes. Se n não for um inteiro estritamente positivo,
a função deve devolver uma string vazia. Essa função deve ser implementada utilizando recursão.
Utilizando a função acima, implemente a função ele... |
54330536cb5b2c1da734f7760e9d81dde245da4e | crobertz/AOJ | /alds1/alds1_1/primes.py | 290 | 3.84375 | 4 | # ALDS1_1_C
# Prime numbers
import math
n = int(input())
count = 0
def isprime(x):
for d in range(2,int(math.sqrt(x) + 1)):
if x % d == 0:
return False
return True
for i in range(n):
x = int(input())
if isprime(x):
count += 1
print(count)
|
b623906e6e23b7d055e7b04f2f4eddd0042e0637 | bradgarropy/pathfinding | /grid.py | 5,403 | 4.1875 | 4 | """
grid.py
Module for creating and manipulating two dimensional grids.
"""
import node as n
import math
class Grid(object):
"""Class for creating and manipulating two dimensional grids."""
def __init__(self, width, height):
self.width = width
self.height = height
self.nodes = {}
... |
b1824c70b839c60c36c50231b357c81df0a633a1 | nemmiz/aoc2017 | /python/09.py | 727 | 3.703125 | 4 | #!/usr/bin/python3
def solve(data):
ignore = False
depth = 0
score = 0
garbage = False
removed = 0
for c in data:
if ignore:
ignore = False
continue
if garbage:
if c == '!':
ignore = True
elif c =... |
3373acc2f756120a49cae8ab40b0b3e3697d1f2f | jimlinntu/NASA2018 | /hw7/b04705003_NA/cryptolocker_decode.py | 3,245 | 3.625 | 4 | #!/usr/bin/env python3
import sys
import hashlib
import AESCipher
import cryptolock
import re
def hash(two_chars):
hashed = hashlib.sha256(two_chars).digest()
return hashed
def brute_force(ciphertext):
# Backward decode
possible_ciphertext_list = [[ciphertext], [], [], [], []]
decoder_key_list = ... |
ea40fe6fc4c31aeb3eafdcbbb767b337f7076e25 | lapulgaatomica/python-data-structures-and-algorithms | /iterative_binary_search.py | 436 | 3.96875 | 4 | def iterative_binary_search(list, target):
first = 0
last = len(list) - 1
while first <= last:
middle = (last + first) // 2
if target == list[middle]:
return middle
elif list[middle] < target:
first = middle + 1
elif list[middle] > target:
... |
11eff0ee9fbbc3679bf716ad1542b4572463be09 | mohitdhamankarr/squareroot | /sqroot.py | 141 | 4.09375 | 4 | a=int(input("Enter number for square root"))
sqroot=0
for i in range(1,a):
if(i//a)==i:
print("Square root is",i)
|
4174d96ddadfc43fa34d16e0a43ca5b90b608c44 | aha-oretama/nlp100 | /chapter3/q27.py | 4,271 | 3.546875 | 4 | """
27. 内部リンクの除去
26の処理に加えて,テンプレートの値からMediaWikiの内部リンクマークアップを除去し,テキストに変換せよ(参考: マークアップ早見表).
内部リンク
[[記事名]] 記事名
[[記事名|表示文字]] 表示文字
[[記事名#節名|表示文字]] 表示文字
"""
from q25 import get_basic_info
import re
def get_cleaned_data():
key_value = get_basic_info()
# https://docs.python.org/ja/3/library/re.html#re.sub
# (?:... |
9869b7fe5877823c75de358a32a4a937cfc06ace | aha-oretama/nlp100 | /chapter1/08.py | 281 | 3.6875 | 4 | def cipher(text):
return "".join([chr(219 - ord(c)) if 97 <= ord(c) <= 122 else c for c in text])
encode = cipher("Neither a borrower nor a lender be; For loan oft loses both itself and friend, And borrowing dulls the edge of husbandry.")
print(encode)
print(cipher(encode))
|
f8bfcb9aff0889670a3584cadfa8fc902182d364 | aha-oretama/nlp100 | /chapter1/02.py | 402 | 3.828125 | 4 | def join_across(text1, text2):
list1 = list(text1)
list2 = list(text2)
joined = []
for (char1, char2) in zip(list1,list2):
joined.append(char1)
joined.append(char2)
return "".join(joined)
print(join_across("パトカー","タクシー"))
print(join_across("パトカーアイウエオ","タクシー"))
print(join_across("パト... |
f7ca4aedf4026d2bf4a1e55a70b56d74fcfb841b | aha-oretama/nlp100 | /chapter1/03.py | 289 | 3.71875 | 4 | def sentence_to_word_length(sentence):
split = sentence.replace(",","").replace(".","").split(" ")
return "".join([str(len(text)) for text in split])
print(sentence_to_word_length("Now I need a drink, alcoholic of course, after the heavy lectures involving quantum mechanics."))
|
a40c1358a4944dbbf5eacac69727f2297df8ef0c | greenfrog82/DailyCoding | /Codewars/5kyu/5kyu_where_my_anagrams_at/src/main.py | 1,246 | 3.5625 | 4 | # def anagrams(word, words):
# ret = []
# for _word in words:
# if len(word) != len(_word):
# continue
# mark = [0] * len(word)
# for m in range(0, len(word)):
# base = word[m]
# for n in range(0, len(_word)):
# if not mark[n] and _wo... |
81056370079d3089494d28873cc57a01a752ebe8 | greenfrog82/DailyCoding | /Codewars/6kyu/6kyu_multiple_3_or_5/src/main.py | 277 | 3.515625 | 4 | import unittest
def mysolution(number):
return sum(i for i in range(number) if not i % 3 or not i % 5)
solution = mysolution
class Test(unittest.TestCase):
def test_1(self):
self.assertEqual(solution(10), 23)
if __name__ == '__main__':
unittest.main()
|
47d60f7ec3d6bcaacaa3525f761728e6e997569e | greenfrog82/DailyCoding | /Codewars/8kyu/8kyu_is_n_divisible_by_x_and_y/src/other.py | 211 | 3.84375 | 4 | def is_divisible(n, x, y):
return n % x == n % y == 0
print(is_divisible(3, 3, 4) == False)
print(is_divisible(12, 3, 4) == True)
print(is_divisible(8, 3, 4) == False)
print(is_divisible(48, 3, 4) == True)
|
5c63d44cd1fb9f9dc759456ac20636259e1c1761 | greenfrog82/DailyCoding | /etc/the_most_closest_two_point/src/main.py | 579 | 3.578125 | 4 | import unittest
import operator
def solution(param):
param = sorted(param)
param = [[abs(param[i]-param[j]), param[i], param[j]] for i in range(len(param)-1) for j in range(i, len(param)) if param[i] != param[j]]
param = sorted(param, key=operator.itemgetter(0))
return param[0][1::]
class Test(un... |
22dd8610f97a2cc28fff0eea3e8726af5151f57b | greenfrog82/DailyCoding | /Codewars/8kyu/8kyu_find_maximum_minimum_value_of_list/src/main.py | 702 | 3.703125 | 4 | def mysolution_min(arr):
return sorted(arr)[0]
def mysolution_max(arr):
return sorted(arr)[-1]
# ------------------------------
def othersolution_min(arr):
return min(arr)
def othersolution_max(arr):
return max(arr)
_min = othersolution_min
_max = othersolution_max
print(_min([-52, 56, 30, 29, -... |
aefa5b81ffeb36e08731286d4b99089e4927dad0 | greenfrog82/DailyCoding | /Codewars/2kyu/src/main.py | 577 | 3.5 | 4 | from random import random
import unittest
import re
solution = ''
for num in range(0,101):
if not num % 7:
print(bin(num)[2:] + ' : ' + str(num))
class Test(unittest.TestCase):
def test_case_1(self):
self.assertEqual(isinstance(solution, str), True, 'your solution is not a string')
def ... |
28194b8c8e24ae885a17f1c91b860d7cdfdfc441 | greenfrog82/DailyCoding | /Codewars/6kyu/6kyu_two_sum/src/main.py | 513 | 3.703125 | 4 | import unittest
def two_sum(numbers, target):
return next((i, numbers.index(target-v, i+1)) for i,v in enumerate(numbers) if target-v in numbers)
class Test(unittest.TestCase):
def test_1(self):
self.assertEqual(sorted(two_sum([1, 2, 3], 4)), [0, 2])
def test_2(self):
self.assert... |
0769b7c6160b31b2b98f2e56b7773697bd52654d | greenfrog82/DailyCoding | /Codewars/7kyu/7kyu_cartesian_neighbors/src/other_2.py | 231 | 3.84375 | 4 | def cartesian_neighbor(x, y):
return [(i, j) for i in range(x-1, x+2) for j in range(y-1, y+2) if (i, j) != (x, y)]
print [(1, 1), (1, 2), (1, 3), (2, 1), (2, 3), (3, 1),
(3, 2), (3, 3)] == cartesian_neighbor(2, 2)
|
49f5deb512c776fe628736a4a6e63fd7d5ef7b94 | greenfrog82/DailyCoding | /etc/category_tree/src/main.py | 1,274 | 3.640625 | 4 | class Node():
def __init__(self, name):
self.name = name
self.child = []
class CategoryTree:
def __init__(self):
self.root = None
def add_category(self, name, parent):
if not parent:
self.root = Node(name)
else:
if self.get_node(s... |
ae370d0ce5a8bf1b3d0915eb74b1f6f1dc1eeda1 | greenfrog82/DailyCoding | /Codewars/8kyu/8kyu_is_n_divisible_by_x_and_y/src/main.py | 215 | 3.953125 | 4 | def is_divisible(n, x, y):
return not n % x and not n % y
print(is_divisible(3, 3, 4) == False)
print(is_divisible(12, 3, 4) == True)
print(is_divisible(8, 3, 4) == False)
print(is_divisible(48, 3, 4) == True)
|
06cf3bdffa489e4fb18b31bd78cc6e305ba26427 | greenfrog82/DailyCoding | /Codewars/7kyu/7kyu_get_the_middle_character/src/main.py | 862 | 3.65625 | 4 | import unittest
def mysolution(str):
str_len = len(str)
center_offset = str_len // 2 - 1
return str[center_offset+1] if str_len % 2 else str[center_offset:center_offset+2]
def other_solution_1(str):
return str[(len(str)-1)//2:len(str)//2+1]
def other_solution_2(str):
index, odd = divmod(len(str),... |
c69946c0d72cc7a589b35db28fb2707d13e917f7 | sabrybarbato/sfera | /sfera.py | 147 | 3.921875 | 4 | import math
def volume(r)
v=(4.0/3.0*math.pi)*r**3
return v
r= input ("inserisci il raggio della sfera:")
r=int(r)
sf=volume(r)
print(sf) |
14bea7c5af8b9815609b330d07a0ff8daa3cfe10 | TylerLott/ds_algo | /python/trees/trees.py | 1,840 | 3.734375 | 4 | class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
def __str__(self):
return f"[v {self.val} l {self.left} r {self.right}]"
def create_bst(nums: list) -> TreeNode:
# take in list of numbers and return the ... |
cf11d938203154380d347e9c8b3d1d7afa0f1ba2 | juliarowe/ProjectEuler | /prob1.py | 141 | 3.78125 | 4 | #!
def addMultiples():
sum = 0
for x in xrange(1,1000):
if (x%3 == 0 or x%5 == 0):
sum = sum + x
return sum
print addMultiples() |
ad026b012bd4bcc29efffb6e161aba35961bdd84 | mashrafsiddiquee/iris_data | /closest_station_pair.py | 1,505 | 3.65625 | 4 | # @author Ashraf
# This python code finds the nearest station for each of the stations
# prints nearest station and the distance with nearest station in miles.
# For the stations (csv-text) file, make sure station name, lat and long values are in column 1, 2, 3
# Place the files in current directory and update the valu... |
9e253d0ef224ecb93a60a59ff84e2c1b1133c4f6 | luhpazos/Exercicios-Python | /Pacote download/Desafios/59.Criando um Menu de Opções.py | 1,170 | 3.90625 | 4 | from time import sleep
n1 = int(input('Digite o 1º valor:'))
n2 = int(input('Digite o 2º valor:'))
m = 0
while m != 5:
print('\033[36m=-\033[m'*20)
m = int(input('''O que você deseja fazer?
\033[31m[1]\033[m SOMAR
\033[31m[2]\033[m MULTIPLICAR
\033[31m[3]\033[m MAIOR
\033[31m[4]\033[m NOVOS NÚMEROS
\033[31m[5]\... |
b978e32f8df5ea90a1b533a1e1692818135d7800 | luhpazos/Exercicios-Python | /Pacote download/Desafios/52.Numeros Primos.py | 449 | 3.875 | 4 | # DESCOBRINDO SE O NUMERO É PRIMO
n = int(input('Digite um número inteiro qualquer:'))
t = 0
for c in range(1, n + 1):
if n % c == 0:
print('\033[33m', end='')
t = t +1
else:
print('\033[31m', end='')
print('{} '.format(c), end='')
print('\n\033[mO número {} foi dividido {} vezes, '.... |
89667cd7392f30c9eb9d0bc9928ecbccc72cbcea | luhpazos/Exercicios-Python | /Pacote download/Desafios/97. Um Print Especial.py | 224 | 3.75 | 4 | def escreva(msg):
c = len(msg) + 4
print('-' * c)
print(f' {msg}')
print('-' * c)
# programa principal
for s in range(0, 3):
escreva(str(input('Digite alguma frase ou palavra:')).strip().capitalize())
|
8180776100051abd3eaada9465651cd7e7416256 | luhpazos/Exercicios-Python | /Pacote download/Desafios/57.Validação de Dados.py | 256 | 3.890625 | 4 | s = str(input('informe seu sexo: [M/F]')).strip().upper()[0]
while s not in 'MF':
print('Opção inválida. Tente novamente')
s = str(input('Qual o seu sexo? [M/F]')).strip().upper()[0]
print('Sexo {} registrado com sucesso. Obrigado!'.format(s))
|
9ba1878f0cdf118030965deaae4c4148eb716c69 | luhpazos/Exercicios-Python | /Pacote download/Desafios/27.Primeiro e Ultimo Nome de uma Pessoa.py | 216 | 3.875 | 4 | n = str(input('Qual é o seu nome completo?')).strip().title()
print('O seu nome completo é {}'.format(n))
m = n.split()
print('Seu primeiro nome é: {}'.format(m[0]))
print('Seu último nome é: {}'.format(m[-1]))
|
74940dc906960fd3533e1627b4946bf9de1fcbcb | luhpazos/Exercicios-Python | /Pacote download/Desafios/15.Aluguel de Carros.py | 218 | 3.59375 | 4 | n = int(input('Por quantos dias o carro foi alugado?'))
m = float(input('Quantos Km foram percorridos com o veículo?'))
d = n * 60
km = m * 0.15
t = d + km
print('o cliente deve pagar um total de R${:.2f}'.format(t))
|
7e445f0afcbe01be0513fc0fa7cd9ee94a3e1a16 | luhpazos/Exercicios-Python | /Pacote download/Desafios/24.Verificando as Primeiras Letras de um Texto.py | 129 | 3.734375 | 4 | c = str(input('Em qual cidade você mora?')).strip()
#v = c.lower().split()
#print('santo' in v)
print(c[:5].lower() == 'santo')
|
597d4881f2737d62a79ca229f1f0e013beef82e3 | luhpazos/Exercicios-Python | /Pacote download/Desafios/58.Jogo da Adivinhação V2.0.py | 414 | 3.609375 | 4 | import random
l = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
c = random.choice(l)
t = 1
n = int(input('Eu pensei em um número entre 0 e 10. você sabe o número em que pensei?'))
while n != c:
if c > n:
print('mais...', end='')
if c < n:
print('menos...', end='')
n = int(input('Tente novamente:'.format(n... |
16b78efc1a0e12dd32642ea4bf60075bc36e7a45 | luhpazos/Exercicios-Python | /Pacote download/Desafios/38.Comparando Numeros.py | 418 | 3.953125 | 4 | print('\033[32m=-' * 10)
print('COMPARANDO NÚMEROS')
print('\033[32m=-\033[m' * 10)
n = int(input('''Escolha dois números inteiros para avaliar.
Primeiro número:'''))
m = int(input('Segundo número:'))
if n > m:
print('O primeiro valor foi o maior número digitado!')
elif m > n:
print('O segundo valor foi o maior... |
a0978b5991626e906648db09820226d043ebce14 | luhpazos/Exercicios-Python | /Pacote download/Desafios/61.Progressão Aritimética V2.0.py | 281 | 3.8125 | 4 | print('\033[36m~CALCULANDO PA~\033[m')
n = int(input('Digite o primeiro termo da PA:'))
r = int(input('Agora digite a razão dessa PA:'))
print('Esses são os dez primeiros termos dessa PA:')
t = n
c = 1
while c <= 10:
c = c + 1
print('{}'.format(t), end=' ')
t = t + r |
b325902063ee48fa44bc9806814bee123bbd623b | luhpazos/Exercicios-Python | /Pacote download/Desafios/76.Lista de Preços em Tupla.py | 403 | 3.546875 | 4 | lista = ('Lápis', 1.75, 'borracha', 2, 'caderno', 15.90, 'Estojo',25, 'transferidor', 4.20,
'Compasso', 9.99, 'Mochila', 120.32, 'canetas', 22.30, 'livro', 34.90)
print('--'*20)
print(f'{"LISTAGEM DE PREÇOS":^35}')
print('--'*20)
for c in range(0, len(lista)):
if c % 2 == 0:
print(f'{lista[c]:.<28}... |
a276112ea86c7dee16295bc0c3c4d563ff055045 | tdeepaksingh/guvii | /vowel.py | 153 | 3.984375 | 4 | n=input()
if n=='a' or n=='e' or n=='i' or n=='o' or n=='u':
print("Vowel")
elif n>'b':
print("Consonent")
else:
print("Invalid Character")
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.