blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
1802b6697bd667627b2bc2de511340ce52a447e6 | maahn/meteo_si | /meteo_si/wind.py | 1,794 | 3.578125 | 4 | # -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function
import numpy as np
# from .constants import *
'''
Functions to deal with wind observations.
'''
def circular_mean(angles):
"""
Compute the arithmetic circular mean, not ignoring NaNs.
Parameters
----------
... |
bb6596a279c26e84d18566c30cd0f63e744db861 | hoangminhhuyen/B-i-gi-i-th-c-h-nh-ph-n-t-ch-d-li-u-Pandas | /1.3.py | 617 | 3.609375 | 4 | import pandas as pd
import matplotlib.pyplot as plt
movies = pd.read_csv('movies.csv')
#tách year ra khỏi title
movies["year"] = movies.title.apply(lambda x: x[-5:-1])
#loại bỏ những year NaN
movies.year=pd.to_numeric(movies.year,errors='coerce',downcast='integer')
#print(movies.year)
#tách genres thành... |
f21b83e43c684b421e42b31c7e7d4180a1672ba5 | Ben1152000/Lost-Continent | /source/mapping/vertex.py | 1,027 | 3.640625 | 4 |
class Vertex():
def __init__(self, x, y):
self.x = x
self.y = y
@staticmethod
def fromDict(vectorDict):
return Vertex(vectorDict["lon"], vectorDict["lat"])
def __eq__(self, other):
return self.x == other.x and self.y == other.y
def __neg__(self):
retu... |
fe060087457455478d7b6609c0b8b2e765908e20 | mross982/Ordinary_Least_Squares | /FACT-G_OLS.py | 1,646 | 3.5625 | 4 | import numpy as np
import pandas as pd
import statsmodels.api as sm
import statsmodels.formula.api as smf
import matplotlib as plt
df = pd.read_csv('C:\\Users\\mrwilliams\\Documents\\Program_Projects\\Ordinary_Least_Squares\\FACT-G.csv', index_col=0)
# Rescale FACT-G scores to 0 - 100 scale as described in Model 1 o... |
9feef2ad06703a3f3f7becb72227d7e8d63b70d9 | TechGirl254/Training101 | /exercise2.py | 583 | 4.15625 | 4 |
# tasklist
tasklist=[23,"jane",["Lesson23",560, {"currency":"KES"}],987,(76,"john")]
# Determine the type of variable tasklist using an inbuilt function
# Print KES
print(tasklist[2][2])
# print(tasklist(c))
# Print 560
# Use a function to determine the length of tasklist
print(len(tasklist))
# change 987 to 789 us... |
b19b91515c63d709dd4a9455213b6cfc7cf38561 | loganpassi/Python | /Algorithms and Data Structures/HW/HW1/distinctNums.py | 1,367 | 4.21875 | 4 | #Logan Passi
#CPSC-34000
#08/27/19
#distinctNums.py
#Write a Python function that takes a sequence of numbers and determines
#if all the numbers are different from each other (that is, they are distinct).
def isDistinct (list, numElem):
count = 0
for i in range(numElem):
currentElem = list[i]... |
f14933cf45966998acc73b44d34d7098f9e6011f | akshatvaidya/SocketProgramming | /Client.py | 5,148 | 3.90625 | 4 | # Name - Akshat Vaidya
# Student Id - 1001550684
# importing all the necessary libraries
# socket library is used to create and handle various sockets
# easygui library is used to create gui
# os library is used to get the file list at a specific location
import socket
import easygui
import os
# specifying t... |
2f87f14ad5db4f60ae47913e6c65a44987eeca90 | jacob568/JDJ-1 | /JacobsTestedThings/CmToFtIn/__init__.py | 512 | 4.25 | 4 | #Converts cm reading to feet and inches
def ConvertToFeetAndInch(cm):
if is_number(cm) == False:
return "Incorrect input type, please enter a number"
inches = float(cm) / 2.54
feet = 0
working = True
while working:
if inches >= 12.0:
feet += 1;
inches -= 12.0;
else:
return (str(feet) + "ft " + str(... |
def3fc6198b0b1d7fcbae2a40a1b21c756587a65 | Richard-12/Curso-Python-Objetos | /herencia-funcionesdeprueba(c09).py | 1,583 | 4.09375 | 4 | # Herencia: funciones de prueba.
# Se utilizará el ejemplo anterior
class Calculadora:
def __init__(self, numero):
self.n = numero
self.datos = [0 for i in range(numero)]
def ingresardato(self):
self.datos = [int(input('Ingrese los datos ' + str(i + 1) + ' = ')) for i in range(self.n)]
... |
5a5145897fbb50e675c3e386eb67f4f0c2e3ccaf | arnaudpilato/Wild-Code-School | /France IOI/01 - Fundamentals 1/28 - Construction d'une pyramide.py | 141 | 3.6875 | 4 | coté = 1
bloc = 1
total = 1
for loop in range (8):
coté = coté + 2
bloc = bloc + coté * coté * coté
total = bloc
print (total)
|
34e1f92b0fd6f65ebf0d8e23f951e7d9be380dcc | RShankar/Social-Web-Apps | /Melissa-Serrano/Homework1_Serrano_WebServicesTutorial/WebServicesJSON.py | 2,141 | 3.75 | 4 | import urllib
import json
serviceurl = 'http://maps.googleapis.com/maps/api/geocode/json?' #Google Maps API URL used to search for geocode information
while True:
address = raw_input('Enter location: ') #get a location from the user
if len(address) < 1 : break #get out (since no address was entered) and ... |
3b74ef10692d52565a2bf5a916bd54d277091e7a | Ernjivi/bedu_python01 | /Curso-de-Python/Clase-01/Soluciones/tabla-verdad-not.py | 1,054 | 3.96875 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Imprimir la tabla de verdad del operador lógico NOT en la salida estándar
en forma tabular incluyendo operador1 y resultado.
"""
# Variables que definen las dimensiones de la tabla
ancho_ter = 58 # Ancho de la terminal
ancho_op1 = 10 # Ancho del campo del operador 1... |
8166c243d3a7cacb0b3fb3da36c9519837ef98c7 | duanheyun/Dhy | /python_pratice/python_002/python_00/python_bicycle.py | 683 | 3.796875 | 4 | class Bicycle:
def run(self, km):
print(f"一共骑了{km}km")
#bike = Bicycle()
#bike.run(100)
#继承父类
class Ebicycle(Bicycle):
def __init__(self, valume):
self.valume = valume
# 电动车充了多少电
def fill_change(self, vol):
print(f"充了{vol}电")
print(f"充完电之后 还有{vol+self.valume}电")
... |
6a4ab8f96b7928aa0b0919289095ac6a72691531 | AZ-OO/Python_Tutorial_3rd_Edition | /10章 標準ライブラリめぐり/10.6.py | 1,038 | 3.90625 | 4 | """
10.6 数学
"""
# mathモジュールを使うと、浮動小数点数数学用の下層のCライブラリ関数にアクセスできる
import math
print(math.cos(math.pi / 4)) # <-- 0.7071067811865476
print(math.log(1024, 2)) # <-- 10.0
# randomモジュールは無作為抽出のツールを提供する
import random
print(random.choice(['apple', 'pear', 'banana']))
print(random.sample(range(100), 10)) # 重複なしの抽出 <-- ... |
2deb2adada5ca5b43d899b190caa4f161037a5df | sandeepvvs007/Python_code | /dailly.py | 948 | 3.84375 | 4 | one=int(input("please enter first number"))
two=int(input("please enter second number"))
oper=input("please enter A for addition S for substraction M for multiplication D for division and X for exit").casefold()
while oper != "e" :
if oper =="a":
print("sum is {}".format(one+two))
elif oper == "s"... |
471f9b9faf20539761835e3692620dc1b811f7d5 | beatrizsnichelotto/curso-python-selenium | /Python/if_else.py | 404 | 3.84375 | 4 |
# IF = SE
# "Pai, você comprou pão"
# Resposta == sim ou == não
# Se comprou, ele vai agradecer
# Se não comprou, ele vai chorar
# ELIF = else if - Se não, outra coisa
# ELSE = se não, sem resposta
resposta = input ('Pai, você comprou pão? ')
if resposta == 'sim':
print ('Obrigado Pai')
elif resposta == '... |
c94ccd0a85e202e31cb7f224cbd56271be9fe8fe | 3232731490/Python | /爬虫笔记/day_02/re_findall.py | 296 | 3.71875 | 4 | #findall(str,begin,end)
#返回一个所有匹配成功子串的列表
#findier(str,begin,end)
#返回一个匹配对象的迭代器对象
import re
pattern= re.compile(r"\d+")
m=pattern.findall("aaa 12345 789")
print(m)
m=pattern.finditer("aaa 123456 789")
for i in m:
print(i.group()) |
dcd9e319696c4f7b27432d87400ca545b0bddfa1 | Renan-S/How-I-Program | /Python/Curso de Python/Dicionarios.py | 742 | 4.1875 | 4 | """
Dicionários {dict}
Em algumas linguagens, os dicionários são chamados de mapas
Dicionário = Coleção de chave/valor
Chaves e valores podem ser de qualquer tipo
Dicionário é representado por {}
#O primeiro string é uma chave e o segundo (após :) um valor
paises = {'br': 'Brasil', 'thai': 'Thailandi... |
3b5b07b16c2a955e3cc87aae8ddce46491ef0b82 | boredcactu/data-structures-and-algorithms-python | /data_structures_and_algorithms/data_structures/stacks_and_queues/stacks_and_queues.py | 3,647 | 4.375 | 4 | class Node:
def __init__(self,value):
self.value = value
self.next = None
class Queue:
def __init__(self):
self.front = None
self.rear = None
def enqueue(self, *value):
"""
it takes any value as an argument and adds a new node with that value to the back of ... |
52b616788bca2013bcc0cf9f716ad5c0486cf80f | arpitsomani8/Data-Structures-And-Algorithm-With-Python | /Searching/Linear_Search.py | 581 | 3.9375 | 4 | # -*- coding: utf-8 -*-
"""
@author: Arpit Somani
"""
def linear_search(n,x):
element=[]
for i in range(1,n):
element.append(i)
count=0
flag=0
for i in element:
count+=1
if(i==x):
print("Yes! I found my number at position"+str(i))
flag=1
break;
if(flag==0):
print("Number is not found... |
fa3a3509dda7a2e7e3eb6d373eb5aaee47cab304 | shasafoster/ProjectEuler | /q30_number.py | 625 | 3.8125 | 4 | """
Surprisingly there are only three numbers that can be written as the sum of fourth powers of their digits:
1634 = 1^4 + 6^4 + 3^4 + 4^4
8208 = 8^4 + 2^4 + 0^4 + 8^4
9474 = 9^4 + 4^4 + 7^4 + 4^4
As 1 = 1^4 is not a sum it is not included.
The sum of these numbers is 1634 + 8208 + 9474 = 19316.
Find the sum of all... |
67b0152a4fd12efd8a66c91d755ea05347156b0d | 1715439636/professional-python3 | /正则表达式/5_标记.py | 1,879 | 3.625 | 4 | """
作者:文文
正则表达式中的标记
python版本:python3.5
"""
import re
"""
re.IGNORECASE | re.I :忽略大小写
re.DOTALL | re.S : .字符在正常情况下不会匹配换行符,但是使用re.S可以使其匹配换行符
re.MULTILINE | re.M : 多行模式,导致仅能够匹配字符串开始与结束的^和$字符可以匹配字符串内任意行的开始与结束
re.VERBOSE | re.X : 允许复杂的正则表达式以更容易阅读的方式表示。导致所有的空白(除了在字符组中的)被忽略,包括换行符,同时将#当作注释字符
re.DEBUG : 编译正则表达式时将一些调试信息输出到sys... |
005bae0f1b808032f5c7e387e0e204de536039c4 | ninehundred1/MiscStuff | /TwitterToMongoDB.py | 3,346 | 3.53125 | 4 | """
Stream live tweets using the twitter API and tweepy. Streams are stored in a mongodb database.
Set filter keywords at bottom.
Stop by interrupting (Ctrl-C) or setting max_tweets
Requires the extra libraries:
pymongo
tweepy
The data is stored in pymongo database:
tweet_db
Collection:
TweetsReceived
"""
import pymo... |
218bb37891952f08845e09549086bcada21d9915 | JasonBehrend7/Behrend_Jason | /PyLesson_11/TwoPoints.py | 1,181 | 3.96875 | 4 | import math
class Distance:
def __init__ (self, x1, y1, x2, y2):
self.xOne = x1
self.yOne = y1
self.xTwo = x2
self.yTwo = y2
self.distance = 0
def newPoints (self, x1, y1, x2, y2):
self.xOne = x1
self.yOne = y1
self.xTwo = x2
self.yTwo =... |
d91dc4ccdf8353e8572c58a2c84e90fa33a13f59 | cheeordie1/Article-Filterer | /nlp/highlight.py | 1,132 | 3.53125 | 4 | """
Usage: python3 highlight.py <user_id> <article_id>
Outputs: a JSON document specifying which paragraphs of the article should be
highlighted based on the user's article history
"""
import psycopg2
import sys
"""
highlight the article based on the user's history using some method
params:
article: string contai... |
1c7c6954e44e345c0ff34a26c502ddd65728d60e | prathapSEDT/pythonnov | /Collections/List/Remove.py | 167 | 3.90625 | 4 | myList=['a',4,7,2,9,3,7]
'''
this method is use to remove an element by using the value
remove the first occurance
'''
myList.remove(7)
myList.remove(11)
print(myList) |
8c13059bc98413be841869e72ba6b93a606bff09 | rafaelperazzo/programacao-web | /moodledata/vpl_data/303/usersdata/296/78458/submittedfiles/testes.py | 153 | 3.953125 | 4 | # -*- coding: utf-8 -*-
#COMECE AQUI ABAIXO
n = int(input("Digite um número: "))
if n%2==0:
print(PAR)
else:
print(ÍMPAR)
|
e8ca86fa465c922f454098f1c1f5f398df28612a | sleighsoft/algorithms | /countingsort.py | 1,164 | 3.875 | 4 | def countingsort(input, key=lambda x: x): # O(n+k) -> k = non-negative value range
"""A 2-pass sort algorithm that is efficient when the number of distinct
keys is small compared to the number of items.
Stable sorting.
Args:
input ([List[int]]): List of positive integers.
key (Callabl... |
3b31e658f0721a83498a44704998368ea7025894 | imsreyas7/DAA-lab | /Recursion/matpow.py | 1,049 | 4.15625 | 4 | def print_matrix(matrix):
for i in range(len(matrix)):
for j in range(len(matrix[0])):
print("\t",matrix[i][j],end=" ")
print("\n")
a=int(input("Enter the power for power of the matrix "))
m = int( input("enter first matrix rows "));
n = int( input("enter first matrix columns "));
array1=[[0 for j... |
7a8492a30cc6962a05e52ab1a2fecdaffd96ff9e | JosephPress13/CP1404-Early-Pracs | /Loops.py | 322 | 3.984375 | 4 | for i in range(1, 21, 2):
print(i, end=' ')
print()
for i in range(0, 100, 10):
print(i, end=' ')
print()
for i in range(20, 0, -1):
print(i, end=' ')
print()
n = int(input("How many stars would you like? "))
for i in range(0, n):
for i in range(0, i):
print("*", end=" ")
print("*")
print... |
463e5699efe5ec96e680b420539671763a8747b9 | SwetaNikki/Python-Assignment | /DivisibleNumber.py | 486 | 4.125 | 4 | #Write a program which will find all such numbers which are divisible by 7 but are not a
#multiple of 5, between 2000 and 3200 (both included). The numbers obtained should be printed
#in a comma-separated sequence on a single line.
a = []
def mul():
for i in range(2000,3201):
if (i%7==0) and (i%5!=0):
... |
2e5f03335fba0c80afb363b756d5c3975f65f9b2 | franklingu/leetcode-solutions | /questions/prime-number-of-set-bits-in-binary-representation/Solution.py | 1,315 | 3.9375 | 4 | """
Given two integers L and R, find the count of numbers in the range [L, R] (inclusive) having a prime number of set bits in their binary representation.
(Recall that the number of set bits an integer has is the number of 1s present when written in binary. For example, 21 written in binary is 10101 which has 3 set b... |
e6462622f0a865a9d16e244a1a63f3ad1cbf0dbe | sunnyyeti/Leetcode-solutions | /966_Vowel-Spellchecker.py | 2,774 | 4.21875 | 4 | # Given a wordlist, we want to implement a spellchecker that converts a query word into a correct word.
# For a given query word, the spell checker handles two categories of spelling mistakes:
# Capitalization: If the query matches a word in the wordlist (case-insensitive), then the query word is returned with the sa... |
a4d12211caee375656252a5caf18575a006b3891 | mindw96/nalcoding | /mathutil.py | 4,581 | 3.5625 | 4 | import _csv
import os
import PIL.Image
import matplotlib.pyplot as plt
import numpy as np
# 수학적인 계산이 필요한 함수들을 모아둔 파일이다.
def relu(x):
return np.maximum(x, 0)
def relu_derv(y):
return np.sign(y)
def sigmoid(x):
return np.exp(-relu(-x)) / (1.0 + np.exp(-np.abs(x)))
def sigmoid_derv(y):
return y *... |
6ed9eb4759db5319b23c169fa82af8be70610701 | SnottyJACK/Python_Projects | /Password.py | 393 | 3.765625 | 4 | #Password
#if construction demonstration
print("Добро пожаловать к нам в ООО \"Системы безопасности\".")
print("--Безопасность - наше второе имя\n")
password = input("Введите пароль: ")
if password == "abrakadabra":
print("Доступ открыт")
else:
print("Вы не прошли проверку")
|
1f4471e03e63bc0a35bffda9d588b9bad50b7be8 | D-J-Harris/AdventOfCode2020 | /days/day18.py | 1,567 | 3.609375 | 4 | """Operation Order"""
def act_op(left, right, op):
if op == '+':
return left + right
if op == '*':
return left * right
def evaluate(inp, first):
if first:
ans = 0
operator = ''
for x in inp:
if isinstance(x, int):
if ans == 0:
... |
4febab4366ab130c81aeff1658d59882a1be875c | Anjana97/python | /pythondatastructures/listprograms/listprograms.py | 194 | 3.9375 | 4 | list=["java","python","c#","javascript"]
# print(type(list))
# print(list[-1:-4:-1])
# list.append("dart")
# list[1]="ruby"
# for item in list:
# # print(item)
list.insert(2,"c")
print(list) |
7f858f5b83315edc2fd7f94a0790d5439a4c4e74 | Asim-Product-College/CS-1.1-Programming-Fundamentals | /MadLibs/madlibs.py | 3,539 | 3.609375 | 4 | # CS 1.1
# Project: Mad Libs
# Written By: Asim Zaidi
# List of Requirements
# Write madlibs program
#list or string, or some different data structure of stories to change, choose from set of stories.
# ask for 5 user inputs line by line.
# randomize user inputs
# insert mad libs into template and return that to user.... |
ff646a54d7b5e9b602c5ebe5d223819866659485 | oneTaken/leetcode | /easy/575.py | 262 | 3.53125 | 4 | class Solution:
def distributeCandies(self, candies):
"""
:type candies: List[int]
:rtype: int
"""
length = len(candies)
kinds = len(set(candies))
return length // 2 if kinds >= length // 2 else kinds
|
6d3cfcec4626a9ba21cd1d113dd4e98f3da75f6f | Llari7/mi_primer_programa | /Calculadora.py | 584 | 4 | 4 |
operacion = input("¿Qué operación deseas realizar? (suma / resta / multiplicación / división): ")
primer_numero = int(input("Primer número: "))
segundo_numero = int(input("Segundo número: "))
if operacion == "suma":
print("Resultado: {}".format(primer_numero + segundo_numero))
elif operacion == "resta":
print... |
2d72456219249154ae02e5646abf5401e782e78f | zako16/heinold_exercises | /1Basics/2Numbers/2-19.py | 517 | 4.15625 | 4 | """
Write a program that draws “modular rectangles” like the ones below. The user specifies the
width and height of the rectangle, and the entries start at 0 and increase typewriter fashion
from left to right and top to bottom, but are all done mod 10. Below are examples of a 3 × 5
rectangle and a 4 × 8 .
"""
wide = ev... |
a36950a2e22c8631111ab36b0dd8c44e4fe44957 | ConstantinescuRachel-zz/PLP | /Problem 2.py | 570 | 3.9375 | 4 | # Define a class which has at least two methods:
# getString: to get a string from console input
# printString: to print the string in upper case.
# Hints:
# Use __init__ method to construct some parameters
class InputOutString:
def __init__(self):
print "Test" #why if I remove this line, I get errors for ... |
590628bbd553024a9eb968451cef42cff6c68d86 | VSMourya/Leetcode_Easy | /Best Time to Buy and Sell Stock II.py | 442 | 3.796875 | 4 |
def maxProfit(prices):
stack = []
profit = 0
for price in prices:
if not stack:
stack.append(price)
else:
if stack[-1] > price:
stack[-1] = price
else:
profit += price -stack[-1]
stack[-1] = ... |
69d0b1cd077f8f62db0383eea91f5206c35aafd0 | bferriman/python-learning | /examples/strings1.py | 1,131 | 4.5625 | 5 | # strings can be in single, double, or triple quotes
print(type('3'))
print(type("3"))
print(type('''3'''))
samp_string = "This is a very important string"
print("Length:", len(samp_string))
# reference first char in samp_string
print(samp_string[0])
# reference last char in samp_string
print(samp_string[-1])
# grab... |
a7a76576a08a327259bb981cb861ded391f56304 | kunzhang1110/COMP9021-Principles-of-Programming | /Quiz/Quiz_8/quiz_8.py | 3,377 | 4.09375 | 4 | # Randomly fills a grid of size 10 x 10 with digits between 0
# and bound - 1, with bound provided by the user.
# Given a point P of coordinates (x, y) and an integer "target"
# also all provided by the user, finds a path starting from P,
# moving either horizontally or vertically, in either direction,
# so that the nu... |
4b3828a25560426b7934056c483a5d798828dbc9 | s3wasser/WATcher | /HTMLScraper.py | 2,187 | 3.828125 | 4 | import urllib2
from bs4 import BeautifulSoup
# Simple HTML scraping and parsing class using the Beautiful Soup Library
# To use, simply instantiate and call getCourseInformationTable to get a
# 2D array of the course information
class HTMLTableParser:
userAgent = 'Mozilla/5.0 (Windows NT 6.1; Win64; x64)'
headers =... |
cdfde67210d0fe5c80ed89b60180a1bb07431908 | msszczep/npr_sunday_puzzle_solutions | /src/python/puzzle_2014-01-19.py | 1,837 | 3.734375 | 4 | #!/usr/bin/python
# -*- coding: utf-8 -*-
"""
http://www.npr.org/2014/01/19/263785641/three-bs-bring-you-to-one
Name a famous person whose first and last names together contain four doubled letters -- all four of these being
different letters of the alphabet. Who is it? For example, Buddy Holly's name has two double... |
0fc986d8da7cd1b7eb6de435b18d7c48bf70e14e | ash/amazing_python3 | /144-fib.py | 164 | 3.828125 | 4 | # Generating and printing
# Fibonacci numbers
# below 100
a, b = 0, 1
while a < 100:
print(a)
a, b = b, a + b
# Notice how nice is
# multiple assignment |
f1a1fcf2223a9c2d62512e0864d98ed8d37447e9 | KatyaKalache/holbertonschool-higher_level_programming | /0x0A-python-inheritance/1-my_list.py | 172 | 3.90625 | 4 | #!/usr/bin/python3
class MyList(list):
list = []
def print_sorted(self):
MyList.list.append(self)
for i in self.list:
print(sorted(i))
|
039241463202bb8aea84cfebf94514b59807b218 | chen13545260986/hello_python | /4常用模块/json模块.py | 447 | 3.5 | 4 | # 序列化模块
# 序列化--转向一个字符串数据类型
# 序列--字符串
# json:dumps序列化方法,loads反序列化方法
import json
dic = {'k1':'v1'}
str_d = json.dumps(dic)
print(type(str_d), str_d)
dic_d = json.loads(str_d)
print(type(dic_d), dic_d)
# json:dump和load
# f = open('fff', 'w', encoding='utf-8')
# json.dump(dic, f)
# f.close()
f2 = open('fff', 'r', encodi... |
b086a56fd1fc5e28b7c38ba4b7bc798e7a1b16f4 | tantziu/Algorithms_python | /graph_playground.py | 2,194 | 3.71875 | 4 | import collections
def dfs_recursion(graph, node, visited=None):
if visited is None:
visited = set()
if node not in visited:
print(node)
visited.add(node)
for neighbour in graph[node]:
dfs_recursion(graph, neighbour, visited)
def bfs_recursion(graph, queue=None, v... |
08780bf97369149720e3b7f9d75a9d714644eff5 | EmlynQuan/Programming-Python | /JZOffer/JZOffer27.py | 565 | 3.59375 | 4 | # coding=utf-8
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
def mirrorTree(root):
"""
:type root: TreeNode
:rtype: TreeNode
"""
if root == None:
return root
queue = [root]
while queue:
temp = que... |
48a599165d1fd8a8d3714aff112083418703d007 | jeanpierreba/holbertonschool-higher_level_programming | /0x0C-python-almost_a_circle/tests/test_base.py | 3,556 | 3.640625 | 4 | #!/usr/bin/python3
""" Unittest for Base class """
import unittest
import os
from models.base import Base
from models.rectangle import Rectangle
from models.square import Square
class Test_Base(unittest.TestCase):
""" Class to test the Base class """
def setUp(self):
Base._Base__nb_objects = 0
... |
15598593efdf061ca0d18701ef611f6af9a44eb1 | CodemanNeil/LearningFromData | /HW2/CoinFlipping.py | 1,328 | 3.625 | 4 | import random
class CoinFlipping:
def __init__(self, numCoins = 1000, numFlips = 10):
self.numCoins = numCoins
self.numFlips = numFlips
self.headFrequency = [0] * self.numCoins
self.flipCoins()
def flipCoins(self):
for coinNumber in range(self.numCoins):
f... |
b95b9f02326ea5b5f63158c3af4b8f36b06a946b | solkan1201/Vivace | /code/libs/modos_de_transmissao.py | 511 | 3.609375 | 4 | class SeletorDeModos(object):
def __init__(self, criador):
self.criador = criador
def setModo(self, modo):
"""Função responsável por setar o modo de tranmissao de dados.
"""
self.criador.modo.valor = modo
print('Trocando para modo ' + str(modo) + ' de transmissao!')
... |
458389f0c946dd660fd0b7b140caea1d11f2ade2 | iljuhas7/lab-9 | /example_1.py | 1,499 | 3.953125 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
if __name__ == '__main__':
school = {'1а': 12, '1б': 24, '2а': 10, '2б': 8, '6a': 25, '6б': 13, '8а': 14, "9б": 12}
while True:
n = input('Введите название операции >>> ')
if n == 'change':
school.update({input(f'Название изменяемого кл... |
0127de62c5e7a9ca88b7b5968517a8e7be353afa | pisces0009/PythonProgram | /hamburger8.py | 1,812 | 4.0625 | 4 | ##############################################################
# fILE: humberger8.py
# Author: Prasad Kale
# Date: january.24,2018
# Purpose: Nested if statement
##############################################################
# print headings
print("\n ... Hamburger 8 ....")
print("======================\n")
#prompt... |
6e5dd0410247273d961e07c966e47f57c0d30f7e | Erick-ViBe/LeetCodePython | /ArraysAndStrings/longestSubstringWithoutRepeatingCharacters.py | 785 | 4.125 | 4 | """
Given a string s, find the length of the longest substring without repeating characters.
Input: s = "pwwkew"
Output: 3
Explanation: The answer is "wke", with the length of 3.
Notice that the answer must be a substring, "pwke" is a subsequence and not a substring.
"""
def lengthOfLongestSubstring(s):
n = len(s... |
8157fe73d2fb6760b575f87a89f368ce1819f72c | PeterSzasz/GraphApp | /utilities/delaunay.py | 8,805 | 3.5625 | 4 | # delaunay triangulation
from math import sqrt
import numpy as np
from utilities.node_generator import NodeGeneratorBase
from core.graph import Node,Edge, Graph
class Triangle(Graph):
'''
helper class for delaunay triangulation
the Bowyer-Watson algorithm uses it mostly
'''
def __init__(self):
... |
06415239b46083595089cc2d8d285b535f00e39f | RifasM/Python-Lab | /1st Cycle Experiments/Program11.py | 304 | 4.15625 | 4 | """
Write a program to compare two numbers without using relational operator
"""
a, b = map(int, input("Enter two numbers: ").split())
if not a ^ b == 0:
print("Not equal")
else:
print("Equal")
"""
OUTPUT
Enter two numbers: 3 52
Not equal
Enter two numbers: 50 50
Equal
""" |
d77bc91ff9be04185bc84499636ed6e423cd3e97 | knpatil/learning-python | /src/bank_account.py | 951 | 3.734375 | 4 | class BankAccount:
def __init__(self, name):
self.name = name
self.balance = 0.00
self.transaction_fee = 0.00
def deposit(self, amount):
if amount > 0:
self.balance += amount
def withdraw(self, amount, transaction_fee=0.00):
if transaction_fee < 0:
... |
0c4d0cf9b68c22a0a5ea739f7812e21f0841b3fa | prnanda/python | /CodeAcademy/Reverse_String.py | 305 | 4.15625 | 4 | def reverse(input):
reversed = ""
i = len(input)-1
while i >=0:
reversed = reversed + input[i]
i-=1
return reversed
choice = "y"
while choice == "y":
input1 = raw_input("Please enter a string: ")
input1 = str(input1)
print reverse(input1)
choice = raw_input("Continue?") |
bfc9e0b68dd518ee4bd6006d26121d62f30efb1b | congyingTech/Basic-Algorithm | /old-leetcode/older/SumofTwoIntegers371.py | 766 | 3.515625 | 4 | class Solution(object):
def getSum(self, a, b):
"""
:type a: int
:type b: int
:rtype: int
"""
MASK = 0x100000000
#max_int是long int的最大值
MAX_INT = 0x7FFFFFFF
def add(a,b):
if b==0:
return a
#1.获得个位数的值
... |
edd4bba64ee5e7849db135b0353468ff68f1a755 | Sreeram225/internsearch | /doublelinkedlist.py | 1,112 | 4 | 4 | class Node:
def __init__(Node, data):
Node.data = data
Node.next = None
Node.prev = None
def insertNodestart(head, newNode):
newNode.next = head
head.prev = newNode
newNode.prev=None
head=newNode
return head
def insertmiddle(head, newNode):
temp = head
while (... |
d8c78922fe0316d16ca2c7dce5a39ba901e71ac6 | mike-peterson04/dataStructures | /linkedlist.py | 922 | 4.09375 | 4 | from node import Node
class LinkedList:
def __init__(self):
self.head = None
self.tail = None
def append_node(self, data):
node = Node(data)
if self.head is None:
self.head = node
self.tail = node
else:
self.tail.next = node
... |
e934414e4bae0e27a3347af8808e30d60cb60ca0 | Dharani379/BEST-ENLIST-Internship | /functions.py | 658 | 4.09375 | 4 | #Creating a function for getting input from userand doing folloeing atmatic operations
a= int(input("Enter the value:"))
b= int(input("Enter the value:"))
import math
def Dharani(a,b):
c=a+b
d=a-b
x=a*b
y=a/b
return c,d,x,y
print(Dharani(a,b))
#Creating a function covid()'''2nd task... |
9d4beef6220fa029242f81f2d6b2eec8e68890b0 | AbdallahHemdan/Python-Solutions | /Basic Data Types/Lists.py | 516 | 3.765625 | 4 | if __name__ == '__main__':
N =int(input())
l = []
for i in range(0,N):
t = input().split()
if t[0]=="insert" :
l.insert(int(t[1]),int(t[2]))
elif t[0]=="print":
print (l)
elif t[0]=="remove" :
l.remove(int(t[1]))
elif t[0]=="ap... |
54cdd75d750d2aad61b3cdc07aede2145f6938d7 | nsid10/Project-euler | /problems/046.py | 567 | 3.984375 | 4 | def primality(n):
if type(n) != int:
raise TypeError("argument must be of type 'int'")
if n == 2:
return True
if n < 2 or n % 2 == 0:
return False
for i in range(3, int(n**0.5 + 1), 2):
if n % i == 0:
return False
return True
def gold(n):
for i in ra... |
5a588dc31c921258087cb172fc9d66f3733215df | Smitharry/HackerrankTasks | /src/AngryProfessorSolution.py | 703 | 3.84375 | 4 | def is_professor_angry(threshold, arrival_times) :
'''Print if class is cancelled.'''
if count_arrival_on_time(arrival_times) < threshold :
print('YES')
else :
print('NO')
def count_arrival_on_time(arrival_times):
'''Count number of students who arrived on time'''
students_on_time =... |
51018b88511838475ff3fbbd47b0249ced3e6516 | DiogenesGois/Estudos-de-Python | /Aprendendo_Python/3Loops/Ex6Maior.py | 186 | 4.15625 | 4 | # maior dos 5 numeros
maior = 0
for i in range(5):
numero = int(input("Insira um numero\n"))
if numero > maior:
maior = numero
print("O maior numero foi: ", maior) |
81242b6c3011333a94e2568540fdcf6ad9739d7c | ngothuyhoa/Python_Exercises | /Exercise_1/exercise2.py | 238 | 4.1875 | 4 | celsius = input('Enter Celsius is Digit: ')
while (celsius.isalpha() or celsius == ''):
celsius = input('Wrong!! Please enter celsius is digit: ')
fahrenheit = (float(celsius)*9)/5 +32
print('{}C = {}F'.format(celsius, fahrenheit)) |
9625ab768c1d0140920804d643a116fc17023201 | thedatazen/DataEngineering | /2-Algo & Sys Design/4-LC/344 Reverse String.py | 1,053 | 4.46875 | 4 | '''
Write a function that reverses a string. The input string is given as an array of characters char[].
Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory.
You may assume all the characters consist of printable ascii characters.
Example 1:
... |
adc84918a1c7758382c83a906ed9ec7ac33f69bf | luzap/mt | /tournament/utils.py | 285 | 3.578125 | 4 | import random
def gen_code(name):
"""Generates a code for the school based upon initials and a random number, to avoid any potential cheating."""
words = name.split(" ")
code = "".join([word[0:1].upper() for word in words]) + str(random.randint(1, 571))
return code
|
6e4ae1ac72d902bf48aac52019942e701ceca5f5 | habibor144369/python-all-data-structure | /list-pop.py | 180 | 3.703125 | 4 | # pop in list---
list = ['Mango', 'Banana', 'Orange','Avocado', 'Apple', 'Pineapple', 'Peach', 'Melon',]
item = list.pop()
item2 = list.pop(2)
print(item)
print(item2)
print(list)
|
e7fa698b4767519971cb2d2b0c094e6123fdb5ff | TusharDimri/Python | /OOPS 4.py | 3,131 | 4.125 | 4 | # Class Methods inn Python
class Fender:
instruments_no = 1
def __init__(self, argument_name , argument_role, argument_net):
self.name = argument_name
self.role = argument_role
self.net = argument_net
def help(self):
return f"Name is {self.name},role is {self.role} & net wor... |
5c57174a12d23cabd7ee2502edf5847490bb4454 | zedudedaniel/IntroProgramming-Labs | /lab04/guessing_game.py | 657 | 3.96875 | 4 | #Have the user guess the animal
#Keep repeating until they get it correct
def main():
animal = "tardigrade"
while (True):
guess = input("Guess the animal! ").lower()
if (guess[0] == "q"):
print("Seeya!")
break
elif (guess == animal):
print("Correct!")... |
a7b0cc430144db3e44123ac267768bd54e5b317c | maxlauhi/webapps | /coroutine.py | 1,075 | 3.859375 | 4 | #!/usr/bin/python
#coding:utf-8
'''生产一个跳到消费者手上,给消费者消费,
消费完后把消息告诉生产者,生产者接收到消费者消费完的消息,打印出来后继续生产
问题:要把生产者生产和消费者消费两个子程序放在一个线程里,用协程的方式执行。
'''
import time
# 消费者
def consumer():
r = ''
while True:
n = yield r
# 如果N=0就代表没有生产,也就没有消费返回空值就可以
if not n:
return
# 打印正在消费第几个的消息
print ('[CONSUMER] Consuming %s...' % n... |
3628946e406d89b414ae4b4b03235236356e16a3 | nmeripo/Data-Structures-and-Algorithms | /LeetCode/Sorting And Searching/Merge_k_Sorted_Linked_Lists.py | 1,068 | 4.03125 | 4 | # Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity.
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
from heapq import *
ListNode.__lt__ = lambda self, n2: self.val < n2.val
... |
bcfcf23d95bf6cbbf484f149efd65959179ea56b | JDPowell648/Code | /Intro to Computing/planner.py | 5,644 | 3.9375 | 4 | '''
Author: Joshua Powell
File: planner.py
Description: A by-the-hour planner for daily and weekly use
'''
from random import randint
def makeList(inputList):
for index in range(0,24):
inputList.append([index, "unscheduled", False])
return inputList
class planner():
def __init__(self)... |
4821ff6c1538a35235010ed53729f71044dd9ceb | kks4866/pyworks | /exercise/test02.py | 1,220 | 3.75 | 4 | # 1번문제
국어 = 80
영어 = 75
수학 = 55
sum = 국어+영어+수학
Average = sum/3
print("평균 점수 : ", Average)
#2번문제
num = 13
print(13%2)
n=13
if n%2==0:
print("짝수")
else:
print("홀수")
#3번문제
pin = "881120-1068234"
yyyymmdd = pin[0:6]
num = pin[7:]
print(yyyymmdd)
print(num)
#4번문제
pin ="881120-2068234"
gender = pin[7]
prin... |
f36d48d011af9f55ff819fe5287e9b9ba019aaba | chenhuang/leetcode | /minDistance.py | 2,157 | 3.890625 | 4 | #! /usr/bin/env python
'''
Edit Distance
Given two words word1 and word2, find the minimum number of steps required to convert word1 to word2. (each operation is counted as 1 step.)
You have the following 3 operations permitted on a word:
a) Insert a character
b) Delete a character
c) Replace a character
https://... |
1d8ede60bf87c32854abd0e7eacb816ff62ef617 | syurskyi/Python_Topics | /125_algorithms/_examples/_algorithms_challenges/pybites/beginner/318/decode.py | 514 | 3.59375 | 4 | import base64
import csv
from typing import List # will remove with 3.9
def get_credit_cards(data: bytes) -> List[str]:
"""Decode the base64 encoded data which gives you a csv
of "first_name,last_name,credit_card", from which you have
to extract the credit card numbers.
"""
temp_list = []
for... |
3ec4aaab7ed5932237eea35205b80555323048e2 | Vozsco/DLA | /randomAtRadius.py | 528 | 3.765625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sun Nov 8 17:24:56 2020
@author: User
"""
"""
Function that generates the random pos, at the specified Radius
INPUT = Radius, Xseed, Yseed
OUTPUT = [x,y] pos
"""
import random
import numpy as np
def randomAtRadius(Radius, Xseed, Yseed):
theta = 2*np.pi*rand... |
94c12d886508919eb1c1c8b5b1e8ddf9eec44fd7 | agforero/SI-PLANNING | /Plans/CSCI121S2AGF-2.27.py | 1,664 | 4.3125 | 4 | '''
- Testing code?
- If one thing causes an error in one place, it'll cause errors everywhere.
- Make a Python function to find the max in a list. Generate the list using
import random
ls = []
for i in range(10):
ls.append(random.randint(1,10))
Define it findMax(). What argument(s) w... |
0c49e3bf2d1cb32853b34faacee2fd0c857b55fd | Critisys/Simple-fashion-classification-with-mnist | /main.py | 1,541 | 3.765625 | 4 | import tensorflow as tf
from tensorflow import keras
import matplotlib.pyplot as plt
import numpy as np
# we load images data from mnist
fashion_mnist = keras.datasets.fashion_mnist
(train_images, train_labels), (test_images, test_labels) = fashion_mnist.load_data()
class_names = ['T-shirt/top', 'Trouser', 'Pullov... |
fa8ebc9816975b98c0e09bc9f06de3ee881aa89d | abbasmalik514/30_Days_Coding_Challenge_HackerRank | /Day_01_Data_Types/Day1_script.py | 545 | 3.78125 | 4 | i = 4
d = 4.0
s = 'HackerRank '
# Declare second integer, double, and String variables.
int_num = 0
double_num = 0.0
string = ''
# Read and save an integer, double, and String to your variables.
int_num = int(input())
double_num = float(input())
string = str(input())
# Print the sum of both integer variables on a new ... |
917bad5bb0ceccbc4c5c7c9c46421b83d4a59d4f | nikonoff16/learn2code | /KGU - Basic Python/viel_21.py | 1,099 | 3.59375 | 4 | # countries = {'Russia', 'China', 'Korea'}
# Autos = {
# 'Toyota':{'Russia', 'Korea'},
# 'Toyamatokanava': set(),
# 'Mazda': {'Russia', 'China', 'Korea'}
# }
count = int(input('Какое количество автомобильных марок вы собираетесь внести: '))
countries = set()
autos = {}
while count != 0:
auto_seria... |
9e15b81b015e9bd5c7328128b7a6738612d82849 | hubinyes/python | /matplot/matplot.py | 409 | 3.65625 | 4 | import matplotlib.pyplot as plt
x_values = list(range(1,100))
y_values = [x**2 for x in x_values]
#plt.plot(xvalues,yvalues,linewidth=5)
plt.title("hello plt",fontsize=25)
plt.xlabel("value")
plt.ylabel("square")
plt.tick_params(axis='both',labelsize=15)
#plt.axis([0,110,0,1100])
plt.scatter(x_values,y_values,s=50,edg... |
7b2b6c4d09e15c38f8f094b4ca493165a784a272 | loganyu/leetcode | /problems/670_maximum_swap.py | 896 | 4.09375 | 4 | '''
Given a non-negative integer, you could swap two digits at most once to get the maximum valued number. Return the maximum valued number you could get.
Example 1:
Input: 2736
Output: 7236
Explanation: Swap the number 2 and the number 7.
Example 2:
Input: 9973
Output: 9973
Explanation: No swap.
Note:
The given numbe... |
4c1f4575e4434992b064e77bf123cc5d99f0116d | cicily-qq/pythontraining | /tongxun.py | 1,362 | 3.84375 | 4 | print('|---欢迎进入通讯录程序---')
print('|---1:查询联系人资料-')
print('|---2:插入新的联系人---')
print('|---3:删除已有联系人---')
print('|---4:退出通讯录程序---')
contacts=dict()
while 1:
instr=int(input('\n请输入相关的指令代码:'))
if instr==1:
name=input('请输入联系人姓名:')
if name in contacts:
print(name+':'+contacts[name])
... |
d2a6f5373317373046e0cb12959f2e18c950bc9f | emir-naiz/classes | /class Planets.py | 1,070 | 3.96875 | 4 | class Planet:
def __init__(self, name, size, color):
self.name = name
self.size = size
self.color = color
self.temp = -999
self.oxygen = False
self.water = False
self.humanity = False
def description(self):
print(f"Название планеты - {self.name}, ... |
aad2330f3cdb9def7795a78c7c2ab8e73df9f717 | Pickerup-Yirui/ourSpider | /urlPool.py | 1,297 | 3.921875 | 4 | """
author = "YiRui Wang"
定义了一个储存url的仓库类
创建于2020 1 13
"""
class urlPool():
"""
一个储存url的仓库类
pressIn(self, url):压入一个url,返回1
popOut(self,):弹出一个url,返回该url或-1
howMany(self,):返回当前url的数量
"""
def __init__(self,):
"""
建立一个内置队列,储存url,并初始化为空
"""
self.queue = []
... |
4b541a439b691fc89ed1ee6f3c9be5bfaa628fee | Mdwsbb01/Pyhton4E | /py4e_ex_chapter6.py | 416 | 4.40625 | 4 | #Exercise 5: Take the following Python code that stores a string:
# str = 'X-DSPAM-Confidence: 0.8475 '
# Use find and string slicing to extract the portion of the string
# after the colon character and then use the float function
# to convert the extracted string into a floating point number.
data = 'X-DSPAM-Confiden... |
94c597099d584f82b578849cb93d4fdb90148d91 | MystWalker/Fey | /Character.py | 4,097 | 3.765625 | 4 | #Define character by stats
import pygame
from pygame.locals import *
DEBUG = False
class Character (pygame.sprite.Sprite):
def __init__ ( self, color = [255,0,0], initial_position = [0,0], size = [60, 120]):
"""Returns a Character. Based on python.sprite.Sprite"""
#Sprite
pygame.sprite.Spr... |
bf63d19a83415649c8567a07594dfd1a133839f4 | github653224/GitProjects_PythonLearning | /PythonLearningFiles/麦子学院Python学习笔记/output_and_format.py | 297 | 4.34375 | 4 | str1=input('enter a string :')
str2=input('enter another string:')
print("str1 is "+str1+" and str2 is "+str2)
print('str1 is {} and str2 is {}'.format(str1,str2))
# enter a string :python
# enter another string:python2
# str1 is python and str2 is python2
# str1 is python and str2 is python2
|
e5dbd4b544f9bb05fdf491bf2a0299fa3803c701 | Eitherling/Python_homework1 | /homework_4.3.py | 106 | 3.65625 | 4 | for number in range(1,21):
print(number)
print('-' * 80)
for number in [1,21]:
print(number)
|
457858b9efc04a746716de6f9f1330a913dd8401 | HarkTu/Coding-Education | /SoftUni.bg/Python Advanced/September 2020/03. Find the Eggs.py | 819 | 4.03125 | 4 | from collections import deque
def find_strongest_eggs(sequence, sub):
found = []
sublists = []
for i in range(sub):
sublist = deque()
for x in range(i, len(sequence), sub):
sublist.append(sequence[x])
sublists.append(sublist)
for x in sublists:
mid_ind = len... |
f90806afdfc17a39caa1ae1f4020ae1846ba8cf0 | TaehoLi/Elementary-Python | /dictionary_assemble/alphanum3.py | 533 | 3.703125 | 4 | song = """by the rivers of babylon, there we sat down yeah we wept,
when we remember zion. when the wicked carried us away in captivity
required from us a song now how shall we sing the lord's song in a
strange land"""
alphabet = dict()
for c in song:
if c.isalpha() == False:
continue
c = c.lo... |
41cdb7ee72292f505d82d7a69cc89bc399e04a04 | srinathalla/python | /algo/bit/repeatedDNASequences.py | 342 | 3.515625 | 4 | import collections
from typing import List
class Solution:
def findRepeatedDnaSequences(self, s: str) -> List[str]:
count = collections.Counter(s[i:i+10] for i in range(len(s) - 9))
return [w for w in count if count[w] > 1]
s1 = "AAAAACCCCCAAAAACCCCCCAAAAAGGGTTT"
s = Solution()
print(s.findRepe... |
c7a784724627d0eb1920df73161dad47b69423f9 | PrashantMhrzn/Bulk-File-Renamer | /renamer.py | 657 | 3.546875 | 4 | from utils import Renamer
import argparse
parser = argparse.ArgumentParser(description='Renames every file inside the given folder.')
parser.add_argument('path', help='Absolute path of the folder')
parser.add_argument('-n','--naming_convention', metavar='', help='Not specifing will default to the name <file>')
args = ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.