blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
5bd3417da3fac43bd2657b2f50712f52d21f1114 | sindrimt/TDT4110 | /Eksamensøving/2013/Sudoku.py | 4,249 | 3.78125 | 4 | def readOneNumber():
rad = int(input("Rad (1-9)"))
kolonne = int(input("Kolonne (1-9)"))
tall = int(input("Tall (1-9)"))
print("Posisjon: (%d,%d) inneholder nå %df"%(rad,kolonne,tall))
def readPositionDigit(rowNr,colNr,board):
board[rowNr-1][colNr-1] = int(input("Hvilket tall vil du ha på (%d,%... |
308ee6d2d352389a14b3b407e01bbcabf00768e0 | shelcia/InterviewQuestionPython | /amazon/CountDistinct.py | 1,376 | 4.03125 | 4 | # Count distinct elements in every window of size k
# Given an array of size n and an integer k, return the count of distinct numbers in
# all windows of size k.
# Example:
# Input: arr[] = {1, 2, 1, 3, 4, 2, 3};
# k = 4
# Output: 3 4 4 3
# Explanation:
# First window is {1, 2, 1, 3}, count of distinct numbe... |
087ae81971ce6cf01d48cf6a7fc2364d26d285a5 | fernandocostar/competitive-programming | /programming-challenges-2016-2/Codes/Tarefa05c.py | 497 | 3.625 | 4 | import itertools
def fazerAnagramas(x):
vet = ["".join(perm) for perm in itertools.permutations(x)]
return vet
def ordenar(x):
temp = []
x = sorted(x)
actual = 0
for i in range(len(x[0])):
user = int(input())
vet = []
for i in range(user):
vet += [input()]
aux = []
result = []
for each ... |
b6496a7e54deeda38ffd866cf97da05d4256aacc | matteocaruso98/matteo | /multiplesoften.py | 387 | 3.96875 | 4 | #multiplies of ten
numlist = range (1,11)
list = [i*10 for i in numlist]
print("i primi 10 multipli di 10:", list)
#cubes
cubelist = [i**3 for i in range (1,11)]
print("i primi dieci cubi:", cubelist)
#awesomeness
print("i am awesome!!")
namelist = ["matteo", "francesco", "michele", "chiara", "giorgio"]
awesomelist ... |
bdb3e0d6dd20d4a4bf44b64dbada4e71e87d1b8d | ksnt/leet | /26.py | 368 | 3.75 | 4 | # Reference: https://www.lifewithpython.com/2013/11/python-remove-duplicates-from-lists.html
class Solution:
def removeDuplicates(self,nums):
"""
:type nums: List[int]
:rtype: int
"""
seen = set()
seen_add = seen.add
nums[:] = [ x for x in nums if x not in se... |
c885e2c7951fe750da25bb0b5313bb1925210892 | CafeYuzuHuang/coding | /ReverseLinkedList.py | 578 | 3.796875 | 4 | # Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def reverseList(self, head: ListNode) -> ListNode:
# 2021.03.29
# 1st solution:
if not head: return head
before = Non... |
51ccaaa6e83217e6cda9dc276e2e5b71afd619a6 | muhammed-ayman/CSCI-101-course-labs-solutions | /02/11.py | 113 | 3.859375 | 4 |
x = int(input('Enter X > '))
y = int(input('Enter Y > '))
res = 1
for i in range(y):
res *= x
print(res)
|
db04d66b999721fbcd37b1cca2981fd23ac1a530 | reutsharabani/the-magic-of-python | /5_flattening_lists_with_sum.py | 960 | 3.765625 | 4 | list_of_lists = [[1, 2], [3, 4]]
print(sum(list_of_lists, []))
def flatten_with_sum(ll):
return sum(ll, [])
def time_flattening(flat_func, sublists_count):
return flat_func([[1]] * sublists_count)
counts = (10, 100, 1000)
for count in counts:
import timeit
t = timeit.timeit('time_flattening(flat... |
448a2f112bb087ff13996dd3a435ed4011572c3f | ipranshulsingla/python | /multiples.py | 87 | 3.765625 | 4 | no=int(input("Enter a no:"))
for i in range(1,11):
print(no,'x',i,'=',no*i)
|
19efe8752a327f67f9ca5007027ac4905d463372 | RamaVenkatSai/PYCHARM | /Nannakuprematho.py | 749 | 4.0625 | 4 | class node:
def __init__(self,data=None):
self.data=data
self.next=None
class Linked_list:
def __init__(self):
self.head=node()
def append(self,data):
new_node=node(data)
cur=self.head
while cur.next!=None:
cur=cur.next
cur.next... |
16a2f4477efb739556ef71367aab9f277dfce9f3 | YanpingDong/leetcodeSolution | /PowerOfTwo.py | 502 | 3.578125 | 4 | class PowerOfTwo(object):
def isPowerOfTwo(self, n):
"""
:type n: int
:rtype: bool
"""
return n > 0 and bin(n).count('1') == 1
def isPowerOfTwoOptimal(self, n):
"""
:type n: int
:rtype: bool
"""
return n > 0 and not(n&n-1)
if __n... |
9dc5d88ca56085188450723c8aed5f1d03540569 | AirEliteMV24/Term-1-Portflio | /term 1/Cool Art.py | 446 | 3.546875 | 4 | from turtle import *
pencolor("deepskyblue")
fillcolor("silver")
begin_fill()
bgcolor("black")
speed = 100
sides = 5
distance = 100
for _ in range(50*sides):
distance += 20
forward(distance)
right(2*360.0/sides+1)
begin_fill()
fillcolor("silver")
speed=100
pencolor("silver")
sides=5
... |
6caa2dcf4fef92fa0f987b1d8132f3582fea89a2 | edgarcamilocamacho/usta_digital_systems_3 | /09_python/04_ejemplo.py | 191 | 3.625 | 4 |
numbers = [5.0, 7.0, 3.0, 8.0, 4.0, 5.0, 6.0]
# numbers_2 = []
# for number in numbers:
# numbers_2.append(number**2)
numbers_2 = [number**2 for number in numbers]
print(numbers_2)
|
6d3cc479922981559db56c8d75710985365e8d09 | CsokiHUN/python-practice | /5.py | 389 | 3.703125 | 4 | numbers = []
for i in range(3):
inum = None
while not inum:
try:
inum = int(input('Add meg a ' + str(i + 1) + '. számot: '))
except:
print('Hibás szám próbáld újra!')
numbers.append(inum)
for i in numbers:
counter = 0
for k in numbers:
if (k != i):
counter += k
print(i, (coun... |
2b2c8f4724e1f2cac9f0ad457a9792cb20310824 | Danny0596/PYTHON | /Año,Mes,Dia.py | 494 | 4.03125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Thu Jul 2 14:41:54 2020
@author: Danny Lema
"""
def daysInMonth(day,month,years):
if years % 400 == 0:
return True
elif years % 100 == 0:
return False
elif years % 4 == 0:
return True
else:
return False
year = 190... |
c7a99f091a3da2f59f633bbc4dcd91c44c1bcd67 | mkioga/21_python_FileIO | /21_FileIO.py | 20,442 | 4.5625 | 5 |
# ===============
# 21_FileIO.py
# ===============
# =======================
# File Input Output
# =======================
# Reading text file in python
# Reading text files consist of three simple steps
# (1) Open file - using python built in function called "open"
# (2) Read the file - can read one line at a time... |
3061ff62f2aff6b39086ca3e4b577fe801cda7dd | hawkinsbl/02-ObjectsFunctionsAndMethods | /src/m2_functions.py | 4,467 | 4.28125 | 4 | """
Practice DEFINING and CALLING
FUNCTIONS
Authors: David Mutchler, Vibha Alangar, Matt Boutell, Dave Fisher,
Aaron Wilkin, their colleagues, and Ben Hawkins.
""" # DONE: 1. PUT YOUR NAME IN THE ABOVE LINE.
###############################################################################
# Done: 2.
# ... |
ab7928a9cccd70ab19a687b649125169e5c7fbf7 | ahirapatel/dspguide-stuff | /ch04/homework-comp.py | 3,315 | 4.09375 | 4 | #!/usr/bin/env python
"""
CHAPTER 4: DSP SOFTWARE
"""
"""
This exercise looks at the problem of adding numbers that are very different
is size. Write a computer program(s) to complete the following.
1. Generate a 256 samples long sine wave with an amplitude of one, and a
frequency such that it completes 3 full p... |
d896718118f379992bae542fbc0738abafb7751f | yulya2787/python_advanced | /less4/#1.py | 3,276 | 3.90625 | 4 | from abc import *
from datetime import date
class Person(metaclass=ABCMeta):
def __init__(self, name, year, month, day):
self.name = name
self.year = year
self.month = month
self.day = day
print('(Person: {0})'.format(self.name))
def __str__(self):
'''Returns c... |
63763b3630bae305ebb4cbc163edcf88a51c0fe2 | MESragelden/leetCode | /Contiguous Array2.py | 415 | 3.59375 | 4 | def findMaxLength(nums):
d = dict()
longest = 0
sum = 0
for i in range(len(nums)):
if nums[i] == 0:
sum -= 1
else :
sum += 1
if sum == 0 :
longest = i+1
if sum in d:
longest = max(longest,(i - d[sum]))
... |
23bcf2b555311c84123314d5a9747162584fd2b3 | Magictotal10/FMF-homework-2020spring | /homework8/ast.py | 3,993 | 3.78125 | 4 | from enum import Enum
from typing import List
# a utility class to represent the code you should fill in.
class Todo(Exception):
pass
########################################
# This bunch of code declare the syntax for the language C--, as we
# discussed in the class:
'''
bop ::= + | - | * | / | == | != | > | < ... |
d24308ddd7c6d2546375f1fcec6149edffcf15cd | Tepah/Aim-Stats-Graph | /stat_tracker.py | 5,948 | 3.6875 | 4 | import json
from datetime import datetime
from datetime import date
import matplotlib.pyplot as plt
import os
# TODO: Clean and refractor a bit
def add_new_mode(all_modes):
"""Adds a new mode to the json dictionary
Args:
all_modes (dictionary):
Returns:
[type]: [description]
"""
... |
b0ebe7981e6231f7c190dc32cda2caf091e3e6d7 | matthew-ding/primes-project-2020 | /compareRelay.py | 635 | 3.5625 | 4 | import matplotlib.pyplot as plt
import broadcastRelay
import trivialRelay
print("Beginning Broadcast Relay")
broadcastCost = broadcastRelay.main()
xList = []
for i in range(len(broadcastCost)):
xList.append(i)
print("\n" + "Beginning Trivial Relay")
trivialCost, diameter = trivialRelay.main()
xList2 = []
for ... |
7541654fa121ca6d285f1c99e6b9d0a8194f6e3b | lauramatchett/hackbright-intro-more-lists-and-loops | /02-range-and-loops/fun_for_loops.py | 280 | 3.8125 | 4 | #for i in range (10,-1, -1):
# if (i == 0):
# print "Blast off!"
# else:
# print i,
#fruits = ["apples", "oranges", "bananas"]
#for f in range(5):
# print fruits,
def sum_nums(num):
sum = 0
for i in range(num):
sum = i + sum
return sum
print sum_nums(10) |
2b10d7f92ee9d5e32a0b795d8041f3e7615d12b7 | vrishank97/Project-Euler | /euler project -145.py | 214 | 3.78125 | 4 | L = 6 #Limit is expressed as 10^L
C = 0
for n in xrange(2, L+1):
if n % 2 == 0: C += 20 * pow(30, n//2 - 1)
elif n % 4 == 3: C += 100 * pow(500, n//4)
print "Reversible numbers below 10 ^", L, '=', C
|
e71c8120249ba37f05ed28b0cbac6ef5f17544db | skdlfjl/network_programming | /HW3_JIHEE_LEE/hw3_2.py | 1,091 | 3.875 | 4 | # 2. 아래 내용에 대한 프로그램(1개)을 작성하라.
d=[{'name':'Todd', 'phone':'555-1414', 'email':'todd@mail.net'}, {'name':'Helga', 'phone':'555-1618', 'email':'helga@mail.net'},
{'name':'Princess', 'phone':'555-3141', 'email':''}, {'name':'LJ', 'phone':'555-2718', 'email':'lj@mail.net'}]
# 전화번호가 8로 끝나는 사용자 이름을 출력하라.
print('전화번호가 8로 끝나는... |
42217183482af357897b74b9e916f32c63c6ec4d | feliperod0519/python | /ransom.py | 1,309 | 3.53125 | 4 | import argparse
import os
import random
def get_args():
parser = argparse.ArgumentParser(description='Ransom Note',formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument('text', metavar='text', help='Input text or file')
parser.add_argument('-s','--seed',help='Random seed',metavar='int... |
5a3d3ca610efd26bea6b5ee67da63b9181c6fcfa | guido-lab/Tasker | /helperScripts/taskFunctions.py | 346 | 3.5 | 4 | import time
from abc import ABC, abstractmethod
class Tasks(ABC):
def __init__(self):
pass
@abstractmethod
def SumTwoNumbers(num_one, num_two):
time.sleep(1)
return num_one + num_two
@abstractmethod
def MultipleThreeNumbers(num_one, num_two, num_three):
return num_... |
c18638fb42a0d6c8e8a296e1c2890d8b7eee7fac | aditiabhang/Face_Detection | /webcam_main.py | 1,115 | 3.59375 | 4 | import cv2
# Importing the pre-trained data
cascade_path = "haarcascade_frontalface_default.xml"
faceCascade = cv2.CascadeClassifier(cascade_path)
# Capturing the video using cv2
video_capture = cv2.VideoCapture(0)
while True:
# Capturing the video frame-by-frame
ret, frame = video_capture.read()
# Reco... |
f7d8aeb63190f98f4e2b268a900fdd0dda81a2d6 | Tobijoe/LPTHW | /ex15.py | 645 | 3.984375 | 4 |
#from sys import argv argument
from sys import argv
#add arguments to argv, in this case script name (ex15.py)and the text sample (ex15sample.txt)
script, filename = argv
#set var txt to open filename given in argument
txt = open(filename)
#print formatted string, with filename
print(f"Here is your file {filename}")
#... |
19641ffe5b289f275e6e5a22f2e2eff645e81243 | holbertra/Python-fundamentals | /data_structures/test.py | 362 | 3.859375 | 4 | my_numbers = [1, 2, 3, 4, 5]
def sum_recurs(numbers, count):
print(f'calling sum_recurs {count} times')
count += 1
if len(numbers) == 1:
return numbers[0]
else:
print(f'from else: returning {numbers[0]} + {numbers[1:]}')
return numbers[0] + sum_recurs(numbers[1:], count)
my_co... |
6d76e1e43f7974bfe9dcffc114682a6a758af344 | songyongzhuang/PythonCode_office | /lemon/python22/lemon_06_190828_for_while_函数/优秀作业_0828/Yuan_HomeWork_0828_02.py | 451 | 3.84375 | 4 | # -*-coding=utf-8-*-
# 2.分别使用for和while打印九九乘法表,格式:每项数据之间空一个Tab键,可以使用"\t"
# for方法
for i in range(1, 10):
for j in range(1, i+1):
print("{} * {} = {}".format(j, i, j*i), end="\t")
print()
print("*" * 120)
# while方法
i = 1
while i <= 9:
j = 1
while j <= i:
print("{} * {} = {}".format(j, ... |
592993959bec9722c6273a79ed0bb989102e55b4 | vineetwani/PythonDevelopment | /ListAndSetBasics.py | 1,056 | 4.15625 | 4 | #Define a list, set
#Output of Function listBasics:
# <class 'list'>
# [['Punit', 79], ['Vineet', 66]]
# ['Punit', 'Vineet']
# [79, 66]
def listBasics():
#l1=list() Can define like this as well
l1=[]
print(type(l1))
l1.insert(0,["Vineet",66])
l1.insert(0,["Punit",79])
... |
9f16cbcb2d2c93422411cc9c1b5d767c976ef33c | buckuw/pynet-ons-oct17 | /day1/exercises_day1/str2.py | 176 | 3.875 | 4 | #!/usr/bin/env python
ip_addr = input("Gimme an IP: ")
ip_addr = ip_addr.split(".")
print('{:<12}{:<12}{:<12}{:<12}'.format(ip_addr[0], ip_addr[1], ip_addr[2], ip_addr[3]))
|
73919ce5023cfd59dc6c1296126f1677700f4786 | almog20-meet/meet2018y1final-proj | /test.py | 2,025 | 4.25 | 4 | import turtle
import random
#make turtles
turtle.tracer(1,0) #removes delay
adam = turtle.Turtle()
valeria = turtle.Turtle()
valeria.shape("square") # so you can tell which turtle is which
player = turtle.Turtle()
valeria.up()
adam.up()
my_turtles = [adam, valeria] # this important
#make constant values, display screen... |
9deb02aa1b78807192a9c57d723396b909ea1242 | runley/KazTranslit | /Ascii changer/test.py | 1,110 | 3.515625 | 4 | import tkinter as tk
from tkinter import filedialog as fd
def callback():
name= fd.askopenfilename()
print(name)
def documentKTL(): #top level func to create a new window as Toplevel
docKTL = tk.Toplevel(bg = "#f16161")
docKTL.title('Document to Text - KTL')
global directory
global saveDire... |
42ef9a5adb37520edc405d2e85085dd4d3c8776d | P0LISH-SAUSAGE/python3 | /tester.py | 127 | 3.671875 | 4 | test_str = "Hey, I'm a string, and I have a lot of characters...cool!"
print (test_str)
print ("String length:", len(test_str)) |
d5a72710057b2da78071b19790533af46546819d | knight-byte/Codeforces-Problemset-Solution | /Python/A_Replacing_Elements.py | 560 | 3.53125 | 4 | '''
Author : knight_byte
File : A_Replacing_Elements.py
Created on : 2021-04-14 09:55:54
'''
def min_sum(arr, i, d):
for j in range(len(arr)-1):
for k in range(j+1, len(arr)):
if j != i and k != 0 and arr[j]+arr[k] <= d:
return arr[j]+arr[k]
return -1
def main()... |
68c15adf3245d7337047f9f63634d61ef680e0a3 | laasya15g/looping | /fibanaaccinumbers and positive range.py | 916 | 4.0625 | 4 | #!/usr/bin/env python
# coding: utf-8
# In[16]:
terms=int(input("enter the number of terms:"))
i=0
j=1 #initialsing the first 2 numbers
count=0;
if terms<=0 :
print("print the valid postive number")
terms=int(input("enter the number of terms:"))
elif terms == 1 :
print("fibancci series:1")
else:
pas... |
dd713d2b6770954815de1b1830fa44b3ccee5a53 | YoungXu06/MachineLearning | /kNN/kd tree/BinaryTree.py | 2,132 | 3.84375 | 4 | # -*- coding: utf-8 -*-
'''
NOTE: This Code is borrowed from: http://blog.csdn.net/v_victor/article/details/51131283
Created on 2017年9月24日
@author: XY
'''
class BinaryTree(object):
'''
创建结点
'''
class __node(object):
def __init__(self, value, k,left=None, right=None):
self.v... |
857d5e0eb9cde724ef86b7e2da10c73eb6777e6e | tomki1/bin-packing | /binpack.py | 5,609 | 3.875 | 4 | # binpack.py
# name: Kimberly Tom
# CS325 Homework 8
import sys
import os
# create a Bin class
# https://www.w3schools.com/python/python_classes.asp
class Bin:
# creating a new bin
def __init__(self, capacity):
self.capacity = capacity
# setting capacity
def c... |
f804d471ad7f2eb042981ddcfaa233c3a2c04167 | andy-ang/Codility_attempts | /1_1_BinaryGap.py | 605 | 3.703125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sun Nov 1 14:02:04 2020
@author: andya
"""
# find longest 0
def solution(N):
bin_N = '{0:08b}'.format(N)
start = 0
for i in range(len(bin_N)):
if bin_N[i] == '1':
start = i
break
count =0
longest_0 = 0
for i in r... |
8551b781c01715f7c16b57c775f442b44f51ab2e | bhenne/PhotoPrivateMetadataViewer | /osm_map/lib/tilenames.py | 2,418 | 3.5 | 4 | #!/usr/bin/env python
"""Translates between lat/long and the slippy-map tile numbering scheme
http://wiki.openstreetmap.org/index.php/Slippy_map_tilenames
@author: Oliver White
@date: 2007
@license: This file is public-domain.
"""
__author__ = "Oliver White"
__copyright__ = "(c) 2007, Oliver White"
__license__ = "T... |
388e21a1646bbe9501cc3e3c056f7579f434be3d | houhailun/leetcode | /数组/leetcode561_数组拆分.py | 929 | 3.78125 | 4 | #!/usr/bin/env python
# -*- coding:utf-8 -*-
"""
@Time : 2019/7/2 15:39
@Author : Hou hailun
@File : leetcode561_数组拆分.py
"""
print(__doc__)
"""
给定长度为 2n 的数组, 你的任务是将这些数分成 n 对, 例如 (a1, b1), (a2, b2), ..., (an, bn) ,使得从1 到 n 的 min(ai, bi) 总和最大。
示例 1:
输入: [1,4,3,2]
输出: 4
解释: n 等于 2, 最大总和为 4 = min(1, 2) + min(3, 4... |
edfae68fe3e00ad6c77d9a0ff507fd80fc339c4a | Deepakdd1402/Body-mass-index-BMI- | /Body mass index (BMI).py | 736 | 4.1875 | 4 | print('\033[1;34;40m Body mass index (BMI) CALCULATOR \n ')
print("\033[1;32;40m")
print(" Enter the following details to calculate your Body mass index (BMI) \n ")
Height=float(input(" Enter your height in centimeters(ex:175) : "))
Weight=float(input(" Enter your Weight in Kg: "))
Height = Height/100... |
0f41f1b872ad047bcc7638d9de931edba24500eb | lihongwen1/XB1929_- | /ch04/if_else.py | 131 | 3.75 | 4 | num = int(input('請輸入一個整數?'))
if num%5:
print(num, '不是5的倍數')
else:
print(num, '為5的倍數')
|
1ae0f1aeb55762f604ceb435f16453b0e54189c5 | laithfayizhussein/data-structures-and-algorithm | /python/code_challenges/linked_list/linked_list/ll_zip.py | 967 | 3.875 | 4 | from linked_list import (
LinkedList ,
)
def zip_ll(ll1, ll2):
current1 = ll1.head
current2 = ll2.head
if current1 == None or current2 == None:
if current1:
return ll1.__str__()
elif current2:
return ll2.__str__()
else:
return " the linked l... |
eed72dc8d8c2edc5c90d6a1b729d07390a091f6f | zhudingsuifeng/python | /offer/fibonacci.py | 397 | 3.96875 | 4 | #!/usr/bin/env python3
#coding = utf-8
class Solution:
# @classmethod
def Fibonacci(self,n):
# starting from 0
if n < 2:
return n
l = [0]*(n+1)
l[1], l[2] = 1, 1
for i in range(3, n+1):
l[i] = l[i-1] + l[i-2]
return l[-1]
if __name__ == "... |
bba0bcabed225f6def2e3bdced98e8ca640c5438 | brpadilha/exercicioscursoemvideo | /DesafiosComFunctions/Desafio 022 - Mudança de tamanho da letra.py | 494 | 3.71875 | 4 | def maiusculo (x):
return x.upper()
def minusculo(x):
return x.lower()
def contar_letras_nome_todo(x):
x=len(x)-x.count(' ')
return x
def contar_letras_nome(x):
x=x.split()
return x
nome=str(input('Digite seu nome todo: ')).strip()
maiusc=maiusculo(nome)
minusc=minusculo(nome... |
3d6daf142591ed572946f5bbe2c1310fbb731763 | kentotakeuchi/data-structures-and-algorithms | /leetcode/easy/counting-words-with-a-given-prefix.py | 223 | 3.5625 | 4 | # https://leetcode.com/problems/counting-words-with-a-given-prefix/
class Solution:
def prefixCount(self, words: List[str], pref: str) -> int:
return sum(w.find(pref) == 0 for w in words)
# True is equal to 1
|
b51e335710c723e6a64f4e3a4d7f086cdb57548c | wwtang/code02 | /craking/BFS.py | 1,619 | 4.1875 | 4 | """
Implement bfs in python
"""
graph = {
'1': ['2', '3', '4'],
'2': ['5', '6'],
'5': ['9', '10'],
'4': ['7', '8'],
'7': ['11', '12']
}
def bfs(graph, start, end):
# maintain a queue of paths
queue = []
# push the first path into the queue
queue.append... |
c674b252ad05bc0d137cee4864196eb9933ad666 | SewonShin/BLOCKCHAINSCHOOL | /Python Code 1/HelloCoding/testmodule/main.py | 5,430 | 3.859375 | 4 | class Test:
def __init__(self):
# # 클래스 선언
# class Student:
# count = 0
# # 생성자
# def __init__(self, name, korean, math, english, science):
# Student.count += 1
# self.name = name
# self.korean = korean
# self.math = math
# s... |
eed5f180330bb91bcb93553130424093c7dc542a | abmish/pyprograms | /100Py/Ex78.py | 195 | 3.8125 | 4 | """
Please write a program to randomly generate a list with 5 even numbers between 100 and 200 inclusive.
"""
import random
print random.sample([num for num in range(100, 200) if num%2 == 0], 5) |
fa12b6b1ef08568b82ef3ca5ae4a11fa99834fef | freebz/Learning-Python | /ch38/getattr_v-getattr.py | 978 | 4.21875 | 4 | class GetAttr:
attr1 = 1
def __init__(self):
self.attr2 = 2
def __getattr__(self, attr): # 정의되지 않은 속성에 대해서만 호출됨
print('get: ' + attr) # attr1 제외: 클래스에서 상속함
if attr == 'attr3': # attr2 제외: 인스턴스에 저장됨
return 3
else:
raise A... |
95e49b7983cf84c2c0b9d94fe2f1a1b41edaacfc | alexmatros/codingbat-solutions | /python/logic-2/make_chocolate.py | 243 | 3.578125 | 4 | def make_chocolate(small, big, goal):
max_big = goal / 5
if big >= max_big:
if small >= (goal - max_big * 5):
return goal - max_big * 5
if big < max_big:
if small >= (goal - big * 5):
return goal - big * 5
return -1 |
efb0333d0fb8d80b1675a465c64b26e5bddaf22e | minu-gatech/Data-Analytics-Challenge | /Python Challenge/PyPoll/main.py | 3,039 | 3.71875 | 4 |
''' PYTHON Homework 3 - PyPoll '''
'''Importing modules'''
import os, csv
filename = os.path.join("PyPoll_Resources_election_data.csv")
''' Intializing Variables'''
total_votes_cast = 0
candidates_list = []
candidate = ''
total_votes = []
khan_count = 0
correy_count = 0
li_count = 0
tooley_count = 0
votes_count ... |
e215a6f4841a6c0ebb7b32d1d694acbb45b789d5 | ValiumK/first_repo | /foods.py | 819 | 4.4375 | 4 | # 27.08.2021 Упражнение с срезами(slices)
my_foods =['borsch', 'dumplings', 'pizza', 'bacon', 'pies']
friend_foods = my_foods[:]
# Добавляем разные элементы в оба списка
my_foods.append('pasta')
friend_foods.append(' ice cream')
# Вывод списка в цикле for
for my_food in my_foods:
print(f"My favorite foods are {my_fo... |
a3e63dba11a3a252d85b16456aa04d5ee203b4bb | satyam-seth-learnings/python_learning | /Harshit Vashisth/Chapter 2(All About String)/C-More About Variable/15.Variable_More.py | 84 | 3.5625 | 4 | name,age="Satyam","24"
print("Hello "+name+" Your age is "+age)
x=y=z=1
print(x+y+z) |
eaabe5e8c71751dae32dab33d62ed12a98351e03 | willkara/PyumIpsum | /datastore/Cache.py | 1,031 | 3.625 | 4 | import pickledb
class Cache(object):
"""
The main Cache object. All different types of caches will extend this class.
"""
def __init__(self):
"""
Create an instance of a cache.
:return:
"""
self.cachedb = pickledb.load('pickle.db', False)
def get(self, key... |
a2292640c2551af34ef14aa8774cc2ebd958bf39 | dang-trung/learn-algorithms | /algorithms_data_structures/algorithms/search_binary.py | 551 | 4.09375 | 4 | def search_binary(input_array, value):
left, right = 0, (len(input_array) - 1)
while True:
if left <= right:
mid = int((left + right)/2)
if input_array[mid] == value:
return mid
elif input_array[mid] < value:
left = mid + 1
... |
1e75535cffbecf42de228a4c293469efb6be0672 | rodmur/hackerrank | /algorithms/implementation/gridsearch.py | 1,053 | 3.546875 | 4 | #!/usr/bin/python3
def check_it(G,P,r,c):
ok = True
p = 1
row = r + 1
while ok and p < len(P) and row < len(G):
column = G[row].find(P[p],c)
if column < 0 or c != column:
ok = False
break
p += 1
row += 1
if row == len(G) and p < len(P):
... |
e44815f8d1c0bc5b211deb8151bdf74acf1ca914 | AdamZhouSE/pythonHomework | /Code/CodeRecords/2405/60647/319754.py | 627 | 3.78125 | 4 | a=int(input())
list=[]
for i in range(a):
temp=input().split()
list.append(temp)
if list==[['1', '2'], ['1', '3'], ['2', '5'], ['3', '4'], ['4', '6'], ['6', '5']]:
print(4)
print(2)
print(8,end='')
elif list==[['1', '2'], ['1', '3'], ['2', '4'], ['4', '3']]or list==[['1', '2'], ['1', '3'], ['2', '4... |
74fbffe2119082d8ef0d62cda203048d23a2ea7f | pppppp040/nlp-base-method | /EnglishModel/preprocessingMed/method01/findStr.py | 144 | 4.125 | 4 | str1 = "hello,Crise!"
str2 = "ello"
str3 = ","
#find()返回的是该字符串的下标索引
print(str1.find(str2))
print(str1.find(str3)) |
e4188456846e7327537512132160c5d0b969ed67 | pmediaandy/bullpen | /codility/frogjmp.py | 338 | 3.71875 | 4 | #!/usr/bin/env python
def solution(X, Y, D):
dist = Y - X
if dist % D == 0:
return dist / D
return dist / D + 1
if __name__ == '__main__':
print solution(10, 10, 3) == 0
print solution(10, 20, 2) == 5
print solution(10, 19, 2) == 5
print solution(10, 21, 2) == 6
print solution(... |
32be34153db901b8fb9f6d85a7786dcbe39ddea6 | harshithaRao5/dumpfile | /cspp1/m1/p3/p3/longest_substring.py | 294 | 3.890625 | 4 | "'#finding the longest substring'"
S = input()
i = S[0]
j = ''
"'#checking for the string present in range'"
for a in range(1, len(S)):
if S[a] >= i[len(i)-1]:
i += S[a]
else:
if len(i) > len(j):
j = i
i = S[a]
if len(i) > len(j):
j = i
print(j)
|
ec8902eb992a9187e7d90f8d3428cee0a9bfbb0d | WQ-GC/Python_AbsoluteBeginners | /CH7_ExceptionHandling.py | 3,997 | 3.953125 | 4 | #Python Exceptions
import sys
def ExitProgram():
print("sys.exit() - Exiting Program...")
sys.exit()
def MyFunc(inputVar):
return "Hello World"
def ExceptionInput():
try:
num = float("Hello World")
except ValueError:
print("cannot convert to float")
def ExceptionDivisi... |
c69b34e2222c41700fa3af4aa85bee6beffe3b86 | Putind/Aca | /exerclse03.py | 5,119 | 3.625 | 4 | # num = 1
# # 短路逻辑逻辑运算时 如果前面的条件能判断出最终结果
# # 后面的代码就不会执行
# # 尽量降复杂的判断放在后面
# # and 发现第一个结果为False 就有结论了
# # 后续条件不在判断
# result = num > 1 and input('请输入a') == 'a'
#
# # or发现第一个结果为Ture
# # 后续条件不在判断
# result1 = num == 1 or input('请输入a') == a
# a = 800
# b = 1000
# # id函数 获取变量存储对象的地址
# print(id(a))
# print(id(b))
# print(a is... |
73e88217bb68c7a999374f0258ce545aadd44201 | aga-wojteczko/PythonGGIT | /lab4zad1listy.py | 188 | 3.765625 | 4 | nazwiska = ["kowalski", "nowak", "iksinski", "dudek"]
szukane = input("podaj szukane nazwisko: ")
if szukane in nazwiska:
print("jest na liscie")
else:
print("nie znaleziono") |
38316ecb31378dbb1a967908fba27b7f1d7de2ac | yyyhhhrrr/pythonoldboy | /day4/decorator2.py | 722 | 3.84375 | 4 | #!/usr/bin/env python
# coding:utf-8
# Author:Yang
# 第一个特性:函数即“变量”
# def foo():
# print('in the foo')
# bar()
#
# foo()
# def bar():
# print('in the bar')
#
# def foo():
# print('in the foo')
# bar()
#
# foo()
# 匿名函数
# calc = lambda x:x*3
# print(calc(3))
# 第二个特性:高阶函数
import time
def bar():
t... |
a2170ba964c793d2d3b5d119ebf4d2fcb54ad49e | hicode/pythonFinance | /NewsFeedReader/parse2.py | 1,163 | 3.71875 | 4 | import feedparser
# Function to fetch the rss feed and return the parsed RSS
def parse_RSS(rss_url):
return feedparser.parse(rss_url)
# Function grabs the rss feed headlines (titles) and returns them as a list
def get_headlines(rss_url):
headlines = []
feed = parse_RSS(rss_url)
for newsitem in feed[... |
8cc569ce39c39e22eb3964a3aad1bac8e2001aa3 | C-CCM-TC1028-102-2113/tarea-4-A01026608 | /assignments/25TrianguloAsteriscos/src/exercise.py | 331 | 3.890625 | 4 |
def main():
#Escribe tu código debajo de esta línea
def trian(h):
j=1
for i in range (h,0,-1):
espacios= " "*i
asteriscos= '*' *j
j= j+1
print(espacios, asteriscos)
h= int(input('Dame un número:'))
trian(h)
if __name__=='__main__':
... |
37b98d69351965078ffc00f1d8512057b0808ff6 | beaulucas/ucsd_algo | /algorithmic_warmup/fib_mod.py | 917 | 3.6875 | 4 | # Uses python3
import sys
def get_fib_mod(n, m):
if n <= 1:
return n
# first thing to do is find the pisano sequence length for m
# need to get f_n % m (remainder) until we encounter a sequence of 0 1, then stop
# create empty list with base-case, every sequence starts with 0 1
lst_mod =... |
a806a3a68e91ddcdbd29bf4a167f1d3421f548e0 | mthompson36/newstuff | /Exercise6.py | 265 | 4.4375 | 4 | #This will ask for a string, then will tell you if it's a palindrome or not.
inputstring = input("Please enter a word: ")
if inputstring[::-1] == inputstring[0:]:
print(str(inputstring) + " is a palindrome")
else:
print(str(inputstring) + " is not a palindrome") |
8c13cf28bbf86783819ca931b96e930c7d341f58 | luckmimi/leetcode | /LC889.py | 782 | 3.765625 | 4 | # Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def constructFromPrePost(self, preorder: List[int], postorder: List[int]) -> Optional[TreeNode]:
if ... |
6fc152c38dda6da00f16c73a2e65008299fb2f34 | vesche/breakout-curses | /board.py | 707 | 3.640625 | 4 | # -*- coding: utf-8 -*-
from random import randint
from breakout import B_ROWS, B_COLS
COLORS = ['white', 'grey', 'red', 'green', 'yellow', 'blue', 'purple', 'cyan']
def checker(color_a, color_b):
board = []
code_a = COLORS.index(color_a)
code_b = COLORS.index(color_b)
for i in range(B_ROWS):
... |
a3c1b19f562f4d47872fa48a0dc17387cfa5974a | erpost/python-beginnings | /functions/math_function_basic.py | 156 | 3.96875 | 4 | n1 = input("Input a number: ")
n2 = input("Input a second number: ")
def addition(num1, num2):
return num1 + num2
print(addition(int(n1), int(n2)))
|
031a3e0649689319bea7018b347307ecac269fb9 | yzgyyang/coala-utils | /coala_utils/FileUtils.py | 1,947 | 4.1875 | 4 | import codecs
import tempfile
import os
def create_tempfile(suffix="", prefix="tmp", dir=None):
"""
Creates a temporary file with a closed stream
The user is expected to clean up after use.
:return: filepath of a temporary file.
"""
temporary = tempfile.mkstemp(suffix=suffix, prefix=prefix, d... |
6b9286ba9e95d50af62cddf6d7daf205eb277b44 | barleen-kaur/LeetCode-Challenges | /DS_Algo/Trees/findDuplicateSubtrees.py | 1,346 | 3.953125 | 4 | '''
Q. Find Duplicate Subtrees
Given the root of a binary tree, return all duplicate subtrees.
For each kind of duplicate subtrees, you only need to return the root node of any one of them.
Two trees are duplicate if they have the same structure with the same node values.
Input: root = [1,2,3,4,null,2,4,null,null,4... |
f585f0dd8411c2ec611ccca6c5d3c54ca2b9366e | SenthilKumar009/100DaysOfCode-DataScience | /Python/Programs/splitList.py | 197 | 4.03125 | 4 | sent = 'Print only the words that start with with s from the given sentance'
listStr = sent.split(' ')
print(listStr)
for val in listStr:
if val[0] == 's' or val[0] == 'S':
print(val) |
23602847dfcf94f96c5d890909138e524432b17d | ThanasisGio/PythonProjects | /oop/Bookstore/backend.py | 1,878 | 4.0625 | 4 | import sqlite3
class Database:
def __init__(self,db):
self.conn=sqlite3.connect(db)
self.cur=self.conn.cursor()
self.cur.execute("CREATE TABLE IF NOT EXISTS book (id INTEGER PRIMARY KEY,title text,author text,year integer,isbn integer) ")
self.conn.commit()
#have to... |
4179f730d62025e7eadfa64471f901a87851830c | SashaTlr/algos | /Chpt3_StacksQeueus/A_ThreeInOne_01.py | 1,898 | 3.5625 | 4 |
class Multistack:
def __init__(self, stackOne, stackTwo, stackThree):
self.topStack = [stackOne, stackTwo, stackThree]
self.array = [None] * (stackOne.capacity + stackTwo.capacity + stackThree.capacity)
class StackInfo:
def __init__(topIndex, capacity = 10):
self.top = topIndex
self.size = 0
self.ca... |
368900644e8b281dde8fdf61f3eab1adf85ade06 | emptybename/Ds-Algo | /tree/problems/height_balance.py | 1,326 | 3.578125 | 4 | class TNode:
def __init__(self, value=None):
self.left = None
self.right = None
self.val = value
class Implementation:
def __init__(self):
pass
@staticmethod
def add_left(node: TNode, value: int):
node.left = TNode(value)
@staticmethod
def add_right(no... |
7ca211aa0b6c43e5adbb37c7218bc4073ed71d36 | dfarfel/QA_Learning_1 | /List/List_task_5.4.py | 197 | 3.796875 | 4 | list1 = input("Enter your first list with comma: ")
list1 = list(list1.split(','))
list2 = input("Enter your second list with comma: ")
list2 = list(list2.split(','))
list3=list1+list2
print(list3) |
4fd24a53161b543bb0c2f166fe655275a71a02e5 | AZhengW/wanderer_work | /2020-4-25 work/work3/Role/TongLao.py | 529 | 3.5 | 4 | # 天山童姥类:
# 初始hp10000,攻击力800,当血量<5000时,攻击力翻三倍,血量扣除一半,只生效一次
import random
class Tonglao():
def __init__(self, hp, power):
self.name = "童姥"
self.hp = hp
self.power = power
def bao_nu(self):
self.hp = self.hp / 2
self.power = self.power * 3
print("童姥说:小鬼,你惹怒我了!!,... |
0a7ac1d9d4ce922c18ea5fdaaaa80f108ffcb8c9 | mzb2599/python | /polymorphism/p2.py | 195 | 3.921875 | 4 | def add(x, y, z=0, v=1):
return x + y + z+v
def add(x, y, z=5, v=10): #Function overwrites the previous function add
return x + y + z+v
print(add(2, 3))
print(add(2, 3, 5))
|
bd192f5e93874233122fa1da732b58a441723d95 | dsujant/Python | /kevin_bacon_number.py | 1,246 | 3.90625 | 4 | import psycopg2
# Parameters for accessing movies db
params = {
'dbname': 'movies',
'user': 'dsujanto'
}
### Set up connection
conn = psycopg2.connect(**params) # Create a connection object
cur = conn.cursor() # Create cursor object
print("Let's find Kevin Beacon!")
guess = input("Enter an actor name:... |
fc38c200b9343a6cb4c9b6445a846ce4c453e550 | Sruthi123-dg/LuminarDjangoPython | /Luminarproject/flowcontrols/decisionmakingstmnts/largestamongtwo.py | 189 | 4.1875 | 4 | num1=int(input("enter the number1"))
num2=int(input("enter the number2"))
if(num1>num2):
print(num1,"is largest")
elif(num1==num2):
print("equal")
else:
print(num2,"is largest") |
fe5041d904ce18f544f76496daf2485f604e44b0 | youandvern/Excel-Proj-Name-Matching | /projectNameReorder - refactor.py | 6,525 | 3.734375 | 4 | """
Created on Tue Oct 13, 2020
@author: Andrew-V.Young
Match project desctiption to project number
"""
import sys
import pandas as pd
from openpyxl import load_workbook
# character matching count function
# https://www.geeksforgeeks.org/python-count-the-number-of-matching-characters-in-a-pair-of-st... |
7f40dfbac1224a4e52599c3aabd14813d2c2a093 | mohsindalvi87/bearsnacks | /computer-vision/anaglyphs/test.py | 2,847 | 3.515625 | 4 | #!/usr/bin/env python3
# https://en.wikipedia.org/wiki/Anaglyph_3D
# https://github.com/miguelgrinberg/anaglyph.py/blob/master/anaglyph.py
import numpy as np
import cv2
# declare various color blending algorithms to mix te pixels
# from different perspectives so that red/blue lens glasses
# make the image look 3D
mix... |
755cf4ddb6a0afc054a3315426d379be36ec6e00 | kamalkkv/guvigithub | /1_2_5.py | 105 | 3.609375 | 4 | n=int(input())
q=int(input())
for i in range(n+1,q):
if(i%2==0):
print(i,end=" ")
|
6accd9183555385c76312f72135e1e8df9b91efc | PhoebeGarden/python-record | /廖雪峰 notes/recursive function.py | 800 | 4.21875 | 4 | #!/usr/bin/env python3
# -*- coding:utf-8 -*-
def fact(n):
if n == 1:
return 1
return n * fact(n-1)
print(fact(1))
print(fact(5))
print(fact(100))
#为了防止递归栈溢出,需要通过尾递归优化
#尾递归是指,在函数返回的时候只调用自身本身,上面的函数不是,因为返回的是乘积
def fact(n):
return fact_iter(n,1)
def fact_iter(num, product):
if num == 1:... |
7345621eac423eef1b9962241828e9581ff0ea13 | mathildebrosseau/INF1007 | /TP2/exercice3.py | 736 | 3.875 | 4 | import math
constanteGravitationnelle = 9.81
def exercice3(hauteurInitiale, coefficientDeRebond):
#TODO: faites vos calculs et mettez le resultat dans la variable 'nombreDeRebonds'
V = math.sqrt(2 * constanteGravitationnelle * hauteurInitiale)
nombreDeRebonds = 0
while hauteurInitiale >= 0.01:
... |
f6a77df2c84b614f37b6b529e79760cd62b0b222 | ansarisaeem00/Mtech | /aac/expt4/bh5.py | 2,942 | 3.53125 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sun Nov 3 00:07:27 2019
@author: saeem
"""
class BinHeap:
def __init__(self):
self.heapList = [0]
self.currentSize = 0
def percUp(self,i):
while i // 2 > 0:
if self.heapList[i] < self.heapList[i // 2]:
... |
5038a386261870e4de436906781db9a5253eb9db | sanjsriv98/coding | /rai.py | 142 | 3.71875 | 4 | def isPalindrome(a):
if(len(a)==1):
return 1
elif len(a)==2:
return a[0]==a[1]
if a[0]==a[-1]:
return isPalindrome(a[1:-1])
|
bf048640dfe130b1eb6b844b68a6810909e14f2c | rifertv/-2-3 | /main.py | 413 | 4.15625 | 4 | def easy_unpack(elements: list) -> list:
"""
returns a tuple with 3 elements - first, third and second to the last
"""
i = [0, 2, -2]
elements = [elements[x] for x in i]
return elements
if __name__ == '__main__':
assert easy_unpack([1, 2, 3, 4, 5, 6, 7, 9]) == [1, 3, 7]
assert easy_unpack([1, 1... |
0674fd2e8bd686abf9b8e0be9b54388d720dcdba | ddp-danilo/ddp-pythonlearning1 | /sm7ex1.py | 251 | 4.1875 | 4 | #desenho que usa '#' para fazer quadrados
largura = int(input("digite a Largura: "))
altura = int(input("digite a altura: "))
while altura > 0:
ll = largura
while ll > 0:
print("#", end='')
ll -= 1
print()
altura -= 1
|
6ebe90e0d556e61ee99d5bfe61730974a54f8f9a | am1089/Python-Exercises | /ListOrganizer.py | 582 | 4.34375 | 4 | # Code to sort multiple lists
# input fields seperated by commas
allip = []
iplist = []
print("Input some names, ages, heights")
# Collect all inputs until an empty line is found.
while True:
ip = input()
if ip == "":
break
# Split into strings and then into integers
iplist = ip.split(',')
... |
a1d35894e5fd1f997be8439a17cc3ed17d895e2c | rcvenky/hacktoberfest2020 | /Solution/Python/LinearSearch.py | 436 | 4.0625 | 4 | def linearsearch(arr,size,key):
for i in range(len(arr)):
if arr[i]==key:
return i
return -1
size=int(input("Enter size of array: "))
arr=[]
for i in range(size):
arr.append(int(input("Enter the element: ")))
key =int(input("Enter element to be searched: "))
ans=linear... |
8e4c710951518949e91577ff31d8a79dce045e6e | asishraz/banka_sir_notes | /ch_1/main.py | 106 | 4 | 4 | #1. wap to input two numbers and print their sum
a = int(input())
b = int(input())
print("Sum is: ", a+b) |
2e115fd623d6d7c98821aa58ed696d53ff57a8a7 | fdl9/fdl9python | /PaulTutorial/Lesson1/read_file.py | 338 | 3.59375 | 4 | import os
import sys
#open file to read
to_read_file_pointer = open("to read.txt", 'r')
a=0
for line in to_read_file_pointer:
a = a + 1
#print("Line:{0}".format(line))
#print("index value is {1}, Line value is {0}".format(line,a))
print("Line value is {0}, index value is {1}".format(line,a))
to_read_fi... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.