blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
3d5bc477a6aff54d869c49970d3b1d27f99de6e3 | alondavid/Self.Py | /ex612.py | 395 | 3.8125 | 4 | #ex 6.1.2
def shift_left(my_list):
'''
The function recieve a list and return a new list shifted 1
position to the left
:param my_list: original list
:type my_list: list
:return: a new list, shifted to the left
:rtype: a list
'''
if len(my_list) > 1:
... |
1804df7397cd3856cc5dc44bda7b490ac9f52088 | hi-ing2/python_base_review | /class/class_basic.py | 1,148 | 3.765625 | 4 | class Person:
name = "후아유"
def __init__(self, name, age): #초기화(initialize) 메소드 : 어떤 클래스의 객체가 만들어질 때 자동으로 호출되어서 그 객체가 갖게 될 여러 가지 성질을 정해주는 일
self.name= name
self.age = age
def say_hello(self, to_name):
# print("안녕 ! "+ to_name + "나는 " + Person.name)
print("안녕 ! "+ to_name + "... |
a1887522ae4d57c3fa24751051637a6cfc07502e | vrrohan/Python100DaysOfCode | /Day6-PythonLists/Py3ListSlicing.py | 1,316 | 4.8125 | 5 | #You can also slice a list i.e. create a sub-list using [a:b]
list_of_city = ['Noida', 'Delhi', 'Bangalore', 'Lucknow', 'Mumbai', 'Gurgaon']
#listName[a:b] means - slice list from index a till index (b-1)
#listName[:] means - slice list from start to end
#listName[a:] means - slice list from a till end of list
#listNa... |
6c587359c88cb5f87f7cc2daba5d121b911e992e | prajwalit/lpthw | /ex24.py | 689 | 3.609375 | 4 | """ Exercise 24 """
print 'I\'m prajwalit \\ I know \n New lines \n\t and Tabs'
poem = """
\tTing ting ting
ting tang ting
tang ting tang \n tang tang ting
\n\t\ttang tang tang
"""
print "----------"
print poem
print "----------"
five = 10 - 2 + 3 - 6
print "This should be five: %d" % five
def formula (started):
... |
17bca88c7dd405ddcc96df4424cb20c507983128 | castrotec/greencoretraining | /semana3/hileras.py | 487 | 3.984375 | 4 | #Tema hileras
message = input("Digite lo que quiera: ")
print (message)
# len() -> Encontrar la cantidad de caracteres que tiene una hilera
print(len(message))
print(message[0])
print(message[len(message)-1])
# Concatenacion de hileras simple
hilera = "Hilera initial "
print(hilera + " y otra hilera")
print(hilera... |
55694a534e79bce1ae7d17ce487b6e287835a219 | tecnobeto/lcs-algorithm | /codigo/code.py | 1,136 | 3.5 | 4 | import time
start = time.time()
def lcs(a, b):
# Valores de uma coluna
tamLinha = len(a)
tamColuna = len(b)
# inicializa o matriz com zeros
matriz = [ [0 for j in range(tamColuna + 1)] for i in range(tamLinha + 1)]
# Começa o laço dentro das linhas
for i in range(0, tamLinha):
# Começa os lados pegando t... |
b27758bc5e945af9fa69134ce86a1fa92e29ea8d | shady1924/chap1 | /Assignments2/ch10_9_mean_stdev.py | 998 | 3.75 | 4 | '''
Sharad: calculate mean and stdwv
'''
printflag=False
def mean(x):
sm=sum(x)
cnt=len(x)
if cnt > 0 :
printflag and print(sm,cnt)
return sm/cnt
else:
return 0
def stddev(meanval, lst):
cnt=len(lst)
sm=0
for i in range(0,len(lst)):
sm = sm+(lst[i]-meanval... |
40fdfafe6742c4ff3089d16828e9f8f4141882e2 | atzengin/spfirst | /fseriesdemo/halfwave.py | 468 | 3.84375 | 4 | #!/bin/usr/env python3
import numpy as np
def halfwave(t, T, signal):
""" HALFWAVE creates a half-wave rectified sine/cosine wave. """
# 1 == sine & 2 == cosine
if(signal == 1):
yy = np.sin(2*np.pi/T*t)
elif(signal == 2):
yy = np.cos(2*np.pi/T*t)
else:
print('Unknown sig... |
f81af5ef347789838f31b538e24bc347293504b8 | kkrugler/codecademy-validator | /intro_to_cs/section8/section8_exercise2.py | 1,997 | 4.0625 | 4 | # Each of the following four statements uses the and operator to
# assign the value of a Boolean variable, by combining the
# results from two arithmetic sub-expressions.
and_result_1 = ((3 > 4) and (1 <= 2))
and_result_2 = ((5 > 4) and (1 <= 2))
and_result_3 = ((5 > 4) and (1 == 0))
and_result_4 = ((3 > 4) and (1 != 1... |
71633753929fef8ce1928d2512c63ec51cf59f37 | zoomie/algorithms_practise | /python/binary_search_tree.py | 715 | 3.75 | 4 |
class Node:
def __init__(self, key, value):
self.key = key
self.value = value
self.left = None
self.right = None
class BST:
def __init__(self):
self.start_node = Node('start', 'value')
def put(self, key, value):
self.put_in_space(self.start_node, key, valu... |
708cb237d5bbb7cee9661c551723a40a64d79cd5 | slickFix/Python_algos | /DS_ALGO/BinaryHeap_heapq.py | 1,541 | 3.71875 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Feb 26 19:39:48 2019
@author: siddharth
"""
from heapq import heappush,heappop,heapify
class MinHeap:
def __init__(self):
self.heap = []
def insertKey(self,val):
heappush(self.heap,val)
def parent(se... |
eda8cd444fbbdb5f52b87e4cfa65c010b5174212 | DevDragonLi/Python | /file_handle.py | 471 | 3.84375 | 4 | # -*- coding: utf-8 -*-# \n 换行
lengTextString = 'this is text string,\n,DragonLi'
print lengTextString
# write a string file
file_test = open('stringFile.txt','w') # w ->write , r -> read , a -> append
file_test.write(lengTextString) # Desktop will create a file stringFile.txt
file_test.close()
# read a pat... |
d8bcc6885e10c5a411b065c9be26e89cb8911bde | Brian-school/LCA-CSU33012- | /maintest.py | 1,507 | 3.640625 | 4 | import unittest
import main
class LCAtest(unittest.TestCase):
def test_NodeConstructor(self):
root = main.Node(20)
def test_BSTCreation(self):
root = main.Node(20)
root.left = main.Node(8)
root.right = main.Node(22)
root.left.left = main.Node(4)
root.left.right... |
5bdd298f7a6dfaa7153895e79d59a3ac7280f417 | wxke/LeetCode-python | /203 移除链表元素.py | 673 | 3.65625 | 4 | 移除链表元素
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def removeElements(self, head, val):
"""
:type head: ListNode
:type val: int
:rtype: ListNode
... |
86cfd63f06e8f058d8221a77b1cb8bbb40f54c31 | BaiLiping/BLP | /DRL/Code/PyTorch/Learning_PyTorch/4.py | 2,260 | 4 | 4 | '''
under the hood, each primitive autograd operator is really two functions that operator on tensors, the forward function computes output tensor from input tensor, the backward function receive the gradient of the output tensor with resepect to some scalar value and compute the gradient of the input tensor with respe... |
2eef74821019cfdb049dbd55564e707a29e863bd | python-practice-b02-927/kuleshov | /lab1/task_30.py | 729 | 3.5625 | 4 | #!/usr/bin/python3
from pyrob.api import *
def square(f):
move_right()
for i in range(f-2):
fill_cell()
move_right()
move_down()
for i in range(f-2):
fill_cell()
move_down()
move_left()
for i in range(f-2):
fill_cell()
move_left()
move_up()
... |
51675a76a4c95835562b7e7365aa1ecbd931ad68 | moraispgsi/pin-bootstrap | /pintools/source/tools/Utils/compare.py | 2,678 | 3.671875 | 4 | #
# This script compares a multi-line input file with a multi-line comparison file, where
# each line in the comparison file is a Python regular expression (re). The input file
# matches if there is some sequence of lines that match (in order) the patterns from the
# comparison file. The input file may have additiona... |
20ca1603680d043cc22f7269dcfb0dfcc35864cf | pawelpe90/self-taught-programmer | /rozdzial_04/python_lst102.py | 412 | 3.765625 | 4 |
n = input("wpisz liczbę: ")
n = int(n)
if n % 2 == 0:
print("liczba jest parzysta.")
else:
print("liczba jest nieparzysta.")
n = input("wpisz liczbę: ")
n = int(n)
if n % 2 == 0:
print("liczba jest parzysta.")
else:
print("liczba jest nieparzysta.")
n = input("wpisz liczbę: ")
n = int(n)
if n % ... |
41cc3e977e67c3db8726b3af815d77f26fe9579f | APM246/Atomic-Chess | /app/lessons.py | 2,527 | 3.671875 | 4 | """ Module that creates all the lessons instead of storing the static data in the database """
class Lesson:
def __init__(self, lesson_id, name, description, template, max_progression):
self.id = lesson_id
self.name = name
self.description = description
# Path to the template filena... |
cd3d3c955367b565074ba96c8d7fd11e6500278a | cmdtvt/R421-python-course | /Chapter7/task7-2.py | 2,982 | 4.21875 | 4 | '''
The second exercise in this chapter continues with random selection. In this exercise the objective is to develop a game called nuke-foot-cockroach, which is pretty similar to the more popular variant, paper-rock-scissors. The rules are simple: both players select either nuke, foot or cockroach, and the winner is d... |
576390df630a98831b91367d7d98e45f39000fe5 | devjayantmalik/PythonTutorials | /src/tutorial_13.py | 7,069 | 4.4375 | 4 | # ==================================================
# ==================================================
# Iterabale, Iterator, List Comprehensions,
# Generator Functions, Generator Expressions
# ==================================================
# ==================================================
# Difference... |
2bb1c79f41ddf229126fd7d98f7e0282e97737c9 | gyoscha/PythonPY100 | /Занятие2/Лабораторные_задания/task1_2/main.py | 204 | 3.8125 | 4 | a = int(input('Введите число А: '))
b = int(input('Введите числа В: '))
cond = a % 2 == 1 and b % 2 == 1
if cond:
print('Нечетные')
else:
print('Четные')
|
be425989396f58255d81b81089bb77d468b01a5f | minhaz1217/python-workshop-preparation | /07. B. Class members.py | 1,519 | 4.09375 | 4 | #Class members
class Person:
name = "N/A"
age = 0
def details(self):
print("My name is ", self.name, " and my age is", self.age)
obj1 = Person()
obj1.details()
obj1.name = "Zibraj"
obj1.age = 19
obj1.details()
class Person:
def eating(self):
print("I'm eating")
def sleeping(sel... |
78c5491a50056b3d20e5ca2474dab9847b151fa6 | dario-wat/theseus-maze | /src/linear.py | 8,245 | 3.90625 | 4 | import math
from abc import ABCMeta, abstractmethod
def _distance((x1, y1), (x2, y2)):
"""Racuna udaljenost 2 tocke u ravnini."""
return math.sqrt((x2-x1)**2 + (y2-y1)**2)
class AbstractPolygon:
"""Apstraktan razred za n-terokute."""
__metaclass__ = ABCMeta
@abstractmethod
def getContours(self):
pass
... |
e61a659ee044f0682677166bdb76ea72c39ff432 | Harshit975shukla/test | /palindrom.py | 462 | 3.8125 | 4 | def palindrom(st, f):
if len(st) == 1 or len(st) == 0:
return f
elif st[0] != st[-1]:
f = -1
return palindrom(st[1:-1], f)
else:
f = 1
return palindrom(st[1:-1], f)
def main():
t = int(input())
for i in range(t):
s = input()
f = 0
x =... |
03029f7fca2d49ae3e54c8edf4a7fd5785e2da41 | mcwanggithub/UW-PYTHON310 | /1_ClassNotes/Class2/string_match.py | 203 | 3.5625 | 4 | def string_match(a, b):
count = 0
for i in range(len(a)):
print(i)
print(a[i:i+2])
print(b[i:i+2])
print(' ')
if a[i:i+2] == b[i:i+2]:
count +=1
return count |
afc00916289279efcdda97c5a69e1eb036d78d01 | GISer18/Convolutional-Block-Attention-Module-CBAM | /CBAM.py | 2,240 | 3.609375 | 4 | """
Implementation Convolutional Block Attention Module (CBAM) with Residual block (Tensorflow2 & Keras)
This snippet code is a part of the Super AI Engineer article
Author: Suesarn Wilainuch (22p21c0153)
Home: EXP
🔴🟢🔵 let's get started! 🔴🟢🔵
"""
import tensorflow as tf
from tensorflow.keras.layers import Conv... |
c92441ba341eb2263237c552c276be3a560e23ae | aambrioso1/NLP | /Letter_Count.py | 1,265 | 4.125 | 4 | #Input a string, create a list of the different characters in the string, then count how many of each character
def CountChar(chr,list):
#This function inputs an item and a list and counts how many of item are in the list.
count=0
for i in list:
if i==chr:
count+... |
946b849894ca11ef343fdd5ff3df98c1b87330b4 | s0fiateixeira/FEUP_FPRO | /RE - Away Assignments/RE03/regular.py | 614 | 4.09375 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Oct 10 11:42:39 2018
@author: up201806629
"""
import turtle
number_sides = input ("Choose the number of sides: ")
length_side= input ("Choose the length of the side: ")
border_color= input ("Choose the border color: ")
fill_color= input ("Choose the fi... |
3820b4eac353ff8ba59a8f521761b6be915b5e87 | Sandhya-02/programming | /0 Python old/03_square.py | 245 | 4.25 | 4 |
#* area of square = side square
side = 3
print("area of square ",side*side)
print("perimetre of square",4*side)
#! user giving input
side = int(input("enter a number "))
print("area of square ",side*side)
print("perimetre of square",4*side) |
ed669410adb8a135b228caf8266935658c675b24 | winecave/prime | /prime.py | 1,903 | 3.640625 | 4 | import time
from sys import argv
def is_prime_num(num):
t0 = time.time()
count = 0
try:
for i in range(3, num -1, 2):
count += 1
if num % i == 0:
return False
return True
except Exception as e:
return False
finally:
t1 = time.t... |
5d6deed9136a1f9bdb6ce8e8d88e71ce0ac9ad7a | Commando16/hackerRankQnA | /Queen attack2/Queen attack-2_2.py | 1,564 | 3.53125 | 4 | ##def move_counter_at_direction( blocks, Q_pos_x, Q_pos_y, X_move, Y_move, restricted_blocks ):
##
## total_move = 0
##
#### while True:
#### Q_pos_x = Q_pos_x + X_move
#### Q_pos_y = Q_pos_y + Y_move
####
#### if Q_pos_x <= 0 or Q_pos_y <= 0 :
#### break
####
#### ... |
3bffb12d992e6649d09464b4edd8e3f9a522ab8b | fabricio24530/ListaPythonBrasil | /EstruturaDeRepeticao11.py | 341 | 4.03125 | 4 | '''Altere o programa anterior(EstruturaDeRepeticao10.py) para mostrar no final a soma dos números.'''
inicio_intervalo = int(input('Informe o inicio do intervalo: '))
final_intervalo = int(input('Informe o final do intervalo: '))
lista = list()
for i in range(inicio_intervalo, final_intervalo + 1):
lista.append(i... |
11b48e53266341ae830d1688232603df76a18f2c | ztcxdu/weather | /weather.py | 567 | 3.734375 | 4 | #coding=utf-8
import urllib.request
from city import city
import json
cityname = input("你想查询那个城市的天气?\n")
citycode=""
try:
citycode=city[cityname]
except:
print ("not Found")
if citycode:
try:
url=r"http://www.weather.com.cn/data/cityinfo/"+citycode+".html"
content=urllib.request.urlopen(url).read()#读取网页源代码
... |
ec3cc67c13c6e0436f297f26fb39a708f603ce93 | Kevin-byt/transport | /towns_graph.py | 9,085 | 3.734375 | 4 | #!/usr/bin/python
import os
import math
#import heapq #needed if we want to use a priority queue
import graph
import tkinter as tk
class TownGraph:
def __init__(self,num_vertices):
self.__graph_vertices=[graph.Graph(vertex_name=i+1) for i in range(num_vertices)]
self.path_str=None
#con... |
b44693aa7f6206662af6158248eee9a6054d48f0 | TrebuhD/AdventOfCode | /day8/b.py | 1,607 | 3.640625 | 4 | input_lines = open("./input.txt", "r").read().splitlines()
visited_idx = set()
acc = 0
curr_index = 0
reached_end = False
# indices of lines that contain 'jmp' and 'nop' instructions
nop_jmp_indices = [i for i, x in enumerate(input_lines) if x.split(' ')[0] in ('nop', 'jmp')]
curr_flipped_idx = 0
def get_flipped_in... |
f55aed8f81443e593c3f57c9190e083911e6a1c6 | ishumann/Dictionary-App-with-PyDictionary-tkinter | /interface.py | 1,411 | 3.71875 | 4 | from PyDictionary import PyDictionary
import tkinter as tk
from tkinter import messagebox
from tkinter import *
class user_interface(Frame):
def __init__ (self,root):
super().__init__(root)
self.root = root
self.wordlist=[]
self.heading=Label(self.root,text="Dictionary",bg="#d81b60",... |
b2d14b20d20347ad70cf68152441e11caa3972ef | phoenix-11/DSA-Python | /Inorder_Tree_without_Recursion.py | 574 | 3.921875 | 4 | class Node:
def __init__(self,data):
self.data=data
self.left=None
self.right=None
def inorder(root):
current=root
stack=[]
while True:
if current is not None:
stack.append(current)
current=current.left
elif(stack):
... |
f1da93d342591ffd910f45424773af6dc293e8dc | rohit-devops-test/python_training | /day_01/code/02_mult_table.py | 198 | 4.125 | 4 | # Program to print the multiplication table
# Input
n = int(input('Enter a number: '))
# Process
# Output
for i in range(1, 11):
print(str(n) + ' X ' + str(i) + ' = ' + str(n * i))
|
b7745b463a40f7253937745b873548e7f73333e1 | blue-moon22/coding101-workshop | /corner_spiral.py | 261 | 3.75 | 4 | import turtle
side = 200 # Change here
angle = 123 # Change here
myPen = turtle.Turtle()
myPen.speed(0)
myPen.pencolor("red")
myPen.penup()
myPen.goto(0,0)
myPen.pendown()
for i in range(50):
myPen.forward(side)
myPen.left(angle)
turtle.done() |
40c27a978bb9e9c657e0d8f36bfc6b5a6c601787 | Yuchen112211/Leetcode | /problem894.py | 1,518 | 3.921875 | 4 | '''
894. All Possible Full Binary Trees
Medium
A full binary tree is a binary tree where each node has exactly 0 or 2 children.
Return a list of all possible full binary trees with N nodes. Each element of the answer is the root node of one possible tree.
Each node of each tree in the answer must have node.val = 0... |
db35ecb13625f52f465cae41b901e6335fde055e | IgorToro/mi_primer_proyecto | /adivina_el_numero2.py | 284 | 4.0625 | 4 | numero_a_adivinar = int(input("Teclea el numero a adivinar: "))
numero_del_usuario = int(input("Adivina el numero: "))
while numero_a_adivinar != numero_del_usuario:
print("¡Has fallado!")
numero_del_usuario = int(input("Vuelve a intentarlo: : "))
print("¡Has acertado!")
|
97212e0515bf8593e88995c4a906e92aa356c92d | pconerly/projecteuler | /p41.py | 1,040 | 3.546875 | 4 | #p41
import pelib
import math
def lexpos_to_num(lexpos, digits = 9): #for 1-n
digits += 1
d = range(1,digits) #1 to 9
new = []
for i in range(1,digits):
new.append(d[lexpos[i-1]])
d.pop(lexpos[i-1])
return new
def incr_lexpos(lexpos, n):
lexpos[-1] += 1
length = len(lexpos)... |
0c92639b271d4c32fe92a7613e2ca4068541ab64 | ssarangi/algorithms | /practice/streaming_median.py | 1,657 | 3.53125 | 4 | import heapq
from enum import Enum
class HEAPTYPE(Enum):
MAX_HEAP = 1
MIN_HEAP = 2
class PriorityQueue:
def __init__(self, heap_type):
self._queue = []
self.heap_type = heap_type
def push(self, item, priority = None):
if priority is None:
priority = item
i... |
fa83bb218f741c43586e51a0a24ad72c9795d364 | Hydebutterfy/learn-python | /message/FrequentWords(with Mismatches Problem)dict 反向互补.py | 1,602 | 3.828125 | 4 | def reverse_string(seq):
return seq[::-1]
def complement(seq):
#return the complementary sequence string.
seq=seq.upper()
basecomplement={"A":"T","C":"G","G":"C","T":"A","N":"N"}
letters=list(seq)
letters=[basecomplement[base] for base in letters]
return ''.join(letters)
def reversecomplement(... |
f995c8bf571e0ee567fa4a94a485b89522109bad | okonwuchekwa9/Problem_4 | /temp_functions.py | 405 | 3.9375 | 4 | def fahr_to_celsius(temp_data):
"""converts Fahrenheit to Celsius"""
return (temp_data - 32)/1.8
def temp_classifier(temp_celsius):
"""This is a temp classifier for grading temperature"""
if temp_celsius < -2:
return 0
elif temp_celsius >= -2 and temp_celsius < 2:
return 1
elif ... |
6244ff6333f042d7fc858c0b3b03fa2e8052c2ff | cotyb/LeetCode-python | /numberof1bits.py | 286 | 3.734375 | 4 | class Solution(object):
def hammingWeight(self, n):
"""
:type n: int
:rtype: int
"""
cnt = 0
while n > 0:
tmp = n % 2
n = n/2
cnt += tmp
return cnt
a = Solution()
print a.hammingWeight(-1) |
b0191954aadff9cd66bbfb6bbc8cefe6f855d6f0 | mayank25awasthi/portfolio | /Data_Structure_Python/Linked_List/Single_Linked_List/Practice2.py | 3,591 | 3.734375 | 4 | class Node():
"""docstring for """
def __init__(self, value):
self.value=value
self.nextnode=None
class SingleLinkedList():
"""docstring for ClassName"""
def __init__(self):
self.head=None
def add_head_element(self,value):
node=Node(value)
if self.head is None:
self.head=node
return
crnt_node=s... |
2d3a83010c4fbc19834191c227e95bdc594d606f | yuri-ming/Algorithm | /baekjoon_python/1_if/2753.py | 121 | 3.765625 | 4 |
year=int(input())
if (year%4==0 and year%100 != 0) or (year%4==0 and year%400==0):
print("1")
else:
print("0")
|
719f4be112bd1150c96fc9c2cc9bbbf0e01e61bf | AliM3/Net-Centric | /IterateLists.py | 402 | 4.21875 | 4 | # Ways to traverse a list
# Reset i for every list test here
list = [1, 2, 3, 4, 5]
# Liat comprehension
[print(i) for i in list]
# Loop with range()
length = len(list)
for i in range(length):
print(list[i])
# For loop only
for i in list:
print(i)
# While loop
length2 = len(list)
i = 0
while i < length:
print(... |
8f0b54657c6355450855b13e34512287c466a032 | filipov73/python_fundamentals_september_2019 | /Exam/Programming Fundamentals Mid Exam - 30 June 2019 Group 1/Number Array.py | 856 | 3.734375 | 4 | numbers = [int(x) for x in input().split(" ")]
command = input()
while command != "End":
tokens = command.split(" ")
if tokens[0] == "Switch":
idx = int(tokens[1])
if 0 <= idx < len(numbers):
numbers[idx] *= -1
elif tokens[0] == "Change":
idx = int(tokens[1])
va... |
bd4ddc6172c893f9a501cdf181672356d26e8c86 | deepu14d/Decrypto | /decrypto/src/bacon_cipher.py | 1,253 | 3.9375 | 4 | class BaconCipher:
def __init__(self):
'''This is python implementation of Bacon Cipher'''
self.bacon_dict = {
'A': 'aaaaa', 'B': 'aaaab', 'C': 'aaaba',
'D': 'aaabb', 'E': 'aabaa', 'F': 'aabab',
'G': 'aabba', 'H': 'aabbb', 'I': 'abaaa',
'J': 'abaab', ... |
b37ab215e99fb34effcacc1624417d7c3e651abb | cathyxingchang/leetcode | /code/127. Word Ladder_4.py | 4,354 | 3.65625 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# 127. Word Ladder
# Created by xing 2017/4/2
"""
随用随生成字典
双向bfs
"""
import time
class Solution(object):
def ladderLength(self, beginWord, endWord, wordList):
"""
:type beginWord: str
:type endWord: str
:type wordList: List[str]
... |
75c0de12150fcdcaa71f428895cc92e4aa5ebe1b | Luminoid/LeetCode | /PythonCode/AddTwoNumbers.py | 1,395 | 3.78125 | 4 | from typing import Optional
from ListNode import ListNode, generateListNodes, printListNode
class Solution:
# Time complexity: O(max(m, n))
# Space complexity: O(max(m, n))
def insertFront(self, num: int, listNode: ListNode) -> ListNode:
return ListNode(num, listNode)
def generateReversedLis... |
26a181d856f08ef0bc5da8852a806cba434ea670 | brunoyanezb/RepositorioBruno | /task1.py | 237 | 3.5 | 4 | import time
nombrearch = input("Teclea el nombre del archivo: ")
print(nombrearch)
contmax = int(input("Cuenta máxima: "))
i=0
while i<= contmax:
f=open(nombrearch, "a")
time.sleep(1)
f.write(str(i))
f.write("/n")
f.close()
i+=1
|
f4acbec19507f8ef6182ff598be6b12789c7c974 | wenjie-lu/AOC2020 | /utils/io_util.py | 1,623 | 3.546875 | 4 | import time
from pathlib import Path
def read_file_raw(input_path):
with open(Path(input_path), 'r') as f:
string = f.read()
return string
def read_file(input_path):
with open(Path(input_path), 'r') as f:
string = f.read().splitlines()
return string
def read_file_with_em... |
9887530231a8fd64ba308e47c2d825da17094b1c | DoctorLai/ACM | /binarysearch/Linked-List-Union/Linked-List-Union.py | 721 | 3.84375 | 4 | # https://helloacm.com/algorithms-to-union-two-sorted-linked-lists/
# https://binarysearch.com/problems/Linked-List-Union
# MEDIUM, RECURSION
# class LLNode:
# def __init__(self, val, next=None):
# self.val = val
# self.next = next
class Solution:
def solve(self, ll0, ll1):
if not ll0:
... |
916c29927e50fc303b2f06c97ed9b88d471f2256 | howletmj/ECE434 | /hw02/etch_matt_howlett.py | 2,808 | 3.5 | 4 | #!/usr/bin/env python3
import Adafruit_BBIO.GPIO as GPIO
#Buttons = ["GPIO_67","GPIO_68","GPIO_44","GPIO_26","GPIO_46","GPIO_65"]
Buttons = ["P8_27","P8_28","P8_30","P8_32","P8_34","P8_36"]
for myButton in Buttons:
print(myButton)
GPIO.setup(myButton, GPIO.IN)
GPIO.add_event_detect(myButton, GPIO.FALLING)
def main()... |
e00fe36139f709281947fd4f049569799e4c7a19 | NguyenHaiPhong/NguyenHaiHa---Fundamentals---C4E19 | /Fundamentals/Session04/guess_my_number.py | 1,182 | 4.1875 | 4 | print("Guess my number game")
print("Now think of a number from 0 to 100, then press 'Enter'")
input()
loop = True
first = 0
end = 100
print("""
All you have to do is answer to my guess
'c' if my guess is 'C'orrect
"s' if my guess is 'S'maller than your number
'h' if my guess is 'H'ihger than your numbe... |
ea84930e9fae139b2c60b3bb4332cf03edbd0d87 | chaitanyakulkarni21/Python | /Lists/setOperations.py | 735 | 4.40625 | 4 |
thisSet = {'a','b','c','d','e'}
print("Set: ", thisSet)
print("Looping through Set: ")
for i in thisSet:
print(i)
print(" ")
print("Search an element in the set ")
x = input("Enter the element you want to search in the set: ")
if x in thisSet:
print("Yes, the element {} is present in the set".format(x))
else:
... |
e227bf0e896a2c6f0215094acc00640dd31873ba | marcoisgood/Leetcode | /0349. Intersection of Two Arrays.py | 446 | 3.890625 | 4 | """
Given two arrays, write a function to compute their intersection.
Example 1:
Input: nums1 = [1,2,2,1], nums2 = [2,2]
Output: [2]
Example 2:
Input: nums1 = [4,9,5], nums2 = [9,4,9,8,4]
Output: [9,4]
"""
class Solution:
def intersection(self, nums1, nums2):
return list(set(nums1)&set(nums2))
if __na... |
87fc15ff1853a258b62c15f360471a7d742848ac | gddaredevil/writeups | /DeconstruCT.F_2021/Code_Decode/encrypter.py | 1,531 | 4.15625 | 4 | from random import choice
inputstring = input("Enter plaintext: ")
# Reads 'cypher.txt' and selects a random key and its corresponding value and returns them
def read_encryption_details():
with open("cypher.txt") as file:
encrypt_text = eval(file.read())
encrypt_key = choice(list(encrypt_t... |
c6798151fac4e193449507f861a5f11c2a053980 | kmanasi95/No_Pairs_Allowed | /No_Pairs_Allowed.py | 1,773 | 4 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat Mar 30 14:15:17 2019
@author: manasikulkarni
You have a boutique that specializes in words that don't have adjacent matching characters. Bobby, competitor, has decided to get out of the word business altogether
and you have bought his inventory. Your... |
28b82e11e49d198f9ea9507adea1b48bcdf67fa6 | Wraient/Python-Progarams | /051.while.sum.py | 197 | 3.96875 | 4 | # total = 0
# i = 1
# number = input("enter a number to sum")
# while total<=int(number):
# total+=1+i
# i+=1
# print(total)
total = 0
i = 1
while i<=10:
total+=i
i+=1
print(total)
|
2f6d7e9567fae8c189a416539d8946a82f897407 | calee14/MyPython | /pythondatabases/databasedata.py | 1,145 | 3.765625 | 4 | class DatabaseData(object):
def __init__(self):
# initialize the lists
self.data_list = []
self.column_list = []
def addrow(self, values):
# add a row to the datalist variables
# row = list of data
row = []
# run checks on the data and add to the lists
for value in values:
print value
if self.ch... |
2f1e092f94cbfa6261998db7be92dc8356688de7 | JosephLevinthal/Research-projects | /5 - Notebooks e Data/1 - Análises numéricas/Arquivos David/Atualizados/logDicas-master/data/2019-1/226/users/4424/codes/1585_1015.py | 409 | 3.765625 | 4 | # Teste seu codigo aos poucos.
# Nao teste tudo no final, pois fica mais dificil de identificar erros.
# Nao se intimide com as mensagens de erro. Elas ajudam a corrigir seu codigo.
numero1=int(input("digite o 1 numero "))
numero2=int(input("digite o 2 numero"))
numero3=int(input("digite o 3 numero"))
x=min(numero1,nu... |
5918c9ab9e2ce11c41893da8125a32601fb5c400 | MeParas324/Python-programs | /pythontuts/loopss.py | 260 | 4.03125 | 4 | # n=1
# while n<=10:
# print(n, end="\t")
# n=n+1
#
# print("\nOutside from the loop")
str="This"
for i in str:
print(str, end="\t")
# n=int(input("Enter any number:"))
# print(f"table of {n}")
# for i in range(1,11):
# print(n,"X",i,"=",n*i) |
bd0f543acb7c9c7b9361eba1314f6c8de6e56442 | diegopnh/AulaPy2 | /Aula 15/Ex069.py | 679 | 3.875 | 4 | print(20*'-','CADASTRO DE PESSOAS \n',20*'-')
age = int(input('Idade: '))
sex = str(input('Sexo: ')).upper()
bigger = men = woman = 0
while True:
contn = (str(input('Você quer continuar? [Y/N]: '))).upper()
if age >= 18:
bigger += 1
if sex == "M":
men += 1
if sex == "F" and age < 20:
... |
150779d9a40ac05ec3ddac569b9bb1293fcd127f | denvs/Python_lessons_basic | /lesson01/home_work/hw01_normal.py | 1,698 | 4.0625 | 4 |
__author__ = 'Ферагин Денис Евгеньевич'
# Задача: используя цикл запрашивайте у пользователя число пока оно не станет больше 0, но меньше 10.
# После того, как пользователь введет корректное число, возведите его в степерь 2 и выведите на экран.
# Например, пользователь вводит число 123, вы сообщаете ему, что число не... |
16b160273b6627597298ac33bea5dc13d4c95ee8 | ipeksahbazoglu/pingpong | /pingpong.py | 3,749 | 3.875 | 4 | #this is a ping pong game
import turtle
import os
#create a window
ipek = turtle.Screen()
#title the window and other customizations
ipek.title("Ping Pong by Ipek")
ipek.bgcolor("black")
ipek.setup(width=800, height=600)
# add a tracer, it stops the window from updating so we manually update it aka make the game run... |
00ca7ffb1b42f03d5635df0c485ee0fd0bac575e | Niccasso/Encryption_Cipher | /Cipher.py | 4,005 | 4.09375 | 4 | import random
import string
class cipher():
def __init__(self):
valid1 = False
valid2 = False
while(not valid1):
print("Now running Matthew's Encryption Cipher.")
choice1 = input("Type \"e\" to encrypt, Type \"d\" to decrypt.")
if choice1 == "e"... |
b942ad7fdbc92d3cc8dd659f0b8e114ebef172b1 | hammond756/hashcode2018 | /Ride.py | 552 | 3.59375 | 4 |
class Ride :
def __init__ (self, line, id):
self.id = id
things = line.split()
self.startRow = int(things[0])
self.startCol = int(things[1])
self.endRow = int(things[2])
self.endCol = int(things[3])
self.start = int(things[4])
self.end = int(things[5])
def __len__ (self):
return abs(self.startRow ... |
a3775466d520e001307f4a23a1c1d63d7286be97 | Software05/Github | /Modulo-for/app3.py | 487 | 3.875 | 4 | palabraSinVocal = ""
# Indicar al usuario que ingrese una palabra
userWord = input('Ingrese la palabra: ')
# y asignarlo a la variable userWord
userWord = userWord.upper()
for letra in userWord:
if letra == 'A':
continue
if letra == 'E':
continue
if letra == 'I':
continue
if l... |
b231d903e751a92ffd1fca5a02261c8e7bbbf48f | jaychea/nevada_test_site | /11 may/breakfast.py | 417 | 4.15625 | 4 | answer = ""
while answer not in ("1", "2"):
answer = input("Did you eat breakfast today? (1/2)\n1) Yes, I ate breakfast today.\n2) No, I did not eat breakfast today.\n 1 or 2\n")
if answer == "1":
print("Good! It is the most important meal of the day.")
elif answer == "2":
print("It's ... |
e800590c010d22b3c8edfcbeff4039dbfe74bdd0 | jackiechen1992/statistics | /software Statistic/Locomotive.py | 1,317 | 3.515625 | 4 | #-*- coding:utf-8 -*-
# 火车头问题
import random
def number_trans(upper_bound):
return random.randint(1,upper_bound)
def train_seen(N):
return random.randint(1,N)
# 最大似然估计,即概率最大
def MLE_estimation(evidence):
return evidence
# 偏差平方和最小
def MSE_estimation(evidence):
return round(1.5*evidence)
# 偏差最小
def ... |
f4cb346b109a3eb9c526915f4dcf07d29627b0ba | yu-ichiro/atcoder-workspace | /arc127/B/main.py | 839 | 3.625 | 4 | #!/usr/bin/env python3
# Generated by AtCoder Tools 2.8.0
# Copyright 2021 Yuichiro Smith
import sys
def base_n(n: int, k: int, chars="0123456789abcdefghijklmnopqrstuvwxyz") -> str:
q, r = divmod(k, n)
return (base_n(n, q, chars) if q > 0 else "") + chars[r]
def solve(N: int, L: int):
base = 2 * 3**(L-1... |
882346b2b54fb9b97945d64b57cc156ddcf36296 | BradleyPelton/Leetcode-Solutions | /contests2020q2/leetcode20200627/pathcrossing.py | 1,335 | 3.609375 | 4 |
## Accepted first try. Leetcode was DDOS'd and was down for 30 minutes
# I solved this after about 5 minutes.
class contests2020q4.leetcode20201017.Solution:
def isPathCrossing(self, path: str) -> bool:
current_x = 0
current_y = 0
visited_points = [(0,0)]
for char in path... |
b62fdb35323d60f7abc1d76dd0bd6c52f030d3da | twirrim/kattis | /python/sodaslurper.py | 734 | 3.5 | 4 | #!/usr/bin/env python3
import sys
import logging
from math import floor
logging.basicConfig(level=logging.INFO)
empty, found, need = sys.stdin.readline().rstrip().split(" ")
empty = int(empty)
found = int(found)
need = int(need)
drunk = 0
logging.info("Empty: {}\tFound: {}\tNeed: {}".format(empty, found, need))
wh... |
130dd72d4bc60059f17524be345cacc317908534 | blopax/2019-advent-of-code | /day01/day01.py | 871 | 3.71875 | 4 | import math
def get_modules_mass(input_path):
with open(input_path) as f:
input_list = f.readlines()
return [int(x) for x in input_list]
def fuel_for_mass(mass):
return max(0, int(math.floor(mass/3.0) - 2))
def fuel_for_module(module_mass):
total = 0
added_fuel = fuel_for_mass(module_m... |
c6c0691bb9390d1c5456182c64f94adbc1d3b9e2 | gabriellaec/desoft-analise-exercicios | /backup/user_344/ch120_2020_04_01_18_40_42_475876.py | 1,149 | 3.671875 | 4 | import random
dinheiro= 100
print("Voce tem {0}".format( dinheiro))
while dinheiro>0:
aposta = int(input("quanto quer apostar?"))
if aposta == 0:
break
perg = input('A aposta é numero ou paridade? ')
if perg == 'n':
resp = random.randint(1,36)
chute = int(input('Escreva um numer... |
04e87f0b57327b214f11443ce261d8e8e7a6e984 | edmartins-br/PythonFundamentals | /Exe_strings.py | 2,616 | 3.984375 | 4 | # ================== EXERCICIOS =========================
# 22)
# Crie um programa que leia o nome completo de uma pessoa e mostre:
# O nome com todas as letras maiusculas
# O nome com todas minusculas
# Quantas letras aotodo sem considerar espacos
# Quantas letras tem o primeiro nome
print('========== EXE... |
1152324b51df6eda0c99596a2c58f9f866820042 | wanghuayou1028/Codetest | /Python/score.py | 262 | 4.0625 | 4 | #coding:utf-8
score = int(input('Please input the score:'))
if 100 >= score >= 90:
print('A')
assert score < 0
elif 90 > score >= 80:
print('B')
elif 80 > score >= 70:
print('C')
elif 70 >score:
print("Fall")
else:
print("input error!!!") |
baf4a9530481bc8a75c1abee80eb1ced5c0ca822 | anoadragon453/AOC-2015 | /day3/spherical-houses-robo.py | 2,553 | 3.953125 | 4 | ### Problem ###
'''
--- Part Two ---
The next year, to speed up the process, Santa creates a robot version of himself, Robo-Santa, to deliver presents with him.
Santa and Robo-Santa start at the same location (delivering two presents to the same starting house), then take turns moving based on instructions from the ... |
05964c961cd041b5a85f343e4c55a436210dbc6a | fastndead/SummerPractice2018 | /стр 21 - I (3).py | 97 | 3.734375 | 4 | import math
x = float(input("Enter X = "))
print(math.sqrt(x ** 4 + math.sqrt(math.fabs(x+1))))
|
0587c7bc933e45e6ab11cf3bb6da2bec604e5982 | Firmino-Neto/Exercicios---Python--UFC- | /Estrutura de repetição -py/18 - bin_To_Dec.py | 197 | 3.53125 | 4 |
n = input("Digite o binario: ")
bin = n[::-1]
exp = 0
soma = 0
for i in bin:
i = int(i)
dec = i*2**exp
soma = soma + dec
exp = exp + 1
print('decimal correspondente:',soma)
|
2e6ef00b997d3a2aebf132996980b311e5e7e491 | liangxiaoxuan/Algorithm-training | /Leetcode/Python/easy/11_24_2_Symmetric Tree.py | 1,685 | 4.34375 | 4 | # coding=utf-8
# Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center).
#
# For example, this binary tree [1,2,2,3,4,4,3] is symmetric:
#
# 1
# / \
# 2 2
# / \ / \
# 3 4 4 3
#
#
# But the following [1,2,2,null,3,null,3] is not:
#
# 1
# / \
# 2 2
# \ ... |
a6065ff7628b2926003abd5a3db72b397ba13e91 | Mtmh/py.1nivel1 | /193Class_Init_Operaciones.py | 1,115 | 3.96875 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sun Sep 17 20:12:55 2017
@author: tizianomartinhernando
"""
'''
Implementar la clase Operaciones. Se deben cargar dos valores
enteros por teclado en el método __init__, calcular su suma,
resta, multiplicación y división,
cada una en un método, imprimir ... |
6d9578c2b626471d079694dd941159d273b1055c | ravitejvenkataswamy/Constitution-of-India | /Programming related/pythoned2.py | 1,427 | 3.65625 | 4 | articles = ["1. Name and territory of the Union",
"2. Admission or establishment of new States",
"3. Formation of new States and alteration of areas, boundaries or names of existing States",
"4. Laws made under articles 2 and 3 to provide for the amendment of the First and the Fourth Schedules and supplemental, incid... |
960391a654a5ff0c0cfbff359b15a157e10f5601 | soowork/python-programming | /unit-2/functions.py | 1,997 | 4.21875 | 4 | # function with multiple arguments
def greeting(name, job, hobby):
# note f'' (f-string) is not available before 3.6
print(f'Hello {name} your job is {job} and you like {hobby}')
#greeting('Sue','DB developer', 'pool')
'''
# -- works
def reverse_list(my_list):
reversed_list = []
# iterate over the lis... |
31d78ffa7a21282f0403e5a5c84f8de3676eab03 | weirdNox/Competitive | /Foobar/Maximum equality.py | 1,093 | 3.640625 | 4 | def answer(x):
numberOfRabbits = 0
i = 0
while i < len(x):
numberOfRabbits += x[i]
i += 1
remainderRabbits = numberOfRabbits % len(x)
if remainderRabbits != 0:
return len(x) - 1
return len(x)
"""
NOT CORRECT - UNIFORM DISTRIBUTION
def answer(x):
... |
efddc7c7f20ca49d35c4e1e1cd2bf861c79b6139 | kaci65/Nichola_Lacey_Python_By_Example_BOOK | /While_Loop/while_party.py | 382 | 3.8125 | 4 | #!/usr/bin/python3
"""Ask for a name and and 1 to count until user declines"""
ans_Y = ["yes", "YES", "y", "Y"]
ans = ans_Y
count = 0
while ans == ans_Y:
name = input("Enter name: ")
print("{:s} has now been invited".format(name))
count = count + 1
ans = input("Do you want to invite anyone else? Y/N: ... |
0fd2946a861afc50b08f2af591a0a8a137e8b1c2 | tliu57/Leetcode | /bnb/WordSearchII/test.py | 1,529 | 4 | 4 | class TrieNode(object):
def __init__(self):
self.children = {}
self.word = False
class Trie(object):
def __init__(self):
self.root = TrieNode()
def insert(self, word):
curr = self.root
for c in word:
if not c in curr.children:
curr.children[c] = TrieNode()
curr = curr.children[c]
curr.word = ... |
d77a4d51d56dda9fbd7337872ed3e8374ecbc33d | apatelCSE/pyprojects | /buzzfeedquiz.py | 1,080 | 4.0625 | 4 | while True:
print("Tell Us Which of These Movies Made You Cry and We'll Guess Your Favorite Food")
counter = 0
titanic = input("Did you cry during Titanic?")
print(titanic)
if "y" in titanic:
counter += 1
up = input("Did Up make you cry?")
print(up)
if "y" in up:
counter += 1
notebook = input(... |
0a1e695314764e476fd2920717b6a1b43023c1a0 | mohanbabu2706/100 | /2020/December/26-Dec/call function.py | 396 | 3.6875 | 4 | def my_function():
print("Hello from my function!")
def my_function_with_args(username,greeting):
print("Hello, %s ,From My Function!,I wish you %s"%(username,greeting))
def sum_two_numbers(a,b):
return a + b
my_function()
#prints - "Hello,Jhon Doe,From my functon!, I wish you a great year!"
... |
2b6fe982a3c3abc548c08a6d0adac82d0422905b | halilkaya/soyouhaveanidea | /ui.py | 1,373 | 3.78125 | 4 | def initproject(all_budget):
print("What's the name of the project?")
name = input()
budget = all_budget + 1
while budget > all_budget:
print("How much budget do you want to allocate to your project?")
budget = int(input())
return name, budget
def cli(objects, entities, used_reso... |
ed13d39700de6fe950efa247e448d83de725f930 | zhengsizuo/leetcode-zhs | /数组/nSum/15-三数之和.py | 2,597 | 3.640625 | 4 | """双指针法,时间复杂度O(n^2)"""
class Solution:
def threeSum(self, nums):
if not nums or len(nums) < 3:
return []
nums.sort() # 先对数组排序
res = []
for k in range(len(nums) - 2):
# 直接跳过的两种情况
if nums[k] > 0:
continue
if k > 0 and n... |
6c43b72768b25d24a3e2a25a3826b90d9a7fa879 | spaikius/subseq | /subseq/SubMatrix.py | 3,992 | 3.5 | 4 | """Description
This module provides a class for generating substitution martrix from a file
"""
import os
class SubMatrix:
def __init__(self, matrix_path):
self.matrix = None
self.name = matrix_path
self.load_matrix(matrix_path)
def load_matrix(self, matrix_path):
"""Loads su... |
e8d3a2a88dfece62a34e388493734f4826f4910a | ananalb/RPSLSPython | /Human.py | 729 | 3.984375 | 4 | # Human
class Human:
def main(self):
print("Main Choice: Choose 1 of 5 choices")
print("Choose 1 for Rock")
print("Choose 2 for Paper")
print("Choose 3 for Scissors")
print("Choose 4 for Lizard")
print("Choose 5 for Spock")
choice = int(input("Please make a ... |
32ad8289d8bdd693956ffa7f542acc0f93894df3 | JamesLawrence30/FinancialEngineeringFinalProject | /homework1/hw1v1.py | 1,810 | 4.28125 | 4 | myFirstString = 'first string!'
print(myFirstString)
student = "I'm a student"
print(student)
thoughts = """I enjoy this
course very much. I think
it will be informative and
helpful in my career pursuits."""
print(thoughts)
a = 100
b = 9
c = a+b
print(c)
quotient = a/b
print(quotient)
quotINT = int(a/b)
pr... |
d87a1540a082ee733553c12c4f6fbd4cf077ad90 | goodsoulkor/python3_fastcampus | /section05-1.py | 1,267 | 4.15625 | 4 | # section05-1
# 조건문
print(type(True))
print(type(False))
# ex1
if True:
print("Yes")
# ex2
if False:
print("No")
# ex3
if False:
print("No")
else:
print("Yes2")
# 관계연산자
# >, >=, <, <=, ==, !=
a = 10
b = 0
print(a == b)
print(a != b)
print(a > b)
print()
# 참, 거짓 종류(True, False)
# 참 : "내용", [내용], ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.