blob_id stringlengths 40 40 | repo_name stringlengths 5 119 | path stringlengths 2 424 | length_bytes int64 36 888k | score float64 3.5 5.22 | int_score int64 4 5 | text stringlengths 27 888k |
|---|---|---|---|---|---|---|
3d6d121aee70adc08624e44ff2487c4a7abcb139 | caburu/python-web-apis | /previsao_tempo_yahoo.py | 2,774 | 4.09375 | 4 | '''
Programa para demonstrar a utilização do Python para obter dados
disponíveis na Web.
O usuário digita uma localidade a ser buscado no Yahoo Weather e, caso
seja encontrado, são exibidos dados deo tempo daquele local.
Descomente a chamada da função exibir_dados_formatados para ver todos
os dados que são retornado... |
54ac390118f2bfdfec331d785ef6dffda61412e6 | NBaiel81/winx_club | /exercise.py | 366 | 3.96875 | 4 | # 1. Прогоните список с помощью цикла while, все четные элементы добавьте в другой список.
i=0
b=[1,2,3,4,5,6,7,8,9]
even=[]
while i<len(b):
if b[i]%2==0:
even.append(b[i])
i+=1
print(even)
# x=2
# list1=[1,22,3,4,2,2,2,4,7]
# while i<len_list1:
# if list in list1
|
1b18410361e1d050bd09385550a7e0b641e45b88 | felipedrosa/algorithmsLessons | /week2/qs3.py | 1,275 | 3.609375 | 4 | import sys
def partition(alist, first, last):
global count
count = count + last - first
pivot = alist[first]
i = first + 1
j = i
while j <= last:
if alist[j] < pivot:
aux = alist[i]
alist[i] = alist[j]
alist[j] = aux
i += 1
j += 1
aux = alist[first]
alist[first] = alist[... |
bb26b887d6865789db15e0a1b8e018bce0e3ac3f | Aasthaengg/IBMdataset | /Python_codes/p03108/s201386745.py | 2,455 | 3.5 | 4 | # https://atcoder.jp/contests/abc120/tasks/abc120_d
# Unionfind
n, m = map(int, input().split())
class UnionFind:
def __init__(self, n):
self.n = n
# 各要素の親要素の番号を格納するリスト
# 根がルートの時は、グループの要素数を格納 最初は全て根で要素数1
self.parents = [-1] * n
# 再帰 groupの根を返す
# 経路圧縮あり
def find(self,... |
7b9363819d84cc585caada1fb753a6a5930324db | gksmfthskan/Python | /day_9-15(C).py | 374 | 3.546875 | 4 | import turtle
X = turtle.Turtle()
while True:
x = turtle.textinput("문자 입력", "l,r,q 나 enter를 누르십시요")
if x == 'l':
X.left(90)
X.forward(100)
elif x == 'r':
X.right(90)
X.forward(100)
elif x == 'q':
X.forward(100)
elif x == '':
break
else:
... |
7f5de6dc24014a1d01dabb2066b93fd0c9d29f5d | omertasgithub/data-structures-and-algorithms | /leet code/Stack/1047. Remove All Adjacent Duplicates In String.py | 341 | 3.8125 | 4 | #1047. Remove All Adjacent Duplicates In String
#realted topics
#stacks
s1 = "abbaca"
s2 = "azxxzy"
def removeDuplicates(s):
stack = []
for i in s:
if stack and stack[-1]==i:
stack.pop()
else:
stack.append(i)
return "".join(stack)
print(removeDuplicates(s1))
print(... |
ffca08b345bebf3fbfe9f7fc15e69b16c22adeb2 | lmarchesani/IDF_Resources | /day1/Marchesani6/numbahFyv.py | 282 | 4.125 | 4 | #! /usr/in/env python3
#Lucas Marchesani
carbs = float(input("input how many grans of carbs you eat per day\n"))
fat = float(input("input how many grans of fat you eat per day\n"))
carbs *=4
fat*=9
print("You get", carbs,'calories from carbs and',fat,"calories from fats\n")
|
1b460b00e1b1f843c220200c55727f6d854eb6b0 | msalman899/Python | /scripts/alphabet_rangoli.py | 700 | 3.890625 | 4 | import string
def print_rangoli(size):
alpha = string.ascii_lowercase
s=(alpha[:size])
if size==1:
print(s)
if size > 1:
for i in range(len(s)):
print("-".join(s[len(s)-i:len(s)][::-1]).rjust((size*2)-3,'-')+"-"+alpha[(size-1)-i]+ "-"+"-".join(s[len(s)-i:len(s)]).lj... |
2afd63b7e401a81a180b7706aa6a19ad8e16db77 | daniel-reich/ubiquitous-fiesta | /KSiC4iNjDHFiGS5oh_0.py | 148 | 3.578125 | 4 |
def is_super_d(n):
for d in range(2, 10):
if str(d) * d in str(d * n**d):
return 'Super-{} Number'.format(d)
return 'Normal Number'
|
5048b742e4527ab657a430400c7b21cb92778a40 | kevinji/project-euler | /problem_34.py | 559 | 3.859375 | 4 | '''
Problem 34
@author: Kevin Ji
'''
FACTORIALS = [1, 1, 2, 6, 24, 120, 720, 5040, 40320, 362880, 3628800]
def factorial(number):
return FACTORIALS[number]
def is_curious_num(number):
temp_num = number
curious_sum = 0
while temp_num > 0:
curious_sum += factorial(temp_num % 10)
tem... |
962846061b5291990ca8976696f58fee3d5c133c | Jaimeibarrae/ejerciciosSegundaunidad | /JACI_piramide.py | 267 | 3.671875 | 4 | def piraminde ():
spaces = 10-1
asterist = 1
for lines in range(10):
while spaces >= 0:
print ('%s%s%s' % ((' '*spaces), ('0'*asterist), (' '*spaces)))
spaces -= 1
asterist += 2
piraminde()
input("")
|
dc4955d94f37f89d4b44e6d72f14f28474cc33b0 | peefer66/100doc | /day 22_30/Day 22/main.py | 1,567 | 3.75 | 4 | from turtle import Turtle, Screen
import time
from paddle import Paddle
from scoreboard import Scoreboard
from ball import Ball
# Define the Screen
screen = Screen()
screen.setup(width=800,height=600)
screen.bgcolor('black')
screen.title('Pong')
screen.tracer(0)
#Create paddle with the starting positions
r_paddle ... |
f90d2135e684c8c99010cbf3d56f1f61421b86af | chensandian/Coursera_Data_structure_and_algorithms | /Algorithmic Toolbox/week1/max_pairwise_product.py | 436 | 3.890625 | 4 | # python3
def max_pairwise_product(numbers):
n = len(numbers)
large1 = 0
large2 = 0
for num in numbers:
if num > large1:
large2 = large1
large1 = num
elif num > large2:
large2 = num
return large1 * large2
if __name__ == '__main__':
input_n ... |
0ff41283fa563d732d1f7b53804a13fb004a4f9f | vsubramaniam851/brainling | /parsing/sentsample.py | 4,436 | 3.609375 | 4 | import csv
import random
import nltk
top_ten_speakers = ["Thor:", "Loki Actor:", "Valkyrie:", "Banner:", "Grandmaster:", "Hulk:", "Hela:", "Korg:", "Odin:", "Doctor Strange:"]
def extract_speakers(speakers):
"""Takes in a list of speakers and extracts the associated sentences that they speak.
The associated se... |
4cf6d2ca2b69de8a9023b1a5fa62d9b450b4a5e2 | Roma-coder/Python_Labs | /Lab_1/Lab_1.2.py | 123 | 3.71875 | 4 | w1 = input("Enter string")
w2 = input("Enter first word")
w3 = input("Enter secound word")
w4 = w1.replace(w2,w3)
print(w4) |
f8a82c544cb5b9cfc0f45e7b5952ad40f9559d4c | donghee1116/data_science_study | /1_AI/keras13_lstm.py | 2,817 | 3.921875 | 4 | #RNN: Recurrent Neural Network
#LSTM: Long Short-Term Memory network - RNN의 한가지 기법 중 하나. 보통 RNN은 LSTM으로 함.
#맨 뒤에 작업량 (실행갯수)를 써줘야하는 특징이 있음
# https://machinelearningmastery.com/time-series-prediction-lstm-recurrent-neural-networks-python-keras/
# RNN의 핵심은 다음 숫자 맞추기!!
# DNN은 열만 맞추면 됐음. RNN은 몇 행 몇 열 + 몇개씩 들어가느냐 .
# 현재의 ... |
a0314ab556e76fa1888411a40c03f99dff5aab2e | ramoncaceres/imbroglio | /digraph.py | 2,571 | 3.671875 | 4 | #
# Maintains and explores a directed graph.
# Each node keeps a list of adjacent nodes.
# Traversals end on nodes that have no adjacent nodes.
#
import random
import numpy
class Digraph(object):
def __init__(self):
self.nodes = dict()
def AddNode(self, node, nextnodes):
self.nodes[node] = nextnodes
de... |
458eabfa44cef26237581acd078d6c2af2b97ab1 | jongfeel/ProjectEuler | /Problems/Problem7/Problem7.py | 421 | 3.84375 | 4 | import math
def IsPrime(number):
for index in range(2, math.floor(math.sqrt(number))+1):
if number % index == 0 and index != number:
return False
return True
def GetPrimeNumber(order):
index, count = 1, 1
while count != order:
index += 2
if IsPrime(index) == True:
... |
29dbf16de9126320fe3470c4d9491e2f2caf4689 | Aasthaengg/IBMdataset | /Python_codes/p02257/s122595704.py | 327 | 3.921875 | 4 | def isPrime(x):
if x==2:
return True
if x<2 or x%2==0:
return False
for n in range(3,int(x**0.5)+1,2):
if x%n==0:
return False
return True
n=int(input())
num=[int(input()) for i in range(n)]
i=0
for nm in num:
if isPrime(nm):
i+=1
p... |
89ce98d4ed43f6e61a40b782522d502074aa1801 | PrismShake/wowtest | /Python Projects Hanna/bounce_click.py | 2,886 | 4.15625 | 4 | """
Pygame base template for opening a window
Sample Python/Pygame Programs
Simpson College Computer Science
http://programarcadegames.com/
http://simpson.edu/computer-science/
Explanation video: http://youtu.be/vRB_983kUMc
"""
import pygame
import random
# Define some colors
BLACK = (0, 0, 0)
WHITE = (255, 25... |
ca9e495d57f618c7125d6cd3a3099f6dd0e8ccfe | strelka0d/Hillel-HW-Python | /HW-7/Homework_7-2.py | 2,314 | 3.84375 | 4 | # Задача-2
# У вас несколько JSON файлов. В каждом из этих файлов есть
# произвольная структура данных. Вам необходимо написать
# класс который будет описывать работу с этими файлами, а
# именно:
# 1) Запись в файл
# 2) Чтение из файла
# 3) Объединение данных из файлов в новый файл
# 4) Получить путь относительный путь... |
b13094df6bf917d41623d3c8ebcf050bb4d486ec | amgartsh/Astro_image_processing | /OrbitDetermination.py | 1,655 | 3.609375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sat Dec 2 00:03:16 2017
@author: Adam
"""
# Program Details
"""
This program will take an input of two 3 dimensional vectors defining two positions observed from a spacecraft orbiting a massive object and a time of flight
measurement between them, and find the orbit of said ob... |
546a4d8c1d1f020b6a8b8bec70f3c3ee293976b7 | fruizga/holbertonschool-higher_level_programming | /0x02-python-import_modules/3-infinite_add.py | 311 | 3.609375 | 4 | #!/usr/bin/python3
if __name__ == "__main__":
import sys
end = len(sys.argv)
i = 1
if end == 1:
print(0)
elif end == 2:
print(int(sys.argv[1]))
else:
i = 1
suma = 0
for i in range(i, end):
suma += int(sys.argv[i])
print(suma)
|
eb42d36d5bcd943a08467ecc7e6b32641e377c71 | underbais/CSHL_python2017 | /python5_problemset/2.py | 240 | 3.734375 | 4 | #!/usr/bin/env python3
file = open("Python_05.txt", "r")
new_file = open("Python_05_uc.txt", "w")
#content = file.read()
for line in file:
line = line.upper()
line = line.rstrip()
new_file.write(line+"\n")
file.close()
new_file.close()
|
1fc1e5957e0d04517665f3aa7a8b03f46b506651 | TilemachosKosmetsas/sequences | /akolouthia 2d armonic deut.py | 528 | 3.515625 | 4 | import matplotlib
import matplotlib.pyplot as plt
vx = []
vy = []
vz=[]
a1 = input("dwse ton prwto oro tis akolouthias \n")
v1 = input("dwse tin stathera n tis akolouthias \n")
counter = 1
a2 = int(a1)
v2= float(v1)
while counter <= 10:
akol = (1/((1/a2)+(counter-1)*v2))
vx.append(counter)
... |
491185c5805bc5578a215a0c57d8d1a7d0bd5648 | m-mohsin-zafar/zero-dataanalysis-work | /geo_data.py | 461 | 3.515625 | 4 | # Name: Muhammad Mohsin Zafar
# Roll No. MS-18-ST-504826
import numpy as np
import pandas as pd
def get_data_as_array(filename):
# Using Pandas Library we read file and construct the dataframe
df = pd.read_csv(filename)
# From data frame we can easily use keys() to construct an Numpy Array
data = n... |
fd08e043ffc387510c37100dcf95a3624d94772c | sandeepyadav10011995/Data-Structures | /30 Days Challenge/Perform String Shifts.py | 1,606 | 3.859375 | 4 | """
You are given a string s containing lowercase English letters, and a matrix shift, where shift[i] = [direction, amount]:
direction can be 0 (for left shift) or 1 (for right shift).
amount is the amount by which string s is to be shifted.
A left shift by 1 means remove the first character of s and append it to the... |
8d0427b09d131b67a046e530c2fe1450814bbe0d | bmorgan365/java-c-python | /python/function-paramters.py~ | 661 | 3.859375 | 4 | #!/usr/bin/python3
# Function definition like C macro
sum = lambda a, b: a + b
def printSumWithLambda(a, b):
"test of lambda function"
print(sum(a, b))
return
def argTypes(a, b, *var):
print(a+b)
print("Other vars:", end = ' ')
for i in var:
print(i)
return
def defaultArg(a, b=20... |
3d15419e56ee0822fb96cff4e59961b4a2ec9826 | Seagrass27/Tensorflow_Learning | /tf_distributing_CustomFunction.py | 1,573 | 3.59375 | 4 | # =============================================================================
# Game of Life is an interesting computer science simulation
# =============================================================================
#1. If the cell is alive, but has one or zero neighbours, it “dies” through
# under-populati... |
cac8296879a80702e3b0335f70f94fa4dcb7f19c | pythongus/metabob | /test/test_2d_arrays.py | 1,391 | 3.640625 | 4 | """
Unit tests for the hourglass sum algorithm.
"""
import math
import os
import random
import re
import sys
from hackerrank.two_d_arrays import (
create_2d_array,
hourglassSum,
make_hour_glass,
)
HG_1 = """
1 1 1 0 0 0
0 1 0 0 0 0
1 1 1 0 0 0
0 0 0 0 0 0
0 0 0 0 0 0
0 0 0 0 0 0
"""
HG_2 = ""... |
5379a5ee2b8db112835ba031e039a581eaec768b | benrbray/yaraku-test | /shared/nlp.py | 1,224 | 3.90625 | 4 | """
NLP.PY
Contains helper functions for working with text data.
"""
import nltk;
stopwords = None;
tokenizer = None;
stemmer = None;
def init():
# create stopwords list
global stopwords;
if stopwords is None:
nltk.download("stopwords");
stopwords = set(nltk.corpus.stopwords.words("english"));
# initialize ... |
b33ff091eff1bc86257e63dbee5a5d65e8142c16 | a1ip/mipt-materials | /3c1t/Parallel and Distributed Computing/HW6. Hadoop/WordCount/mapper.py | 310 | 4.0625 | 4 | #!/usr/bin/env python
import sys
import re
for line in sys.stdin:
line = line.strip()
words = re.split('\W+', line) #matches any non-alphanumeric character; this is equivalent to the set [^a-zA-Z0-9_]
for word in words:
if word and word[0].isupper():
print '%s\t%s' % (word, 1) |
d1f6de07feff8cc7315f16f96f5fb1225370c1d3 | helenpark/PIP | /Algorithm and Data Structure Impl/Sorting.py | 4,137 | 4.125 | 4 | # Sorting
# http://danishmujeeb.com/blog/2014/01/basic-sorting-algorithms-implemented-in-python/
# 1. Bubble sort
# It’s basic idea is to bubble up the largest(or smallest), then the 2nd largest
# and the the 3rd and so on to the end of the list. Each bubble up takes a full
# sweep through the list.
def bubble_so... |
dcf233b179b91759431e583a06ffa81efad7e2cd | SelvorWhim/competitive | /LeetCode/NumberOfGoodPairs.py | 388 | 3.734375 | 4 | # don't need to show the pairs, so the order doesn't matter
# just need to find how many times each number appears and count the pairs
from collections import Counter
class Solution:
def numIdenticalPairs(self, nums: List[int]) -> int:
counts = Counter(nums)
return sum(count * (count - 1) // 2 for... |
1b9e840c37545f99f1ac758e998390720ad1a771 | nithinreddykommidi/pythonProject | /PYTHON_WORLD/1_PYTHON/12_Predefine_modules/6_Threrading/3_get_thread_name.py | 407 | 3.640625 | 4 | '''
1. threading.currentThread(): Returns the currentThread object
'''
import threading
import time
def fun1():
print(' \n Fun1 thread name is :::::', threading.currentThread().getName())
def fun2():
print(' \n Fun2 thread name is :::::', threading.currentThread().getName())
t1 = threading.Thread(target=fu... |
c8ad09f9a740ad068f6b003bacf4b7ed062f1d6b | MatheusFidelisPE/ProgramasPython | /Exercicio 115/principal.py | 1,089 | 3.71875 | 4 | import cores as c
'''
mensagem=str(input('Qual a mensagem? ')).upper()
c.cores_letra(opções=True)
cor_letra= str(input('cor da letra? ')).lower()
c.cores_fundo(opções=True)
cor_fundo=str(input('Cor do fundo? ')).lower()
c.estilo_letra(opções=True)
estilo_letra=str(input('Estilo da letra? ')).lower()
print(menu.pr... |
ecffadfb6a83b8d9481b1ce3c211e875a1bfbc0b | eduardmihranyan/My-ML-homeworks-ACA- | /Practical_3/decision_tree.py | 2,074 | 3.71875 | 4 | import dtOmitted as dt
import numpy as np
class DecisionTree(object):
"""
DecisionTree class, that represents one Decision Tree
:param max_tree_depth: maximum depth for this tree.
"""
def __init__(self, max_tree_depth):
self.max_depth = max_tree_depth
def fit(self, X, Y):
"""
... |
cf8d1fa591221420bb019ea2c60727cd44233e40 | thoraage/python_poker | /card.py | 775 | 3.6875 | 4 | from enum import IntEnum
class Colour(IntEnum):
CLUBS = 1
DIAMONDS = 2
HEARTS = 3
SPADES = 4
class Value(IntEnum):
V2 = 2
V3 = 3
V4 = 4
V5 = 5
V6 = 6
V7 = 7
V8 = 8
V9 = 9
V10 = 10
KN = 11
Q = 12
K = 13
ACE = 14
class Card:
def __init__(self, val... |
e283b4b8172f26fea23aed77990c1fd6933196d7 | Ani-Gil/Python | /Python 200/131.py | 425 | 3.859375 | 4 | # 131.py - 사전 정렬하기(sorted)
names = {'Mary' : 10999, 'Sams' : 2111, 'Aimy' : 9778, 'Tom' : 20245,
'Michale' : 27115, 'Bob' : 5887, 'Kelly' : 7855}
ret1 = sorted(names)
print(ret1)
def f1(x):
return x[0]
def f2(x):
return x[1]
ret2 = sorted(names.items(), key = f1)
print(ret2)
ret3 = sorted(names.ite... |
6f4eb668562ddad8449b0fa4cd1e402a7498f5e6 | eddo888/Argumental | /Argumental/Attribute.py | 256 | 3.75 | 4 | #!/usr/bin/env python3
from Argumental.Argument import Argument
class Attribute(Argument):
"""
used for class attributes
examples:
@args.attribute(
...
)
"""
def __init__(self, fn, kwargs=None):
super(Attribute, self).__init__(fn, kwargs)
|
04f897144b488e6964bb0b9164f4314046af58f3 | renidantass/learning_python | /exercises/guanabara/ex63.py | 219 | 3.78125 | 4 | # coding:utf-8
n_termos = int(input("Quantos termos você quer mostrar? "))
t1, t2 = 0, 1
cont = 3
while cont <= n_termos:
t3 = t1 + t2
print '{} -> {} ->'.format(t1, t2),
t1 = t2
t2 = t3
cont += 1
|
6372990eb57edd788f62c090a537ca30e34c77ec | shwetasharma18/python_algorithm_questions | /algo/prime2.py | 358 | 3.953125 | 4 | def prime2(num):
lis = []
num1 = str(num)
i = 0
while i < len(num1):
num2 = int(num1[i])
j = 2
while j < num2:
if num2 % j == 0:
var = num2,"is not a prime number"
lis.append(var)
break
j = j + 1
else:
var = num2,"is a prime number"
lis.append(var)
i = i + 1
return(lis)
print prim... |
9e83838839cabb115fdba82689ef5e2224e1eace | angelaxie2015/EncourageBot | /main.py | 3,258 | 3.546875 | 4 | import discord
import os
import requests
import json
import random
from replit import db
#discord.py library is used in this project.
#os provides a portable way of using operating system dependent functionality
#requests allows us to request from http stuff
#json JSON is a lightweight format for storing and tran... |
01515b41eec41a202326b0097cf81a28b1e5bee8 | vbipin/bfs_astar_training | /solutions.py | 9,917 | 3.8125 | 4 | #In this file we keep the BFS/DFS and Greedy/A* algorithms and other useful functions
#I will try to use the minimum required libs from python
#Also the code is written with simplicity in mind than efficiency
#the code is suboptimal; to be used only as a teaching resource
#XXX
#These functions assume successors() and... |
ee32d8a2700ea56411a547d571e8fff09df50c6d | sofia-russmann/Python-Practise | /1/inclusive.py | 796 | 3.71875 | 4 | #frase = 'todos somos programadores'
#frase = 'Los hermanos sean unidos porque esa es la ley primera'
frase = 'Cmo transmitir a los otros el infinito Aleph?'
#frase = 'Todos, tu tambin'
palabras = frase.split()
i1 = -1
i2 = -2
#i3 = -3
frase_t = ''
for palabra in palabras:
if len(palabra) >= 2:
if palab... |
a8ea7cf188a6a2a741986ae483e9b9b2f5f58edb | RushikeshNarkhedePatil/python | /RandonNumber.py | 236 | 3.828125 | 4 | """
Generate 10 Integer Random Number and print Even and odd Number Seprated.
"""
import random
even=[]
odd=[]
for i in range(1,11):
n=random.randint(1,100)
if n%2==0:
even.append(n)
else:
odd.append(n)
print(even)
print(odd) |
1ab7f8d63fd9c6f76bcaf37894e47bb5d6333421 | VanessaGaete/Neural-Networks | /perceptron.py | 1,593 | 3.640625 | 4 | from numpy import array
class Perceptron(object):
def __init__(self, bias, w1, w2):
self.bias=bias
self.w1=w1
self.w2=w2
def output(self, x1,x2):
m1=x1*self.w1
m2=x2*self.w2
result= m1+m2 +self.bias
if result <= 0:
return 0
else:
... |
5b92ffaa938547c90476fa38fad58b1e34b0cdce | roflcopter4/random | /school/LAB/ass/cheat.py | 2,181 | 3.828125 | 4 | #!/usr/bin/env python3
import sys
class Stack:
def __init__(self):
self.__items = []
def push(self, item):
self.__items.append(item)
def pop(self):
return self.__items.pop()
def peek(self):
return self.__items[len(self.__items)-1]
def is_empty(self):
re... |
29f12fff7c2ca258b5bf2356161171d01c5e6f9e | joselynzhao/Python-data-structure-and-algorithm | /algorithm/xianxingbiao/shun.py | 914 | 3.671875 | 4 | #!/usr/bin/python
# -*- coding: utf-8 -*-
'''
@AUTHOR:Joselyn Zhao
@CONTACT:zhaojing17@foxmail.com
@HOME_PAGE:joselynzhao.top
@SOFTWERE:PyCharm
@FILE:shun.py
@TIME:2020/5/11 21:41
@DES: 顺序表的插入、检索、删除和反转操作
'''
class SeqList(object):
def __init__(self,max=8):
self.max = max
self.num = 0
self.d... |
a1778258d94dcf45144989828ce0605a04c04538 | ShiraAnaki130/OOP_Ex3 | /src/DiGraph.py | 6,598 | 3.78125 | 4 | from src.GraphInterface import GraphInterface
from src.NodeData import NodeData
class DiGraph(GraphInterface):
"""
This class represents a directional weighted graph.
Each vertex in the graph is from the type of node_data and
every edge has a positive weight and direction.
The class supports sever... |
422658bc045ff540c69636c75494b71516826e09 | jkbockstael/leetcode | /2020-07-month-long-challenge/day12.py | 732 | 3.953125 | 4 | #!/usr/bin/env python3
# Day 11: Reverse Bits
#
# Reverse bits of a given 32 bits unsigned integer.
class Solution:
def reverseBits(self, n: int) -> int:
# This can be written as a one-liner, but here's a breakdown:
output = bin(n) # parse the input
output = output[2:] # get rid of "0b"
... |
e07e917b7132df843ae35564848a384870a3bbe4 | pcaramguedes/cursopython520 | /lista.py | 325 | 3.90625 | 4 | #!/usr/bin/python3
# Tuplas listas
matriz = [
[ 0, 1, 2 ],
[ 3, 4, 5 ],
[ 6, 7, 8 ]
]
soma = 0
for lin in range(len(matriz)):
print(matriz[lin])
for col in range(len(matriz[lin])):
print(matriz[lin][col])
soma += matriz[lin][col]
print(f"A soma dos numeros da matriz eh: {soma... |
e252efc98e6c12d4d005e6d46802fb3248e0014e | andre11-ai/4IV8-Tecnicas | /Archivos/EscrituraArchivoTextoyPosicion.py | 815 | 3.59375 | 4 | with open ("EscribirArchivo.txt", "w+", encoding="utf8") as archivo:
archivo.write("Escribiendo una línea de texto\n")
datos=archivo.read()
print("Leyendo archivo completo, después de haber escrito y donde este el puntero: ", datos)
archivo.seek (0, 0) # primer cero, son los bytes que recorre y el segun... |
cf8ff8f7a1c9f07d7df8f72e4e64c47cecda0535 | AlexeyLyubeznyy/python4everybody | /scraping numbers using beautiful soup.py | 1,295 | 3.5 | 4 | # To run this, download the BeautifulSoup zip file
# http://www.py4e.com/code3/bs4.zip
# and unzip it in the same directory as this file
from urllib.request import urlopen
from bs4 import BeautifulSoup
import ssl
import re
# Ignore SSL certificate errors
ctx = ssl.create_default_context()
ctx.check_hostnam... |
563b429fe3f5fc09023c825b19e47061020ed27d | anushreetrivedi01/TWoC-HBTU-B1_Day1 | /day3code6.py | 709 | 4.03125 | 4 | def Sum(List,size,sum):
sumList = []
is Size==1:
for x in List:
sumList.append(sum + x)
return sumList
L=list(List)
for x in List:
L.remove(x)
sumList.extend(Sum(L,size-1,sum + x))
return sumList
def summation(List,size):
sumList = list(List)
for i in range(2,size+1):
sumList.extend(Sum(List,i,0))
number = 1
while Tru... |
631e79ef4857e588a1a657addc01066407913be6 | X-sc-fan/computationalphysics_N2015301020074 | /ChapterOne/CHAPTER1_1.py | 657 | 3.546875 | 4 | from matplotlib import pyplot as plt
import numpy as np
g = 9.8 #定义重力加速度的值
dt = 0.001 #定义步长
N = int(10/dt) #总循环次数
v = [0 for x in range(0,N+1)] #速度数组
t = [0 for x in range(0,N+1)] #时间数组
#print (len(v))
for i in range(N):
v[i+1] = v[i] - g*dt #利用微分方程求解
t[i+1] = t[i] + dt
# print(v[i+1])
x=np.linspace(0,10,... |
0fd9a99abfb6d25ec571ffe8c4bd5d0531102128 | daorejuela1/holbertonschool-higher_level_programming | /0x0A-python-inheritance/10-square.py | 537 | 4.0625 | 4 | #!/usr/bin/python3
"""
Starting module to define a rectangle with basegeometry
attributes and methods
"""
Rectangle = __import__('9-rectangle').Rectangle
class Square(Rectangle):
"""Square class to represent a rect with width and height equal """
def __init__(self, size):
""" Instantiate square """
... |
9da0da5dd58abba5d9ebbbf4074efbc130f96e0a | munezou/PycharmProject | /normal/FluentPython_code_master/ch02_array_seq/main_02.py | 2,159 | 3.625 | 4 | # Cartesian product
colors = ['black', 'white']
sizes = ['S', 'M', 'L']
print('colors are {0}'.format(list(colors)))
print('sizes are {0}'.format(list(sizes)))
print()
# Shirt types are made with a combination of color and size.
print('---< Shirt types are made with a combination of color and size. >---')
tshirts = ... |
1827f8a5095276a1be24e478610448e0dd388b8c | iabdullahism/python-programming | /Day01/ stringhand.py | 670 | 3.921875 | 4 |
"""
Code Challenge
Name:
String Handling
Filename:
stringhand.py
Problem Statement:
Take first and last name in single command from the user and print
them in reverse order with a space between them,
find the index using find/index function and then print using slicing concept of the ind... |
32e447a49c9ec65673179e28a7cbd41563a88f93 | TimRemmert13/Movies | /media.py | 932 | 3.75 | 4 | import webbrowser
class Movie ():
'''A class to model a movie.
Attributes:
title (str): the title of the movie.
storyline (str): a breif description of the movie.
image (str): A poster image of the move which is a URL link to a
image hosted on wiki... |
f90dd2ce22512947689330926636bba2e6f6db17 | EricksonSiqueira/curso-em-video-python-3 | /Mundo 1 fundamentos basicos/Aula 10 (condições 1)/Teoria 1.py | 162 | 3.875 | 4 | nome = str(input('Qual é o seu nome?'))
if nome == 'Gustavo':
print('Que nome feio!')
else:
print('Seu nome é tão bonito!')
print(f'Bom dia, {nome}!')
|
dfc6924d85e7dea900015c0444def2aacbfda6f2 | gnsisec/learn-python-with-the-the-hard-way | /exercise/ex18.py | 679 | 4.03125 | 4 | # This is Python version 2.7
# Exercise 18: Names, Variables, Code, Functions
# this one is like your scripts with argv
def print_two(*args):
arg1, arg2, arg3, arg4 = args
print "arg1 : %r, arg2 : %r, arg3 : %r, arg4 : %r" \
% (arg1, arg2, arg3, arg4)
# ok, that *args is actually pointless, we can ... |
afb0c2b8ed485ec4b2d4f0ef739a962f3ce50a54 | AntonMAXI/Python_lessons_basic | /lesson03/home_work/hw03_normal.py | 2,025 | 3.765625 | 4 | # задание-1:
# напишите функцию, возвращающую ряд фибоначчи с n-элемента до m-элемента.
# первыми элементами ряда считать цифры 1 1
n = int(input('First num : '))
m = int(input('Second num : '))
def fibonacci(n,m):
dict_1 = {}
k1 = k2 = 1
for i in range(1,m + 1):
dict_1[i] = [k1, k2]
k1 = ... |
b715d3a52cf31b23c9161a4b08d38c86b5ccb1eb | atastet/Python_openclassroom | /Chap02/test_modul_op.py | 259 | 3.5 | 4 | #!/usr/bin/python3.4
# -*-coding:Utf-8 -
etudiants = [
("Clément", 14, 16),
("Charles", 12, 15),
("Oriane", 14, 18),
("Thomas", 11, 12),
("Damien", 12, 15),
]
from operator import itemgetter
print(sorted(etudiants, key=itemgetter(2)))
|
7f79d6d1cc4ebe79b36d68d827abe485c9acf99c | ckade15/auto-hgtv | /hgtv.py | 7,664 | 3.53125 | 4 | """
@author Chris Kade
HGTV/Food Network 2021 Home Giveaway Entry Bot
Stores information in a database so all you have to do to fill out both forms
after originally entering all of your information is type your last name
"""
import enum
from selenium import webdriver
from webdriver_manager.chrome import Chr... |
a16967b7d69c1b75033e89903ccdd057bb0dc711 | vakobtu/TASK | /Memkvidreoba.py | 1,426 | 3.96875 | 4 | #1
"""class Book:
def __init__(self, title, author, numPages, publishdate):
self._title = title
self._author = author
self._numPages = numPages
self._publishdate = publishdate
myBook = Book
myBook._title = "Coding"
myBook._author = "Code Koshmaridze"
myBook._n... |
56477865153cafe5a6d267796c8adfb36ae1d2bd | SSaquif/python-notes | /2-strings.py | 899 | 4.03125 | 4 | # String multiplication
print('*'*10)
# Strings can use single, double or triple quotes (for multi line)
small = 'hello'
message = '''sssssssssssssssssssssssss
ssssssssssssssssss'''
print(message)
# String Methods
print(len(small)) # 5
print(small[0]) # h
print(small[-1]) # o
print(small[0:3]) # hel
print(small[... |
824089ec09917a36f69a9e3144aa6eff203b3274 | Vaishnavicap/Fibonacci_numbers. | /Fibonacci_Numbers.py | 221 | 4.0625 | 4 | n = int(input("Enter the no. of elements : "))
a = 0
b = 1
print("List of ",n, " Fibonacci numbers : ")
print("0 1",end=" ")
for i in range (2,n):
sum = a + b
print(sum , end=" ")
a = b
b = sum
|
1892fe256edba546816fd4de59499837ac48f694 | erick-camacho/academlo-python | /homework2.py | 995 | 3.734375 | 4 | class TextFile:
def __init__(self, name):
self.name = name
self.text = open(self.name)
self.counts = dict()
def word_counter(self):
for line in self.text:
words = line.split()
for word in words:
self.counts[word] = self.counts.get(word, 0)... |
e9e03a969c3dafe2362441992efb349ef1048f41 | Radek011200/Wizualizacja_danych | /Zadania_lista_nr7/7_2.py | 266 | 3.546875 | 4 | import numpy as np
a = np.array( [20,30,40,50,40,7,60,70,2,] ).reshape(3,3)
b = np.array( [31,43,56,33,12,312,345,2,7,16,11,12,13,14,15,16] ).reshape(4,4)
print(a)
print(b)
print(a.min(axis=1))
print(a.min(axis=0))
print(b.min(axis=1))
print(b.min(axis=0)) |
e3cfad5166526f82b70b82b0d60319ce73f81be6 | alveraboquet/Class_Runtime_Terrors | /Students/tom/Lab 9/lab_9_unit_converter_version_4.py | 2,014 | 4.1875 | 4 | # Version 3 of Unit Converter adds more conversion factors
# Tom Schroeder 10/14/2020
original_distance = float(input ('\nEnter the distance that you want to convert: '))
# user inputs the units of the original disance
original_units = input ('Enter the original units (ft, mi, m, km): ')
converted_units = input ('En... |
66b9521016013ba00ff17aad337411d135e311f4 | Litao439420999/LeetCodeAlgorithm | /Python/longestPalindrome.py | 770 | 3.96875 | 4 | #!/usr/bin/env python3
# encoding: utf-8
"""
@Filename: longestPalindrome.py
@Function: 最长回文串 区分大小写
@Link: https://leetcode-cn.com/problems/longest-palindrome/
@Python Version: 3.8
@Author: Wei Li
@Date:2021-07-29
"""
import collections
class Solution:
def longestPalindrome(self, s: str) -> int:
ans = 0
... |
f476d748db1914b7f2eb8c6fea94a05bb43b419d | nirnicole/Artificial-Intelligence-Python-Repositories | /Neuron Networks/ANN-BP/source/NNframe.py | 13,033 | 4 | 4 | """
Course: Biological computation
Name: Nir nicole
Module: ANN implementaion
"""
import numpy as np
import random
class NeuralNetwork:
"""
This class outlines the structure of a Neural Network.
"""
def __init__(self, n_inputs, n_hidden, n_outputs,layer_count=1, learning_rate=0.3, iteration... |
2e472b129472e5451261d6e767e4e14ea4913c23 | JormaTapio/TryPython | /Kokeilu.py | 381 | 3.75 | 4 | # Ohjelma pitusmitan antamiseksi
def pituusmitta(mitta):
if (mitta != 0):
print("Antamasi syöte oli",mitta,"merkkiä pitkä.")
else:
print("Et antanut syötettä")
def main():
while True:
syote = input("Anna syöte (Lopeta lopettaa): ")
if (syote == "Lopeta"):
break
pituus = len(syote)
pi... |
10f5985704ace2fd467ab69b4a5dc7d63c2c711d | JoelBrice/PythonForEveryone | /ex3_01.py | 213 | 4.03125 | 4 | ##Python for everyone Exercise 3
hrs = input("Enter Hours:")
h = float(hrs)
rate = input("Enter rate:")
r = float(rate)
extra_pay = 0.0
if h>40.0:
pay = ((h-40.0)*1.5+ 40)*r
else:
pay = r*h
print(pay)
|
4c8ab24eadcffa75e5a14643ca43df0bb191fe9a | pmarcio87/Multiple-Dice-Roller | /Dice_Roller.py | 2,563 | 4.28125 | 4 | import numpy as np
dice = {'1':4,'2':6,'3':8,'4':10,'5':12,'6':20} #Using a dictionary to pair each type of die with its number of sides
def menu():
print('Choose the appropriate die to roll according to the numbers below:')
print('')
print('1 - 4-sided die (d4)')
print(... |
8ac4f47962068be73a1ae148073c507bff63e167 | Pohjois-Tapiolan-lukio/raspberry_pi-projects | /examples/perusteet/tehtävä6.py | 415 | 3.625 | 4 | lista = []
luku = input("Syötä lukuja. Lopeta kirjoittamalla stop\n")
while luku != "stop":
lista.append(luku)
luku = input()
lista.sort(reverse = True)
for i in lista:
print(i)
summa = 0
for i in lista:
summa += int(i)
keskiarvo = summa / len(lista)
print("Keskiarvo on ", keskiarvo)
suurin = 0
for... |
3784846a150c6225dac0e77503572ea30c32e4a6 | technologyMz/Python_DS | /leetcode/tree/SameTree.py | 1,724 | 3.828125 | 4 | """
问题:给定两个二叉树,编写一个函数来检验它们是否相同。
(如果两个树在结构上相同,并且节点具有相同的值,则认为它们是相同的)
"""
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def same_tree(self, p: TreeNode, q: TreeNode) -> bool:
# 两棵树均为空
if not p and not ... |
fcd116cbbdf1ad1c56885b4e5cd3a4aa084d0951 | w00zie/graph_exploration | /utils/traversal.py | 1,595 | 3.5 | 4 | class GraphTraversal():
"""
This class handles the animation of the exploration.
At every frame the agent's action is plotted over the graph.
"""
def __init__(self, g, pos, valid_nodes, obstacles, traversal):
"""
Parameters
----------
g : nx.Graph
The envi... |
42ba8997da70bade2706d8917a0c1525cb2a1263 | jixinfeng/leetcode-soln | /python/038_count_and_say.py | 1,192 | 4.03125 | 4 | """
The count-and-say sequence is the sequence of integers beginning as follows:
1, 11, 21, 1211, 111221, ...
1 is read off as "one 1" or 11.
11 is read off as "two 1s" or 21.
21 is read off as "one 2, then one 1" or 1211.
Given an integer n, generate the nth sequence.
Note: The sequence of integers will be repre... |
e073010b7430b56953aad89a2b06caa16eae42b0 | Madhivarman/DataStructures | /leetcodeProblems/invertBST.py | 750 | 3.890625 | 4 | class Node():
def __init__(self, val):
self.data = val
self.left = None
self.right = None
def invertTree(root):
if root == None:
return
else:
#traverse till it reaches the leaf
invertTree(root.left)
invertTree(root.right)
#once subtrees are swapped just
... |
13b2d0fe9cade8cae4397de3bfdea5ed08aba8fa | kj2138998670/tutorial | /week4/number.py | 276 | 4.125 | 4 | def main():
numbers=[]
for time in [1,2,3,4,5]:
number = float(input("Enter number " + str(time) + ": "))
numbers.append(number)
print("the largest number is",max(numbers),"\nthe minimum number ",min(numbers))
main() |
f45820a074077300c1a4458946dfb2f07e8a3b4a | ShaunSEMO/my-python-codes | /print.py | 287 | 4.0625 | 4 | name = 'shaun'
surname = 'Moloto'
def out_put():
count = 0
for char in name:
count += 1
while count < len(name):
characters = ''
for char in name:
characters += char
print(characters)
out_put()
print('Hello World')
|
270cfaff7a33e1748177030587eb84a0688584ee | paepcke/email_anonymizer | /src/group_management/group_printer.py | 4,560 | 3.5 | 4 | #!/usr/bin/env python
'''
Created on May 8, 2017
@author: paepcke
'''
import argparse
from collections import OrderedDict
import os
import sys
class GroupPrinter(object):
'''
Given a list of participant-groupName pairs, and a group
ID, output the participation IDs of only the given group.
If no pa... |
10ea9054e855a84d64ed829e089c69a86f4baf68 | darshit-rudani/Python-Basic-I | /23.2.sets.py | 476 | 3.71875 | 4 | my_set = {1,2,3,4,5}
your_set = {4,5,6,7,8,9,10}
print(my_set.difference(your_set))
print(my_set.discard(5))
print(my_set)
# print(my_set.difference_update(your_set))
# print(my_set)
print(my_set.intersection(your_set))
print(my_set.isdisjoint(your_set))
print(my_set.union(your_set))
print(my_set | your_set)... |
039ad0ce82c86e7f4daf11acfa65598fb3b7289b | Shivam4819/python | /reverse.py | 451 | 3.875 | 4 | class ReverseStack:
def __init__(self):
self.item = []
def push(self, data):
self.item.append(data)
def pop(self):
return self.item.pop()
def isEmpty(self):
return len(self.item)==0
def reverse(text):
s = ReverseStack()
for c in text:
s... |
2bbf384381634911e9b1cc6f885f27a2728fe972 | CharleXu/Leetcode | /leetcode_560_Subarray_equal_k.py | 583 | 4.03125 | 4 | # coding: utf-8
def subarray_sum(nums, k):
"""
Given an array of integers and an integer k,
you need to find the total number of continuous subarrays whose sum equals to k.
:param nums: List[int]
:param k: int
:return: int
"""
count, total = 0, 0
res = {0: 1}
for i in range(l... |
f8e5b646d07bd97a5e3a7c95ee616c5fdf859183 | aaakashkumar/competitive_programming | /interviewcake/largest-stack.py | 5,927 | 4.34375 | 4 | # Largest Stack
# https://www.interviewcake.com/question/python3/largest-stack?course=fc1§ion=queues-stacks
# @author Akash Kumar
import unittest
class Stack(object):
def __init__(self):
"""Initialize an empty stack"""
self.items = []
def push(self, item):
"""Push a new item ont... |
fb6beff73508b6c32721d68c0111dcc762eabf7f | mboufatah/defect_scripts | /data_mining.py | 4,818 | 3.5 | 4 | from math import sqrt
import json #Get rid of json related function in future
_struct_prop = {'charge_ratio', 'radius_ratio', 'no_inter'}
def minkowski (struct1, struct2, power):
"""
Computes the Minkowski distance (interstitial properties) between two structures
"""
dist = 0
for key in _struc... |
b9328e487c33d43171e368f733261237c3963f99 | usvyatsky/azure-functions-durable-python | /samples/fan_out_fan_in_tensorflow/ShowMeTheResults/__init__.py | 725 | 3.671875 | 4 | import json
def main(value: str) -> str:
"""Get a summary of the results of the predictions.
Parameters
----------
value: str
List-formatted string of the predictions
Returns
-------
str
JSON-formatted string representing the summary of predictions
"""
results = js... |
2b97e895ba0e0fb0a5830fca17c2fe293c8767b5 | AGamble7/CatClassintro_hw | /car_cat.py | 251 | 3.703125 | 4 | class car:
make = Honda
model = Civic
color = white
def __init__(self, make, model, color):
self.make = "Honda"
self.model = "Civic"
self.color = "white"
print(" My car is a %s %d and it is %d so I call it snowflake")
|
fbb26e8ff82a7692da3ec5a8fec7a791a4c26280 | gkouvas/Hangman | /Topics/Search in a string/Checking email/main.py | 320 | 3.625 | 4 | def check_email(e_string):
if (" " not in e_string) and ("." in e_string) and ("@" in e_string) and ("@." not in e_string):
place_at = e_string.find("@")
place_dot = e_string.rfind(".")
if e_string.endswith('.') is False and place_dot > place_at + 1:
return True
return False
|
0416ec00bc54e595e1bcd41336057396e3f66d76 | CaptainAlexey/learnpython_homeworks | /1st.py | 614 | 3.875 | 4 | def life_answer(age):
if 1 < age < 7:
return "Вы еще ребенок. Вы должны быть в детском саду."
elif 7 <= age < 18:
return "Вы школьник. Вы должны быть в школе."
elif 18 <= age < 24:
return "Вы студент. Вы должны быть в ВУЗе."
else:
return "Вы прошли все подготовительные эт... |
d5fea71e529e3a779703000c012989c0b5b60887 | zhuzaiye/HighLevel-python3 | /chapter09/iterable.py | 1,586 | 4.1875 | 4 | # _*_ coding: utf-8 _*_
"""
1.什么迭代协议?
2.迭代器是什么?
迭代器是访问集合内元素的元素的一种方式,一般用来遍历数据。
3.迭代器是不能返回的,得带起提供了一种惰性方式的数据
4. __iter__ 是说明可迭代, __next__才是迭代器的本质
"""
from collections.abc import Iterable, Iterator
class MyIterator(Iterator):
"""
迭代器
"""
def __init__(self, employee_list):
self.iter_list = em... |
5fbf1e2a2dd899f7f5390f06d6cd5bffcb3b4eb4 | whaleygeek/cyber | /for_microbit/secret-receiver.py | 1,607 | 3.796875 | 4 | from microbit import *
import radio
radio.config(group=3, length=64)
radio.on()
PLAIN = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" # unshifted caeser cipher
WHEEL = ".........................." # build up your key here
#WHEEL= "ABCDEFGHIJKLMNOPQRSTUVWXYZ" # use this to show ciphered text
def cipher(wheel, message, shifti=0, shift... |
cc5a0f575a5feade58f8cedf645db6d64d1e598f | rid47/python_basic_book | /chapter8/factors.py | 135 | 4.0625 | 4 | number = input("Enter number: ")
n = int(number)
for i in range(1, n+1):
if n % i == 0:
print(f"{i} is a factor of {n}")
|
b504f65265bb11b936a5234e989d1a5a206330a8 | fiona-niwiduhaye/news-api-project | /app/models_test.py | 1,976 | 3.578125 | 4 | import unittest
from models import Source
from models import Article
class SourceTest(unittest.TestCase):
"""
Test Class to test the behaviour of the Source Class
"""
def setup(self):
"""
Set up method that will run before every Test
"""
self.new_source = Source("nana","... |
2cc685dc472df7c795099d7dac7667d64d73b7d7 | lihaoranharry/INFO-W18 | /week 2/Week 2 Breakout Activity.py | 6,044 | 4.59375 | 5 |
# coding: utf-8
# ## Activity 1
#
# ### Part A
#
# You work for a Python consulting company. One of your clients is really bad at math, and comes to you with an important task: to create a "calculator" program.
#
# We're going to build your first tool using Python code! Create a calculator tool that prompts a user fo... |
4bbb564d52641b262a8fc87a2b9e99a680b8e64f | katabullet1/Machine-learning | /Capstone project/maze_enviroment.py | 3,812 | 3.78125 | 4 | #importing modules
from Tkinter import *
import turtle
#setting up the platform
launch = Tk()
launch.title("THE MYSTERIOUS ISLAND")
launch.iconbitmap(default='img/Robotic_pet.ico')
#defining variables
actions = ["up", "down", "left", "right"]
Width = 40
b_border=40
a=15
b=15
(x, y) = (a, b)
board = Canvas(launch, ... |
e3328d591c567876a33ee7999b43db8fb549822f | Jadatravu/Tutorials | /pr_euler_sol/problem_6/sol_6.py | 715 | 3.796875 | 4 | def get_squares_sum(num):
"""
Returns the squares sum
"""
sum=0
for i in range(0,num,1):
sum=sum+i*i
return sum
def get_sum_square(num):
"""
Returns the sum of squares
"""
sum=0
for i in range(0,num,1):
sum = sum+i
return sum*sum
def main():
"""... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.