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 |
|---|---|---|---|---|---|---|
c33ad4bbfce49a4272950774f47ff4f4a2092a51 | xieziwei99/py100days | /day16_20/algorithm/searching.py | 1,087 | 3.90625 | 4 | #!/usr/bin/env python
# -*- encoding: utf-8 -*-
"""
@Description: 顺序查找和二分查找
@author: xieziwei99
@Create Date: 2019/6/22
"""
# items: list,表示期望items的类型是list
# -> int,表示期望函数的返回值是int
# 这种写法,若不遵守也不会引起代码运行错误,最多由IDE给出警告
def seq_search(items: list, elem) -> int:
"""
顺序查找
:param items: 类型为list,要查找的列表
:param elem: 要查找的元素
... |
5524db8bcf497f2be9b6c2e324d59e2e2c772761 | dragonman117/USUACM2017CodeCompetition | /plants-50/_verify_solutions.py | 2,130 | 3.515625 | 4 | import _brute_force_solution
import _iterative_solution
import solution
# print("")
# print(_brute_force_solution.answer(1, 1, 10000, 10001, 0)) # brute force fails to exceed 10^4
# print("")
#
# raise TypeError
# print("")
# print(_iterative_solution.answer(1, 1, 10**8-2, 10**8-1)) # iterative solution fails to exc... |
497d18a55100351194107935791840ad8782dc99 | EoinMcKeever/Test | /QuickSort.py | 400 | 3.734375 | 4 | from collections import Counter
def isValid(s):
# Write your code here
d = Counter(s)
d = Counter(str(s))
print(d["a"])
print(d)
if len(d) == 1:
return "YES"
if len(d) > 2:
return "NO"
print(d)
if 1 in d.values() and (d[min(d.keys())]==1 or (max(d.keys()) - min(d.keys())==1)):
return "YES"
else:... |
7791023ad7a3561d91401b22faeff3fce3a1c7c8 | EoinMcKeever/Test | /doublyLinkedListImplemention.py | 1,028 | 4.4375 | 4 | class Node:
def __init__(self, data):
self.data = data
self.next = None
self.previous = None
class DoublyLinkedList:
def __init__(self):
self.head = None
self.tail = None
#insert at tail(end) of linked list
def insert(self, data):
new_node = Node(data)
if self.head is None:
self.head = new_node
... |
d33f4f821c7c1867031714bc92143db0af602a9d | maxfischer2781/pypelined | /pypelined/utilities/__init__.py | 524 | 4 | 4 | import ast
__all__ = ['safe_eval']
def safe_eval(literal):
"""
Evaluate a literal value or fall back to string
Safely performs the evaluation of a literal. If the literal is not valid,
it is assumed to be a regular string and returned unchanged.
:param literal: literal to evaluate, e.g. `"1.0"`... |
b5b575cae37c9f8e6d2b0d2b647fcdda73b1762d | brendencrogers/calcudoku | /calcudoku.py | 4,587 | 3.640625 | 4 | """Calcudoku Project 2
CPE 101
Spring 2020
Author: Brenden Rogers
"""
def main():
"""To solve Calcudoku puzzle"""
cage_num = get_num_cages()
cages = get_cage_info(cage_num)
grid = create_grid()
i = 0
j = 0
while i < 5:
grid[i][j] += 1
if validate_all(grid, cages) is True an... |
9c14a71ea0abbc35a831473e2f5dbaa9c93b3fc6 | elenghazaryan/All-in-group-tasks | /Exercises/Dictionary Exercise/dict.py | 3,147 | 3.828125 | 4 | #Question1
def convert_to_dict():
keys = ['Ten', 'Twenty', 'Thirty']
values = [10, 20, 30]
return_dict = dict(zip(keys, values))
print(return_dict)
#Question2
def marge_dicts():
dict1 = {'Ten': 10, 'Twenty': 20, 'Thirty': 30}
dict2 = {'Thirty': 30, 'Fourty': 40, 'Fifty': 50}
dict1.update(d... |
ccecccceecb2d02a3acf2fad8c529c801e1d93e4 | gonsoomoon/RNN | /sentimentalAnalysis/read_imdb_data.py | 2,418 | 4.03125 | 4 | """
Author: gonsoomoon
DAte: Sep 10, 2017
Ref: Nikhil Buduma (2017). Fundamentals of deep learning. Sebastopol, CA: O’Reilly Media
"""
from tflearn.data_utils import to_categorical, pad_sequences
from tflearn.datasets import imdb
import numpy as np
# IMDB Dataset loading
train, test, _ = imdb.load_data(path='data/imd... |
788c103477b61d3e98ac05237573be6752fe9051 | Dwensdc/Upeu_practice1_FDP | /secuenciales/ejercicio3CLSS.py | 590 | 3.8125 | 4 | def muestraMenorEdad():
#Definir Variables y otros
pnombre=""
pedad=0
#Datos de entrada
p1nombre=input("Ingrese Nombre 1ra Persona:")
p1edad=int(input("Ingrese edad 1ra Persona:"))
p2nombre=input("Ingrese Nombre 2da Persona:")
p2edad=int(input("Ingrese edad 2da Persona:"))
p3nombre=input("Ingrese Nomb... |
2d35be1297f4c2955e3e2a86496268f8c6149cca | admiralanker/Lcrawler | /part2/condition_s.py | 1,233 | 3.859375 | 4 | '''
条件控制
1、比较运算符 == > < >= <= !=
'''
i = "a"
j = "B"
if i < j:
print('a小')
else:
print('a大')
'''
ascii码表
'''
print(ord(i))
print(ord(j))
print(chr(99))
'''
成员运算符
in not in
'''
s = '123456'
if '1' in s:
print('1在s里')
if 'a' not in s:
print('a不在s')
'''
逻辑运算符
and or not
'''
pmj = ['萧峰','... |
38989090769b34dd15fafb97590a296cf9a26f8f | admiralanker/Lcrawler | /part2/tuple_s.py | 174 | 4 | 4 | '''
元组:在一个小括号内包裹着 ()
'''
t = (1, 2, 3, 0)
print(t)
print(type(t))
# 访问元组 []
print(t[0])
print(t[1:])
print(t[:2])
# 元组不能修改
|
78717e6e36c8eed535f324e50e917d30f097a2d3 | admiralanker/Lcrawler | /part1/1_data_type/date_type.py | 266 | 3.796875 | 4 |
#声明一个变量
first_number = 1
print(first_number)
print(type(first_number))
second_float_number = 1.2
print(second_float_number)
print(type(second_float_number))
#布尔型 True False
third_boolean = False
print(third_boolean)
print(type(third_boolean))
|
42fde517ef4ef77f0db7f7fd7d379d51e7c919a8 | Diakakodo/Tetris-1 | /Board.py | 5,046 | 3.5625 | 4 | from Pieces import T,O,I,J,L,Z,S
from random import choice
from math import factorial
PIECES_LIST = [T,O,I,J,L,Z,S]
LEVEL_UP_ROWS = 2
SCORE_BASE = 40
class Board( object ):
def __init__(self, x=10 , y=20, piecesList=PIECES_LIST):
#Size of Board in blocks
self.x = x
self.y = y
#List of Pieces for game... |
692a9761e57966a93a8333261b17402a1c061bad | trajeshmca21/rajesht | /assignent/assignment4/usecase1.py | 640 | 3.953125 | 4 |
from datetime import datetime
a=dict()
choice=0
while choice!=2:
print("""My To Do App
============
1. Add Task
2. View All Tasks
0. Exit
""" )
choice=int(input("enter your choice: "))
if choice==1:
k=input("enter data: ")... |
d795bad87b7b902d05ee026e5f280a131aa15a89 | trajeshmca21/rajesht | /assignent/assignment4/usecase2.py | 279 | 4.15625 | 4 | even = [ x for x in range(20) if x % 2 == 0]
odd= [ x for x in range(20) if x %2 != 0]
square=[x*x for x in range(20) ]
cube=[x*x*x for x in range(20)
print("print square of list",square)
print"odd numbers",(odd)
print("print even numbers",even)
print("print cube",cube) |
d274f95bf752c84423ecb5e0940d86462e81a99a | trajeshmca21/rajesht | /assignent/assignment7/usecase3.py | 766 | 3.625 | 4 | class Memory:
def __init__(self,internal, secondary, ram):
self.internal=internal
self.secondary=secondary
self.ram=ram
def getinfo(self):
print("INTERNAL :{} \n secondary :{} \n and ram :{}\n".format(self.internal,self.secondary,self.ram))
class Properti... |
f4a66803634b3d00e983d2cd09eac30ce156ebee | khaleel3020/snake_game | /scoreboard.py | 1,016 | 3.703125 | 4 | from turtle import Turtle
class Scoreboard(Turtle):
def __init__(self):
super().__init__()
self.score = 0
with open('data.txt') as file:
self.content = file.read()
self.high_score = int(self.content)
self.hideturtle()
self.color('white')
self.pe... |
2a0b02c7698b8acc68636a17ba9d9292b2fcea50 | Emma-sels/EE480Projects | /Cont_Sweeping.py | 1,408 | 3.59375 | 4 | import RPi.GPIO as GPIO #importing the RPi GPIO library
from time import sleep #function to add in delay later in code
GPIO.setmode(GPIO.BOARD) #physical pin numbers
GPIO.setup(18, GPIO.OUT, initial=GPIO.LOW) #pin 7 (GPIO4) as an output that starts off
GPIO.setup(11, GPIO.OUT, initial=GPIO.LOW) #pin 11 (GPIO17) as an ... |
2d22c83fb58d9ede67d8a15ef325354462a40cc9 | ChaymaeHarfoush/codeSignal | /areFollowingPatterns.py | 876 | 3.75 | 4 | def areFollowingPatterns(strings, patterns):
HT={}
for i in range(len(strings)):
if strings[i] not in HT:
if patterns[i] in HT.values():
return False
HT[strings[i]]=patterns[i]
else:
if HT[strings[i]]!= patterns[i]:
return False... |
96bf3f03e6773d6f16dcf6e910f557469f04ceed | ChaymaeHarfoush/codeSignal | /isListPalindrome.py | 940 | 4 | 4 | # Definition for singly-linked list:
# class ListNode(object):
# def __init__(self, x):
# self.value = x
# self.next = None
#
def isListPalindrome(l):
if l is None:
return []
fast=l
slow=l
while fast.next!=None:
#list have even number of elements
if fast.next.next ==No... |
118b1c6a84b1a28b10631001c3e5fc100aa3f7b3 | ChaymaeHarfoush/codeSignal | /rotate_image.py | 417 | 3.71875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Tue Jul 10 19:59:40 2018
@author: Chaymae
"""
from copy import deepcopy
def rotateImage(a):
rot=deepcopy(a)
for x in range(0,len(a)):
for y in range(len(a)-1,-1,-1):
rot[x][len(a)-1-y]=a[y][x]
return rot
a=[[1,2,3],
[4,5,6],
[7,8,9]]
print(... |
ba26792c347d926b82a64798f94f9fd8460b78c8 | andreysher/study | /pythonCourse/my_file.py | 930 | 3.5 | 4 | import os
import tempfile
class File:
def __init__(self, full_path):
self.full_path = full_path
self.name = os.path.split(full_path)[-1]
self.file = open(self.full_path, 'a+')
def write(self, s):
self.file.write(s)
def __add__(self, other):
if type(other) == F... |
83ae554dbbb28ae0415b176f013c2dff7da87e6e | AndreyNadolenko/AndreyNadolenko | /main.py | 407 | 4 | 4 | name = "Андрей"
age = 22
city = "Киев"
print("Привет! Меня зовут "+name+", мне "+ str(age)+" года, я живу в городе "+city+"!")
name2 = input("Как тебя зовут?")
city2 = input("С какого ты города?")
print("Окей, "+name2+", жди, я уже еду в "+city2+" ! ")
print("Нажмите Enter чтобы закончить!")
a = input() |
f04fdb0b6e5780368315d7885276a55621b7c92c | PanKou/RMHD-CHM-Lie-Analysis | /utils/DEint.py | 8,264 | 3.859375 | 4 | # I want to put the interpretation code I write in a separate file,
# so I can call them when I need to in a main analysis file
from sympy import *
def intlist(s):
""" Recieves a list written in a string format
and transforms it into a list object-
Args:
s (str): string version of a list... |
e20dbdf4fe19e1c530849af1ad7d02d795752ddf | AhmedKhaledAK/HTTP-proxy | /http_proxy.py | 17,795 | 3.671875 | 4 |
# Don't forget to change this file's name before submission.
import sys
import os
import enum
import socket
import re
import queue
import select
cache = {}
class HttpRequestInfo(object):
"""
Represents a HTTP request information
Since you'll need to standardize all requests you get
as specified by t... |
23c26650fe39769bd627cb5e31d09fafecc974c6 | gioguarnieri/siseqnaolineares | /newton.py | 243 | 3.5625 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import numpy as np
def func(x):
return np.cos(x)-x
def dfunc(x):
return (func(x+h)-func(x))/h
h=1e-3
tol=1e-10
x=1
ox=0
i=0
while((ox-x)**2>tol):
ox=x
x=x-func(x)/dfunc(x)
i=i+1
print x,i
|
0418327bb5259eb80ae28acb1db0c0ed73481a93 | rekhinnvs/learnPython | /HackerRank/codes/Halloween.py | 581 | 3.84375 | 4 | #Alex is attending a Halloween party with his girlfriend, Silvia. At the party, Silvia spots the corner of an infinite chocolate bar (two dimensional, infinitely long in width and length).
#If the chocolate can be served only as 1 x 1 sized pieces and Alex can cut the chocolate bar exactly k times, what is the maximum ... |
1da86b9c0e953787d0ae33850015e6f3aea85f7b | rekhinnvs/learnPython | /HackerRank/codes/Conditional.py | 435 | 4.40625 | 4 | # Given an integer, , perform the following conditional actions:
#
# If n is odd, print Weird
# If n is even and in the inclusive range of 2 to 5, print Not Weird
# If n is even and in the inclusive range of 6 to 20, print Weird
# If n is even and greater than 20, print Not Weird
N = int(raw_input().strip())
if N%2 !=... |
85cc01530e2662097e31358b2b951d1d1d1e5e05 | samsonq/Macroeconomic-Default-Analysis | /src/modeling/model.py | 3,682 | 3.5 | 4 | """
Build and train various types of classification models to predict default/loan status of
a borrower, given feature data about the loan.
Models:
- Neural Network Classifier
- Support Vector Machine (SVM)
- Decision Tree & Random Forest (ensemble)
- Logistic Regression
- K Nearest Neighbors
-... |
a9f4de4ffe2955ad42fc0e2a0e9ee478eee4f78d | DingJohn/Study | /study/stage002_study.py | 1,488 | 3.875 | 4 | #!/usr/bin/env python
# _*_ coding:utf-8 _*_
'''
转义符的使用
'''
# \n 表示换行
print("====>I'm \n python")
# \t 表示空格,空格的个数是缩进的空格数
print("====>I'm\tpython")
# \\ 表示\
print("====>this is \\ python")
# r的使用,表示输出字符串中的转义符就只是一个字符串的意思,不做转义的操作
print(r"====>this is \\ python")
# R的使用同r
print(R"====>this is \\ python")
# 使用三引号(‘’‘ ... |
8342761dcbff1392500ebf647ef6105e6abb617d | DingJohn/Study | /study/stage007_study.py | 816 | 4.03125 | 4 | #!/usr/bin/env python
# _*_ coding:utf-8 _*_
'''
dict
'''
print("=======================dict===============================")
d = {"jack": "beijing", "tony": "shanghai", "lisa": "wuhan"}
# 查询key中是否有一个名为lisa的
print("lisa" in d)
# 查询d中是否有一个key为jack的,如有则返回value,如没有则返回none
print(d.get("john"))
# 修改key为lisa的值
d["lisa... |
5eee1d429a523794ff8fa75598f606bce77bf907 | scheffeltravis/Python | /Algorithms/Search/binary_search.py | 359 | 4.03125 | 4 | """
binary_search.py
Recursively partitions the list until the key is found.
Time Complexity: O(log n)
"""
def search (seq, key):
lo = 0
hi = len(seq) - 1
while (hi >= lo):
mid = lo + (hi - lo) // 2
if (seq[mid] < key):
lo = mid + 1
elif (seq[mid] > key):
hi = mid - 1
... |
227a6a13d82d0ae4f93f74cf28e1dda85788d566 | scheffeltravis/Python | /Geometry/Geometry.py | 8,010 | 4.09375 | 4 | import math
class Point (object):
# constructor with default values
def __init__ (self, x = 0, y = 0):
self.x = x
self.y = y
# get distance to another Point object
def dist (self, other):
return math.hypot(self.x - other.x, self.y - other.y)
# create a string representation of a Point (x, y)
... |
8f5c216e452e901f53f3318905f01d3ef9717a81 | scheffeltravis/Python | /Algorithms/Search/rabinkarp_search.py | 492 | 3.765625 | 4 | """
rabinkarp_search.py
Search for a substring in a given string, by comparing hash values
of the strings.
Time Complexity: O(n * m)
Space Complexity: O(n)
"""
from hashlib import md5
def search(s, sub):
n, m = len(s), len(sub)
hsub_digest = md5(sub).digest()
offsets = []
if (m > n):
... |
5edf8cb2a9e0e25df4d2ce8e76c143b7b43e4f91 | scheffeltravis/Python | /Fractals/Tree.py | 761 | 4.25 | 4 | """
Tree.py
Simple fractal program which draws a tree based on bifurcation in terms
of 'branch' length.
"""
import turtle
# Draw a tree recursively
def drawTree (ttl, length):
if length > 5:
ttl.forward (length)
ttl.right (20)
drawTree (ttl, length - 15)
ttl.left (40)
drawTree (ttl,... |
b7c0c2b0a47198ae4b61873285bf1bca676e744c | ArunShishodia/Smaller-Programs | /Advanced_Python_Class/Exercisesheet 4/Exercise 10.3.py | 996 | 3.65625 | 4 | import matplotlib.pyplot as plt
import numpy as np
def derive(f, x):
eps = 10e-09
return (f(x + eps) - f(x - eps))/(2 * eps)
def newton_method(function, x0, n):
counter = 0
x_list = []
y_list = []
while counter < n:
x1 = x0
x0 = x0 - function(x0)/derive(function, x0)
... |
0ecb8e5879fdd21ca5af20f34a5727793f6d5ad3 | ArunShishodia/Smaller-Programs | /Algorithms/newton_method.py | 686 | 3.578125 | 4 | import numpy as np
# Newton method
def derive(f, x):
eps = 10e-09
return (f(x + eps) - f(x - eps))/(2 * eps)
def newton_method(function, x0, n):
global x_list
global y_list
counter = 0
x_list = []
y_list = []
while counter < n:
# in this case x1 would be x0 and vice versa
... |
1493d7fc40bd5cef0c9b907c89f4a6c54f60516f | ArunShishodia/Smaller-Programs | /Advanced_Python_Class/Exercisesheet 4/Exercise 10.2.py | 1,669 | 3.875 | 4 | # also possible as class
# x0 can be zero of the derivative and then can be dividing by zero
# am besten ableitung hardcoden falls möglich in Anwendungen, bzw. optimierte varianten verwenden
# Analytische Genauigkeit ist mathematische Genauigkeit
'''
class Derivative:
def __init__(self, function, epsilon=10e-09)... |
ab0678b6ebd0141bf5547a0fb6990c8924aefd4d | ArunShishodia/Smaller-Programs | /Advanced_Python_Class/Exercisesheet 4/Exercise 12.2.py | 2,074 | 3.875 | 4 | import numpy as np
import matplotlib.animation as animation
import matplotlib.pyplot as plt
from PIL import Image
"""Rules: 1. If a cell is ON and has fewer than two ON neighbors it turns OFF -> Underpopulation
2. If a cell is ON and has two or three neighbors that are ON, it remains ON -> Stasis
3... |
55204971cd8d55114d2ba1495d496b6575d23241 | SwarnaKen/UniPy | /Inheritence.py | 411 | 3.6875 | 4 | class Base:
name="Swarna" #properties
def baseMethod(self): #Methods
print("I am in Baseclass")
def getname(self):
return self.name
class Child(Base): #class
company="Kenric"
def childMethod(self):
print("I am in Childclass")
# def getcompany(self):
c=Child() #Object/ in... |
6eb48816205257b528b1aefd8f03fa8206716aa9 | sayee2288/python-mini-projects | /blackjack/src/Deck.py | 1,401 | 4.1875 | 4 | '''
The deck class simulates a deck of cards and
returns one card back to the player or the dealer randomly.
'''
import random
class Deck:
'''
The deck class creates the cards
and has functions to return a card or shuffle all cards
'''
def __init__(self):
print('Deck is ready for the game'... |
f23bbb9dd81fa18004a0ae67e526ded45076afef | abedigram/baqpy | /arith.py | 326 | 4 | 4 | import math
print(10 + 3)
print(10 - 3)
print(10 * 3)
print(10 / 3) #float res
print(10 // 3) #int res
print(10 % 3)
print(10 ** 3) # 1000
x = 10
x = x + 3
x //= 3
print(x)
# precedense
x = 10 ** 2 * (3 + 1)
print(x)
#functions
x = 2.9
print(round(x))
print(math.ceil(x))
print(math.floor(x))
x = -2
print(abs... |
559041645671da7b5636cf48b1c307325d326690 | abedigram/baqpy | /list.py | 558 | 3.96875 | 4 | names = ['john', 'bob', 'sarah', 'mary']
print(names)
print(names[0])
print(names[2])
print(names[1:3])
names[0] = 'jon'
print(names)
matrix = [
[1,2,3],
[5,6,7],
[8,9,0]
]
print(matrix[0][1])
for row in matrix:
for col in row:
print()# print(col)
list = [1,2,3,4,5,6]
list.append(7)
list... |
2362d7bc85e342d0e830467087a83fd8e77b768d | robert11arad/210CT-Coursework | /Lorry.py | 2,027 | 3.5625 | 4 | from copy import *
#Working data
maxkg=10
cargo={"material1":["Copper", 7, 65], "material2":["Plastic",15,50], "material3":["Gold",4,100]}
order=list(cargo)
#Arranges the materials from the most valuable to the cheapest.
def arange(arcubes):
arorder=list(arcubes)
valors=[]
for val in range(len(arorder)):
... |
676ce4adc986f7283afed9d8c4292950aacac29a | ba1dr/bowlingtest | /bowlingtest.py | 1,558 | 3.609375 | 4 | # -*- coding: utf-8 -*-
"""
Script file: bowlingtest
"""
__author__ = "Alexey Kolyanov"
__email__ = "alexey.kolyanov@gmail.com"
from collections import defaultdict
# input
SCORES = [10, 3, 7, 6, 1, 10, 10, 10, 2, 8, 9, 0, 7, 3, 10, 10, 10] # 193
def bowling10(scores):
"""
Calculate scores for the... |
ffe53c6d1faea576494109c6a2bad70d5041b43a | raisantos/weasel-program | /weasel.py | 1,404 | 3.734375 | 4 | import random
import string
padrao = "RAI SANTOS DA SOLEDADE"
string_aleatoria = ""
lista = []
pontuacao = []
probabilidade = 5
maior_pontuacao = 0
for i in range(len(padrao)):
string_aleatoria = string_aleatoria+random.choice(string.ascii_uppercase+' ')
for i in range(100):
lista.append(string... |
f110a9f2f8f7298cbbd2544e46555774149b7e2a | ookathuria/testing | /nonRepeatingChar.py | 770 | 3.65625 | 4 | from math import floor
class non_repeating_char:
def __init__(self):
self.nonRepeatingChar()
def nonRepeatingChar(self):
string = input("Enter the string to analyze for first non-repeating character : ")
i=0
j = 0
dict = {}
for i in range(len(... |
a163c85206c6985072d21ccdb96f551aacc9170b | thuylinh25/profile | /A Quick Recap #3 - Correlation and Regression Lines.py | 1,210 | 3.609375 | 4 | # https://www.hackerrank.com/challenges/correlation-and-regression-lines-8/problem
import math
physics_scores =[15,12,8,8,7,7,7,6,5,3]
history_scores = [10,25,17,11,13,17,20,13,9,15]
def covariance(a, b):
if len(a) != len(b):
return
a_mean = sum(a)/float(len(a))
b_mean = sum(b)/float(len... |
b980760469d8664e199b628ad3b180ec5a5ccc01 | ghfkddorl/mazerunner | /maz/s.py | 233 | 3.703125 | 4 |
def bfs(graph,root,search):
visited=[]
que=[root]
while que:
node=que.pop(0)
if node not in visited:
visited.extend(node)
que.extend(graph[node])
if node==search:
break
return visited
|
d7d1a16d7d91c9d730eb8374706705229cb8408a | lokymm/Proyectos-Python | /Clase24.py | 721 | 3.8125 | 4 | print("*********************************")
print("* While con la sentencia Breack *")
print("*********************************\n")
contador=0
while contador< 10:
contador += 1
if contador== 5:
break
print("Valor actual de la variable", contador)
print("Fin del programa. La sentencia Breack se h... |
9c507608c67defec5fa27a8146dc46e84cc3dadc | lokymm/Proyectos-Python | /Clase27_Funciones.py | 491 | 4.0625 | 4 | '''
Este código es para usar funciones en Python.
'''
def saludo(nombre):
print("Hola {}".format(nombre))
print("Bienvenidos amigos a esta prueba genial")
print("Probaremos funciones en Python\n")
saludo("Marcelo")
print("\n")
saludo("Pedro")
print("\n")
nombre = input("Ingresa tu nombre: ")
print("\n")... |
c6440e478cc7aa97fcc5cbe5b76d41ad31b54321 | lokymm/Proyectos-Python | /Clase30_Ciclo_FOR.py | 295 | 3.984375 | 4 | '''
Este código es para probar BUCLES en Python.
'''
for contador in range(5):
print (contador**2)
print("\nEl Bucle ha finalizado \n")
#Usando el Bucle FOR para recorrer Strings
frase = "Curso de Python"
for caracter in frase:
print(caracter)
print("\nEl Bucle ha finalizado \n") |
108e38e218f28312cc77a759e78ba781645b6af4 | lokymm/Proyectos-Python | /Clase28_Convertidor deTemperatura.py | 581 | 4 | 4 | '''
Este código es para usar funciones en Python.
'''
print("*" *31)
print("* Convertidor de Temperaturas *")
print("*" *31, "\n")
def convertirCelsius(temp, unidad):
if unidad == "K":
return temp/9.8112
elif unidad =="C":
return temp*9.8112
else:
print("Debe ingresar la uni... |
527dc79b303f4459dc5b18d440258d007666a812 | lokymm/Proyectos-Python | /Clase14.py | 599 | 4.03125 | 4 |
print("###################################################")
print("Comparador de Números")
print("################################################### \n")
#Operadores Relacionales
numero_1 = int(input("Ingresa el primer número a comparar: "))
numero_2 = int(input("\n Ingresa el segundo número a comparar: "))
if n... |
127075587fa48b93de07cbaf67368796440b50e5 | sqshine/python_demo | /b__slots__.py | 1,357 | 3.625 | 4 | import collections
import datetime
ImmutableThingTuple = collections.namedtuple("ImmutableThingTuple", "a b c d")
class MutableThing:
def __init__(self, a, b, c, d):
self.a = a
self.b = b
self.c = c
self.d = d
class ImmutableThing:
__slots__ = ['_a', 'b', 'c', 'd']
def ... |
e9fca85b94def08371832202e19427e1e52a2350 | emreozb/HackerRank_Exercises | /grading_students.py | 333 | 3.796875 | 4 | import math
grades = [84, 29, 57, 38]
round_grades = []
for grade in grades:
if grade < 38:
round_grades.append(grade)
elif grade >= 38:
if ((5*math.ceil(grade/5)) - grade) < 3:
round_grades.append((5*round(grade/5)))
else:
round_grades.append(grade)
print(round... |
773ceb1094f6f7506f552009e2e823c7ac29f306 | dwjkate/Python-Study | /Jump02-Q6.py | 206 | 4.03125 | 4 | #[1, 3, 5, 4, 2] 리스트를 [5, 4, 3, 2, 1]로 만들어 보자.
#※ 리스트의 내장 함수를 사용해 보자.
my_list = [1, 3, 5, 4, 2]
#뒤집기 함수 reverse
my_list.reverse()
print(my_list) |
0240991d2a500c398cfd17ea1ac3616d00dd09dd | Spandan-Madan/python-tutorial | /8_while_loops.py | 2,147 | 4.40625 | 4 | import random
# ** While Loops **
# What if you want your code to do something over and over again until some
# condition is met?
# For instance, maybe you're writing code for a timer
# and you want to keep checking how much time has passed until you have waited
# the correct amount of time.
# Then you should us... |
7f48e6553356d931f387808073f75aaaf8ca6786 | Spandan-Madan/python-tutorial | /15_imports.py | 5,800 | 4.625 | 5 | # ** Imports **
print("Imports:")
# So far, most of the code that we have written in Python has all been inside
# one file. But what if you have a big project and you want to split your code
# between files? Or what if you want to use a function that someone else wrote?
# This is where imports come in!
# Imports ... |
e6bed67b87876e59d12ad8a0e2776649b169f3bf | Spandan-Madan/python-tutorial | /5_booleans.py | 1,334 | 4.40625 | 4 | # ** Boolean Comparisons **
print("Examples of boolean comparisons")
# Python also supports logical operations on booleans. Logical operations take
# booleans as their operands and produce boolean outputs. Keep reading to learn
# what boolean operations Python supports.
# And
# The statement `a and b` evaluates t... |
3173fc7178ebdff2bd848e1b6d002faea0c4701a | rafallewanczyk/Komiwojazer | /test/graph_manager_test.py | 1,397 | 3.5625 | 4 | import unittest
from math import sqrt
from data.graph_manager import GraphManager
class GraphManagerTest(unittest.TestCase):
graph_manager = GraphManager()
def test_read_from_file(self):
graph = self.graph_manager.read_from_file("test/test1_nodes.txt", "test/test1_links.txt")
self.assertEqua... |
c2cbac4cc29f69f468d2755159b7cc7ae5a7aea1 | code-drops/UpGrad | /python for data science/2. Data cleaning/bank_data_cleaning.py | 1,816 | 3.84375 | 4 | import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import warnings
# to remove the warnings
warnings.filterwarnings("ignore")
# read csv file and skipping first two rows
bank = pd.read_csv("bank marketing.csv",skiprows=2,index_col="customerid")
################## Fixing the rows and co... |
d60132cb748db290fa88b3f31708ae646aa47131 | code-drops/UpGrad | /python for data science/libraries/panda/indexing and slicing.py | 931 | 3.8125 | 4 | import pandas as pd
sales = pd.read_excel("C:/Users/dell/Desktop/sales.xlsx",index_col=1)
print(sales)
# fetching specific columns
# if used one bracket , it will return series and if used double brackets, it will return data frame
print(sales["Profit"]) # return series
print(sales[["Profit",... |
a781c268a1c97cad611b138644658d5858f626a6 | jasonwee/asus-rt-n14uhp-mrtg | /src/lesson_mathematics/fractions_create_strings.py | 114 | 3.59375 | 4 | import fractions
for s in ['1/2', '2/4', '3/6']:
f = fractions.Fraction(s)
print('{} = {}'.format(s, f))
|
b44da3842b1060ede797a5d8c000aa6c829bd624 | jasonwee/asus-rt-n14uhp-mrtg | /src/lesson_mathematics/math_radians.py | 469 | 3.59375 | 4 | import math
print('{:^7} {:^7} {:^7}'.format(
'Degrees', 'Radians', 'Expected'))
print('{:-^7} {:-^7} {:-^7}'.format(
'', '', ''))
INPUTS = [
(0, 0),
(30, math.pi / 6),
(45, math.pi / 4),
(60, math.pi / 3),
(90, math.pi / 2),
(180, math.pi),
(270, 3 / 2.0 * math.pi),
(360, 2 * ... |
71e439cc92a4816b6588d761a0e0e82388b80fd0 | jasonwee/asus-rt-n14uhp-mrtg | /src/lesson_language_tools/abc_abc_base.py | 700 | 3.546875 | 4 | import abc
class PluginBase(abc.ABC):
@abc.abstractmethod
def load(self, input):
"""Retrieve data from the input source
and return an object.
"""
@abc.abstractmethod
def save(self, output, data):
"""Save the data object to the output."""
class SubclassImplementation... |
b6965d0d5ebe028780d4ba63d10d1c159fab97c7 | jasonwee/asus-rt-n14uhp-mrtg | /src/lesson_text/re_groups_individual.py | 407 | 4.1875 | 4 | import re
text = 'This is some text -- with punctuation.'
print('Input text :', text)
# word starting with 't' then another word
regex = re.compile(r'(\bt\w+)\W+(\w+)')
print('Pattern :', regex.pattern)
match = regex.search(text)
print('Entire match :', match.group(0))
print('Word ... |
f50b28836bc6d28896fac9b3d68a089c06c6227a | jasonwee/asus-rt-n14uhp-mrtg | /src/lesson_text/re_flags_multiline.py | 454 | 3.796875 | 4 | import re
text = 'This is some text -- with punctuation.\nA second line.'
pattern = r'(^\w+)|(\w+\S*$)'
single_line = re.compile(pattern)
multiline = re.compile(pattern, re.MULTILINE)
print('Text:\n {!r}'.format(text))
print('Pattern:\n {}'.format(pattern))
print('Single Line :')
for match in single_line.findall(te... |
1fb6060feb520deb27b0cabe2b7decae42fd684a | jasonwee/asus-rt-n14uhp-mrtg | /src/lesson_concurrency_with_processes_threads_and_coroutines/asyncio_queue.py | 1,676 | 3.53125 | 4 | import asyncio
async def consumer(n, q):
print('consumer {}: starting'.format(n))
while True:
print('consumer {}: waiting for item'.format(n))
item = await q.get()
print('consumer {}: has item {}'.format(n, item))
if item is None:
# None is the signal to stop.
... |
7580f2081d9e148dd08f67765dd78fcf7a8d24d8 | jasonwee/asus-rt-n14uhp-mrtg | /src/lesson_algorithms/itertools_map.py | 375 | 3.9375 | 4 | def times_two(x):
return 2 * x
def multiply(x, y):
return (x, y, x * y)
print('Doubles:')
for i in map(times_two, range(5)):
print(i)
print('\nMultiples:')
r1 = range(5)
r2 = range(5, 10)
for i in map(multiply, r1, r2):
print('{:d} * {:d} = {:d}'.format(*i))
print('\nStopping:')
r1 = range(5)
r2 =... |
a37f8b2477765651bee8c00f11ef24c273dcb13f | jasonwee/asus-rt-n14uhp-mrtg | /src/lesson_file_system/mmap_write_copy.py | 733 | 3.609375 | 4 | import mmap
import shutil
# Copy the example file
shutil.copyfile('lorem.txt', 'lorem_copy.txt')
word = b'consectetuer'
reversed = word[::-1]
with open('lorem_copy.txt', 'r+') as f:
with mmap.mmap(f.fileno(), 0,
access=mmap.ACCESS_COPY) as m:
print('Memory Before:\n{}'.format(
... |
35fcadb42a8c0eee775fa78d5a6945e9f5495dce | jasonwee/asus-rt-n14uhp-mrtg | /src/lesson_algorithms/itertools_islice.py | 316 | 3.59375 | 4 | from itertools import *
print('Stop at 5:')
for i in islice(range(100), 5):
print(i, end=' ')
print('\n')
print('Start at 5, Stop at 10:')
for i in islice(range(100), 5, 10):
print(i, end=' ')
print('\n')
print('By tens to 100:')
for i in islice(range(100), 0, 100, 10):
print(i, end=' ')
print('\n')
|
00225e6b7cfd0f985fd3ef9260384f07dc48edb8 | jasonwee/asus-rt-n14uhp-mrtg | /src/lesson_algorithms/itertools_accumulate_custom.py | 115 | 3.75 | 4 | from itertools import *
def f(a, b):
print(a, b)
return b + a + b
print(list(accumulate('abcde', f)))
|
7e11da94080f04d65ecc166fed6d2425cc9d0a02 | jasonwee/asus-rt-n14uhp-mrtg | /src/lesson_dates_and_times/datetime_comparing.py | 346 | 3.625 | 4 | import datetime
import time
print('Times:')
t1 = datetime.time(12, 55, 0)
print(' t1:', t1)
t2 = datetime.time(13, 5, 0)
print(' t2:', t2)
print(' t1 < t2:', t1 < t2)
print()
print('Dates:')
d1 = datetime.date.today()
print(' d1:', d1)
d2 = datetime.date.today() + datetime.timedelta(days=1)
print(' d2:', d2)
pri... |
76479df8180f2cea7fce03cae5840bb4a8960870 | jasonwee/asus-rt-n14uhp-mrtg | /src/lesson_application_building_blocks/shlex_table.py | 211 | 3.953125 | 4 | import shlex
text = """|Col 1||Col 2||Col 3|"""
print('ORIGINAL: {!r}'.format(text))
print()
lexer = shlex.shlex(text)
lexer.quotes = '|'
print('TOKENS:')
for token in lexer:
print('{!r}'.format(token))
|
712e91098295dc9206033f05d4235352d1cdedeb | jasonwee/asus-rt-n14uhp-mrtg | /src/lesson_algorithms/functools_wraps.py | 1,146 | 3.59375 | 4 | import functools
def show_details(name, f):
"Show details of a callable object."
print('{}:'.format(name))
print(' object:', f)
print(' __name__:', end=' ')
try:
print(f.__name__)
except AttributeError:
print('(no __name__)')
print(' __doc__', repr(f.__doc__))
print(... |
06287580e8987d2b0e29efd45e4052d0f1fc2c38 | jasonwee/asus-rt-n14uhp-mrtg | /src/lesson_dates_and_times/datetime_date_math.py | 374 | 3.859375 | 4 | import datetime
today = datetime.date.today()
print('Today :', today)
one_day = datetime.timedelta(days=1)
print('One day :', one_day)
yesterday = today - one_day
print('Yesterday:', yesterday)
tomorrow = today + one_day
print('Tomorrow :', tomorrow)
print()
print('tomorrow - yesterday:', tomorrow - yesterday)... |
05420354d1b028993425c79b9e72f6954a13b0d0 | jasonwee/asus-rt-n14uhp-mrtg | /src/lesson_text/re_groups_named.py | 440 | 3.84375 | 4 | import re
text = 'This is some text -- with punctuation.'
print(text)
print()
patterns = [
r'^(?P<first_word>\w+)',
r'(?P<last_word>\w+)\S*$',
r'(?P<t_word>\bt\w+)\W+(?P<other_word>\w+)',
r'(?P<ends_with_t>\w+t)\b',
]
for pattern in patterns:
regex = re.compile(pattern)
match = regex.search(... |
278a0ecaac037eb74a20f304ed4a001c632e1bfa | KevinLaam/EDD_1S2019_P1_201403888 | /ListaCircular.py | 1,345 | 3.78125 | 4 | class Nodo():
def __init__(self,usuario):
self.usuario = usuario
self.siguiente = None
self.anterior = None
class ListaCircular():
def __init__(self):
self.primero = None
self.ultimo = None
def estaVacia(self):
return True if self.primero == None else Fa... |
7c4e6f138c3c515731e9fb3c0f0ab10ba26149b9 | JuanL-Code/python_4 | /high_order_functions.py | 380 | 3.75 | 4 | #recibe como parametro otra funcion
#Filter
#my_list = [1,4,5,6,9,13,19,21]
#odd = list(filter ( lambda x: x%2 !=0, my_list))
#print (odd)
#Map
#my_list = [1,4,5,6,9,13,19,21]
#squares = list(map ( lambda x: x**2, my_list))
#print (squares)
#Reduce
from functools import reduce
my_list = [2,2,2,2,2]
all_multipli... |
ffcf5ca4edbf91a2f446dbb545ebf515367fef00 | lawrence615/sockets | /sockets/database.py | 657 | 3.5625 | 4 | import psycopg2
import sys
def main():
#get a connection, if a connection cannot be made, an exception is thrown
global conn
conn = psycopg2.connect(database="chatapp_db", user="postgres", password="db2013.", host="localhost");
#conn.cursor will return a cursor object, you can use this cursor to ... |
2064cf30c73a0ff6292a3a29b633a5eb2347c79c | Nurzatnur/rabota2 | /usloviya/problem3.py | 327 | 3.890625 | 4 | a=79
if a>0 and a<21:
print ("Число ", a, "находится в разрешенном диапозоне")
elif a>79 and a<100:
print ("Число ", a, "находится в разрешенном диапозоне")
else:
print ("Число ", a, "находится в запрещенном диапозоне") |
507b7099be4a01b04c9e35023f4e0dfeededf227 | Nurzatnur/rabota2 | /Nedelya3/fibonachi.py | 208 | 3.796875 | 4 |
def fibonachi():
i = 0
a = 1
b = 1
fib = [a, b]
while i < 8:
c = a + b
a = b
b = c
fib.append(c)
i += 1
print(fib)
fibonachi() |
981d1284277cf464f95507d4edb0915a225e7031 | MuthuSelvaraj/python | /Assignment_8.py | 218 | 3.703125 | 4 | tup1=(10,20,30,40,50,60,70,80,90,100)
print "The tuple1 is",tup1
print "Slicing of tuple11 is ",tup1[1:5]
print "repetition in tuple1 1 is ",tup1*2
tup2=('xxx','yyy','zzz')
print "concat of two tuple is",tup1+tup2 |
58b9db4ecfa71d787b4c20bb61560739124c57fd | MuthuSelvaraj/python | /Assignment_11.py | 449 | 3.78125 | 4 | a = input("enter num1")
print "\n"
b =input("enter num2")
print "\n"
c = input("enter num1")
print "\n"
And = a & b;
print "and operation ", And
Or = a | b;
print "or operation ", Or
Xor = a ^ b;
print "xor operation ", Xor
comp = ~a;
print "complement operation ", comp
left_shift=... |
2473aca3d8dde8d10e1350ffc8a09f7a11d11d6b | MuthuSelvaraj/python | /Assignment_6.py | 319 | 3.875 | 4 | str1=raw_input("enter the string")
str2=raw_input("enter the string")
print "\n"
print "print each character seperately"
for i in range(len(str1)):
print str1[i]
str3=str1[1:4]
print "The substring is ",str3
print "100 times of the string is",str3*100
print "concat of ",str1,str2, "using + is",str1+str2 |
45bec49176bcc4a960243c0fc4eea94987cb6143 | bibliofilica/Adivina | /adivina2.py | 959 | 4.03125 | 4 | import random
import math
intentos = 0
print ('Dime un numero alto')
top = (input())
max=int(top)
numero = random.randint (1,max)
iteraciones = int(math.log2(max))+1
chances=str(iteraciones)
print ('Estoy pensando un numero entre 1 y ' + top +' tienes ' + chances + ' intentos' )
while intentos < it... |
f5991410bc8125a831d1defe4ee7207a10a2e8cd | SanjanaSrabanti16/urban-chronicles | /preprocessing/Model/geometryds.py | 3,237 | 3.734375 | 4 | import json
class GeometryDS:
def __init__(self, deli = ";"):
self.__geometriesDS = {}
self.__uniqueID = 0
self.__delimiter = deli
def __getId(self):
result = self.__uniqueID
self.__uniqueID += 1
return result
def getCurrentId(self):
... |
f41164a1ce6dde0955e8219509eff34330e59871 | SanjanaSrabanti16/urban-chronicles | /preprocessing/Model/categoricalSummary.py | 1,808 | 3.859375 | 4 | class CategoricalSummary:
SUM = 1
APPEND = 2
def __init__(self, initClass):
'''
this method initialize Categorical Summary object
@param initClass initialization Class for "Folha"
'''
self.__initializationType = initClass if initClass != "int" else int
... |
30820a9187bd571e98f3eab47a7d22b59685b0c5 | fcornejv/retos | /BackEnd-Retos/Semana01/reto1.py | 602 | 3.765625 | 4 | #Reto 1: Desarrollar un programa de bienvenida
# 1. Ingresar un nombre y su edad.
# 2. Si es menor de edad que indique que dependiendo de la hora (si es mas de las 6pm) debe ir a dormir y si no hacer la tarea.
# 3. Si es mayor de edad que indique que no esta obligado a hacer nada.
import datetime
name = input("Ingres... |
a564175584e9e26ead1f13e23e799924c14a133e | themayurkumbhar/wemake-python-styleguide | /wemake_python_styleguide/logic/tokens.py | 1,380 | 3.640625 | 4 | # -*- coding: utf-8 -*-
import tokenize
from typing import Container, Iterable, Tuple
def split_prefixes(token: tokenize.TokenInfo) -> Tuple[str, str]:
"""
Splits string token by prefixes and the quoted content.
Returns the tuple of modifiers and untouched string contents.
>>> import tokenize
>... |
8025c47447a18c0f93b4c59c6c1191c6b0c6454a | shail0804/Shail-Project | /word_series.py | 2,137 | 4.125 | 4 | def Character_to_number():
""" This function converts a given (User Defined) Character to Number\
as per the given Pattern (2*(Previous Character) + counter) """
nb = input('please enter the character: ')
nb = nb.upper()
count = 1
sum = 0
for s in range(65,ord(nb)+1):
sum = sum*2... |
e8596535535979655079184dbf2d61899b8610b3 | diptaraj23/TextStrength | /TextStrength.py | 324 | 4.25 | 4 | #Calculating strength of a text by summing all the ASCII values of its characters
def strength (text):
List=[char for char in text] # storing each character in a list
sum=0
for x in List:
sum=sum+ord(x) #Extracting ASCII values using ord() function and then adding it in a loop
return... |
1775f4ecf0c6270b6209dd68358899fa92c8387c | jasonchuang/python_coding | /27_remove_element.py | 897 | 4.40625 | 4 | '''
Example 1:
Given nums = [3,2,2,3], val = 3,
Your function should return length = 2, with the first two elements of nums being 2.
It doesn't matter what you leave beyond the returned length.
Example 2:
Given nums = [0,1,2,2,3,0,4,2], val = 2,
Your function should return length = 5, with the first five elements of n... |
7979c9109a2dd210b7838f3080c14628e4ced7f9 | pyskonus/AppleGame | /A_backend.py | 3,354 | 3.9375 | 4 | import pygame
import A_frontend
mode = False
current_target = 0
def ulam_numbers(elements):
"""
(int) -> list
Precondition: elements > 2
This function returns a list of ulam numbers of given length.
>>> ulam_numbers(5)
[1, 2, 3, 4, 6]
>>> ulam_numbers(8)
[1, 2, 3, 4, 6, 8, 11, 13]
... |
5b7878b6bed6c9ae6ff4292da3cb0b98ae90c1e0 | kimdogyu1/practice-algorithm | /hashtable.py | 608 | 3.609375 | 4 | tablesize = 11
def hashcode(arr):
cell = [0 for i in range(tablesize)]
i = 0
while i < len(arr):
k = arr[i] % 11
if cell[k] is not 0:
while cell[k] is not 0:
k = (k + 1) % tablesize
cell[k] = arr[i]
else:
cell[k] = ... |
1f4a2131d181fdaca3e5b3872e2b4017197ba532 | alanamckenzie/advent-of-code | /advent2017/code/dec03.py | 5,060 | 4.25 | 4 | """
--- Day 3: Spiral Memory ---
You come across an experimental new kind of memory stored on an infinite two-dimensional grid.
Each square on the grid is allocated in a spiral pattern starting at a location marked 1
and then counting up while spiraling outward. For example, the first few squares are allocated like t... |
a606564149222554890365957c5e827a17f16f64 | alanamckenzie/advent-of-code | /advent2017/code/dec05.py | 3,964 | 4.375 | 4 | """
--- Day 5: A Maze of Twisty Trampolines, All Alike ---
An urgent interrupt arrives from the CPU: it's trapped in a maze of jump instructions,
and it would like assistance from any programs with spare cycles to help find the exit.
The message includes a list of the offsets for each jump. Jumps are relative: -1 mov... |
ce6f6114512ae2682c8902999118c08474da92fd | alanamckenzie/advent-of-code | /advent2017/code/utils.py | 403 | 4.15625 | 4 | def read_file(filename, line_delimiter='\n'):
"""Read the contents of a file
:param str filename: full path to the text file to open
:param line_delimiter: line delimiter used in the file
:return: contents of the file, with one list item per line
:rtype: list
"""
with open(filename, 'r... |
36ac8905679118a796c0ea1e073b8f4c035f3246 | campbellerickson/CollatzConjecture | /Collatz.py | 540 | 4.25 | 4 | print "Type '123' to start the program::",
check = input()
if check == 123:
print "To what number would you like to prove the Collatz Conejecture?::"
limit = input()
int(limit)
for x in xrange(1,limit+1):
num=x
original=x
iterations=0
while num > 1:
if (num % 2 == 0):
num = num/2
iteration... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.