blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
5fb7f49ac5f9cfc8d798dd3d3a1584b8bb9a7dc4 | Jpeck219/nyc-mhtn-ds-060319-lectures | /Mod_1/rolling-stones/functions1.py | 7,955 | 3.921875 | 4 | import csv
from collections import Counter
import json
with open('data.csv') as f:
# we are using DictReader because we want our information to be in dictionary format.
rolling_stones_list = list(csv.DictReader(f))
#print(rolling_stones_list[:4])
#Find by name - Takes in a string that represents the nam... |
600dcfd8d809520bfbe2af0ca94293411206eac9 | bishkou/leet-code | /Arrays 101/moveZero.py | 439 | 3.765625 | 4 | from typing import List
def moveZeroes(nums: List[int]) -> None:
j = 0
i = 0
while i < len(nums):
while j < len(nums) and nums[j] != 0:
j += 1
if i > j and i != 0:
nums[j] = nums[i]
nums[i] = 0
i += 1
else:
i += 1
if __n... |
7fac4084c82ea280dea4afa3bbce686dd6df84a7 | yusun-hci/LeetCodeDaily | /43_Multiply_Strings_20180613.py | 1,383 | 3.75 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Jun 13 01:58:42 2018
@author: lifanhong
The length of both num1 and num2 is < 110. —— what's the point of this?
test case:
when output = "0"
3141592653589793238462643383279502884197169399375105820974944592
271828182845904523536028747135266249... |
b6af5b818a08f0e9da96acb7bfca724c3495e11b | xiongfeihtp/NLP-embedding | /ChineseWordSegment/sentence_manager/sentence_embedding.py | 4,809 | 3.703125 | 4 | '''
Embedding a sentence into a vector.
By the approach of described in 'A SIMPLE BUT TOUGH-TO-BEAT BASELINE FOR SEN- TENCE EMBEDDINGS', Sanjeev Arora, et al.
But with some modification / addition.
If there are some words not exists in the vocabulary, give it a random value with uniform distribution in space
D^w
... |
8e485f833c51fa1d0f2919072fb0025503c0eb9d | renedekluis/HBO-ICT_python_2B | /Week5/Opdracht1/main.py | 1,010 | 3.890625 | 4 | import sys
sys.path.append("../")
from BFS import *
def is_connected(G):
"""
This function checks if graph is fully connected.
Parameters
----------
G: graph
Dictionary of graph connections.
Returns:
--------
is_connected : Boolean
returns if the graph is fully connected or not.
Example:
------... |
7d866e70906280b49b0707860ca6b406e799fb5e | liuminghao0830/leetcode | /609_Find_Duplicate_File_in_System.py | 755 | 3.625 | 4 | import collections
class Solution(object):
def findDuplicate(self, paths):
"""
:type paths: List[str]
:rtype: List[List[str]]
"""
# Time complexity: O(m * n), m: len(paths), n: files in each paths
# Space complexity: O(m * n)
group = collections.defaultdict(l... |
f743236c17a169f9636f8fc561c8277d01e60b57 | cmcahoon01/SpaceRogue | /ships/projectile.py | 1,326 | 3.53125 | 4 | from ships import ship, projectile
import pygame
from math import sin, cos, atan2, pi, degrees, sqrt
class Projectile(ship.Ship):
def __init__(self, angle, allied, control):
super().__init__(control)
self.hitbox_radius = 3
self.angle = angle
self.speed = 30
self.life_time =... |
50d5688036eb9886bfda2247a497693d84d64223 | TeyMeiQun/DPL5211Tri2110 | /lab5.4.py | 506 | 3.734375 | 4 | #student id:1201200152
#STUDENT NAME:TEY MEI QUN
def rectangle(width,length):
r_area=width*length
return r_area
def traingle(width,length):
t_area=(width*length)/2
return t_area
def main():
width=float(input("Enter width:"))
length=float(input("Enter length:"))
rarea=rectangle(wid... |
d24063a833f26fca5b39341b4acc731339f702c4 | gsrr/leetcode | /hackerrank/week_of_code_34/test_same_occurrence.py | 993 | 3.609375 | 4 | #!/bin/python
import sys
import collections
import itertools
import json
def findsubsets(S,m):
return set(itertools.combinations(S, m))
def same_occurrence(q, dic):
cnt = 0
for s in dic.keys():
ss = json.loads(s)
if ss.get(str(q[0]),0) == ss.get(str(q[1]),0):
cnt += dic[s... |
b944f0d728a7d8d854a955798670d1777f050940 | Codebeastdave/GUI-Calculator-project | /scratch_1.py | 1,792 | 3.5625 | 4 | #
class Calc:
def __init__(self, x, y, operator):
self.minus = "-"
self.plus = "+"
self.x = x
self.y = y
self.operator = operator
def add(self):
assert self.operator == self.plus
results = str(self.x) + self.operator + str(self.y)
return "{0} = {... |
4fb7bf8ff0068a78e5cdef5749544eeba8488908 | HunterProgram22/Football_game_project | /Football_game_project/firstdown.py | 1,094 | 3.53125 | 4 | # coding: utf-8
class team(object):
# Class with attribute of a team on a yardline
def __init__(self, yardline = 20):
self.yardline = yardline
def yardchange(self, yardchange):
self.yardline = self.yardline + yardchange
def printyard(self):
print(self.yardline)
class series(team):
# a series is an sub... |
b5e28408c67fc71edc6933233f8d3497af93c85b | kgremban/leetcode | /0066-plus-one.py | 635 | 3.546875 | 4 | from typing import List
class Solution:
def plusOne(self, digits: List[int]) -> List[int]:
if digits[-1] < 9:
digits[-1] += 1
return digits
index = len(digits) - 1
while index >= 0:
if digits[index] == 9:
digits[index] = 0
... |
ec1aef56d737bbe43b2dfd4041bdf49234d209e9 | nihal223/Python-Playground | /CTCI/Chapter4/01-route-between-nodes.py | 1,121 | 3.8125 | 4 | import unittest
from collections import defaultdict
class Graph():
def __init__(self, vertices):
self.V = vertices # No. of vertices
self.graph = defaultdict(list) # default dictionary to store graph
def add_edge(self, u, v):
self.graph[u].append(v)
def is_reachable(self, s, d)... |
058c05d8d570e68aa48a662ff7dbe77e5831c1f7 | iamreebika/Python | /Datatypes19.py | 175 | 3.875 | 4 | def smallest_num_in_list( list ):
min = list[ 0 ]
for a in list:
if a < min:
min = a
return min
print(smallest_num_in_list([12, -10, -8, 90]))
|
55b9acd501a97cf73865fe063f6f293c25f9c88e | salman079/python | /helloworld/test.py | 691 | 3.671875 | 4 | # class Point ():
# def __init__(self,x=0,y=0):
# self.x=x
# self.y=y
# def __sub__(self,other):
# x=self.x+other.x
# y=self.y+other.y
# return Point(x,y)
# p1 = Point(3,4)
# p2 = Point(1,2)
# result = p1-p2
# print(result.x,result.y)
# class Parent ():
# def __init... |
94f4324e61ccbecb98243a0758c862745f330aec | adnanzaidi/Image-Classification | /More_than_two_Classes/CNN_Classification_Multi_Class.py | 3,404 | 3.671875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Thu Mar 1 11:13:51 2018
@author: pranavjain
This program predicts the type of flower from an image.
"""
# Importing the Keras libraries and packages
from keras.models import Sequential
from keras.layers import Conv2D
from keras.layers import MaxPooling2D
from ke... |
c3d15173a7b98b1b05b87de66cd077fe525e2787 | cloveses/myhouse | /mysimple/q4.py | 877 | 3.9375 | 4 | class Person:
def __init__(self, name, age, vocation, salary):
self.name = name
self.age = age
self.vocation = vocation
self.salary = salary
def introduce(self):
print('name:', self.name)
print('age:', self.age)
print('vocation:', self.vocation)
def... |
9c9e87b5267682e91a27a9c8ef5e0d0b045f94f8 | kwangminini/Algorhitm | /BAEKJOON/1927Solution.py | 540 | 3.609375 | 4 | """
문제 제목 : 최소 힙
문제 난이도 : 하
문제 유형 : 힙, 자료구조
최소 힙의 기본적인 기능을 구현
heapq 라이브러리를 이용하면 간단히 힙 구현 가능
배열로 하니 시간초과 -> 최소 힙
"""
import heapq
n=int(input())
heap=[]
result=[]
for _ in range(n):
data = int(input())
if data == 0:
if heap:
result.append(heapq.heappop(heap))
else:
result.... |
6b389b6f90bde59b27becfae1a69eb94e92d90c9 | afonso-21902703/pw-ficha3 | /pw-python-03-main/exercicio_1/analisa_ficheiro/acessorio.py | 539 | 3.703125 | 4 | def pede_nome()->"String":
while True:
teclado = input('Insira o nome do ficheiro: ')
try:
open(teclado)
for n in teclado:
if n =='.':
tecladosplit = teclado.split('.')
if tecladosplit[1] == 'txt':
... |
2c258cabcf17d8cc9ce3c9b896b8dc9d5dfd79ef | StefanDimitrovDimitrov/Python_Fundamentals | /Python_Fundamentals/Fundamentals level/13.Exaam prep/05_exam.py | 640 | 3.859375 | 4 | guest_singer_price = int(input())
command = ""
cover = 0
total_guest = 0
is_restauran_is_full = False
while not is_restauran_is_full:
command = input()
if command == "The restaurant is full":
is_restaurant_is_fill = True
break
else:
num_guest = int(command)
total_guest += num... |
a44dbfdfeff0b83a98b784ae9b5a4671bbda19ba | JakeNTech/GCSE-Python-Code | /Input/Welcome.py | 101 | 3.828125 | 4 | name = input("What is your name, please? ").title()
print("Hello", name ,"welcome to the doctors!!")
|
ee8af45c88422cbce4b651fa6aa1cb20c114fcc2 | swapnil-sat/webwing-code | /ManthanBore/Flow Control/Iterative Statement/using_for.py | 826 | 4.0625 | 4 | # l=[1,2,3,4,5]
# print(l)
# for i in l :
# print(i)
# l=[1,2,3,4,5]
# print(l)
# for i in l :
# if i % 2 == 0 :
# print(i,"is even number")
# for i in range (1,10,1):
# print(i)
# for x in range (1,10,2) :
# print(x)
# for i in range (20,0,-1) :
# print(i)
# for x in range (20,0,-3) :
... |
fc22320009d7508bf73cfb624f78bc0f4a008513 | AbhinavTC/My-python-programs | /add and multipy numbers.py | 378 | 4.125 | 4 | # function to add two numbers
def add_numbers(num1, num2):
return num1 + num2
# function to multiply two numbers
def multiply_numbers(num1, num2):
return num1 * num2
number1 = 5
number2 = 30
sum_result = add_numbers(number1, number2)
print("Sum is", sum_result)
product_result = multiply_number... |
81d37b3bbaaefe8e1c67b2b0b278abbac4db5847 | Preetpalkaur3701/python-programmes | /primeinterval.py | 386 | 3.90625 | 4 |
lower = input("first number")
upper= input("secong number")
check=False
print ("prime numbersbetween",lower, "and",upper, "are:")
for num in range(lower, upper+1):
if num > 1:
for i in range(2,num):
if (num % i) == 0:
check=True
if check == False:
print num
check=False
""" if num > 1:
for i in range... |
3f435e4878ea28ef2aeb00730ba57034c8511839 | hejazizo/stackoverflow-bot | /send_email.py | 1,128 | 3.671875 | 4 | """The first step is to create an SMTP object, each object is used for connection
with one server."""
import smtplib
from validate_email import validate_email
import emoji
def send_mail(receiver, randnum):
is_valid = validate_email(receiver)
if not is_valid:
return "Invalid email address"
elif is... |
5a8729215c8f23ba1de3b3935dce950df42aaf63 | chuzhinoves/DevOps_Python_HW3 | /3.py | 292 | 4 | 4 | """
Реализовать функцию my_func(), которая принимает три позиционных аргумента,
и возвращает сумму наибольших двух аргументов.
"""
def my_func(a, b, c):
return sum([a, b, c]) - min([a,b,c])
|
32041aaefd77c794dbdaee692f199ce82ccb3a71 | manjumugali/Python_Programs | /ObjectOrientedPrograms/Inventory.py | 986 | 3.75 | 4 | """
******************************************************************************
* Purpose: Reading JSON File
*
* @author: Manjunath Mugali
* @version: 3.7
* @since: 27-01-2019
*
******************************************************************************
"""
import json
from OOPS_Utility.Test_Oops_Utility imp... |
4499a7dc3f8ff6bf7a769ef1134293b24be3c26a | rv-nataraj/myprograms | /prog16.py | 122 | 4 | 4 | n=input("Enter a value : ")
n=int(n)
sum=0
for x in range(1,n,1):
sum=sum+x
print("Sum of first ",n," numbers is ",sum)
|
55db07ef1eae861e716bde77d0c564237dfd8e5d | flaviogpacheco/python-520 | /aula1_3.py | 419 | 3.9375 | 4 | #!/usr/bin/python3
# ==, !=, <, <=, >, >=
# Se o numero resultado da soma for maior 100
# Escrever: "Que numero grandão..."
# Caso contrário: "Que numero pequeno..."
n1 = int(input('Digite o primeiro número: '))
n2 = int(input('Digite o segundo número: '))
n3 = n1 + n2
print(n3)
if n3 > 100:
print('Que número... |
092731e968adb8cda2fa5ffb12e4b8acc4295f40 | sinegami301194/Python-HSE | /6 week/mergeLists.py | 488 | 3.78125 | 4 | import random
A = list(map(int, input().split()))
B = list(map(int, input().split()))
def quicksort(nums):
if len(nums) <= 1:
return nums
else:
q = random.choice(nums)
l_nums = [n for n in nums if n < q]
e_nums = [q] * nums.count(q)
b_nums = [n for n in nums if n > ... |
33402df1245439cecdcee3555d575ba4e21cfe19 | sichkar-valentyn/Working_with_files_in_Python | /Files_in_Python.py | 5,364 | 3.984375 | 4 | # File: Files_in_Python.py
# Description: Examples on how to work with files in Python
# Environment: PyCharm and Anaconda environment
#
# MIT License
# Copyright (c) 2018 Valentyn N Sichkar
# github.com/sichkar-valentyn
#
# Reference to:
# [1] Valentyn N Sichkar. Examples on how to work with files in Python // GitHub ... |
c015680a51cbe0d087fb805a62a12365c797a8c8 | larryworm1127/tic-tac-toe-python | /ttt_game/ttt_computer.py | 1,575 | 3.765625 | 4 | """
Mini-max Tic-Tac-Toe Player
"""
from typing import Tuple
from .ttt_board import *
# Scoring values
SCORES = {PLAYERX: 1,
DRAW: 0,
PLAYERO: -1}
def get_move(board: TTTBoard, player: int) -> Tuple[int, int]:
"""Make a move on the board.
Returns a tuple with two elements. The first el... |
285915d6bbfc1abace271907ca5e79581e09f8d9 | dimmxx/codecademy | /FileIO_WithAs.py | 176 | 3.59375 | 4 | with open("text.txt", "w") as textfile:
textfile.write("Success!")
with open("text.txt", "w") as my_file:
if not my_file.closed:
my_file.close()
my_file.write("OK") |
0f969719b70c5aed7ca258b0475bd363209f3174 | Aasthaengg/IBMdataset | /Python_codes/p03796/s491879310.py | 237 | 3.6875 | 4 | #-*-coding:utf-8-*-
import sys
input=sys.stdin.readline
def main():
n = int(input())
mod = 10**9+7
power=1
for i in range(1,n+1):
power*=i
power%=mod
print(power)
if __name__=="__main__":
main() |
3f19872efe0ba6446572452c7aab7f33ee8d4d37 | gabastil/reports | /pyExperiments/get_pass.py | 545 | 3.53125 | 4 | from Tkinter import *
def getpwd():
password=''
root=Tk()
pwdbox=Entry(root, show='*')
def onpwdentry(evt):
password=pwdbox.get()
root.destroy()
def onokclick():
password=pwdbox.get()
root.destroy()
Label(root, text='Password').pack(side='top')
pwdbo... |
ad50aaf1365bea9d1a4f2eb42bd51b29d7dcbdf9 | bboyle34/PythonBeginnerProgramming | /ch6-examples/UsefulTurtleFunctions.py | 1,961 | 4.34375 | 4 |
import turtle
# Draw a line from (x1, y1) to (x2, y2)
def drawLine(x1, y1, x2, y2):
turtle.penup()
turtle.goto(x1, y1)
turtle.pendown()
turtle.goto(x2, y2)
# Write a text at the specified location (x, y)
def writeText(s, x, y):
turtle.penup() # Pull the pen up
turtle.goto(x, y)
... |
16fa481e0b0870cb188c2037f33998716719c2a7 | Akagi201/learning-python | /misc/list.py | 230 | 4.5625 | 5 | #!/usr/bin/env python
# Python 3: List comprehensions
fruits = ['Banana', 'Apple', 'Lime']
loud_fruits = [fruit.upper() for fruit in fruits]
print(loud_fruits)
# List and the enumerate function
print(list(enumerate(fruits)))
|
9facb78e4df94052f0cf7bc3ac339194193d70c8 | Streamline27/TSI-Python-LabWorks | /LabTasks/Task4.py | 644 | 4.1875 | 4 | __author__ = 'Vladislav'
# Some types in python are mutable some are not.
# this is the only way to change variable inside function.
def mutable_pow(a):
a[0] **= 2
print "Inside mut_pow "+ str(a[0])
# In this way variable wont be mutated
# but will be returned.
# This is a nice way to go!
def function_pow(... |
ee3b8fd6e99cedaeb2e322bbb7b94ca8e2cfda34 | tcano2003/ucsc-python-for-programmers | /code/lab_03_Functions/lab03_4.py | 907 | 4.40625 | 4 | #!/usr/bin/env python3
"""Write a DoBreakfast function that takes five arguments:
meat, eggs, potatos, toast, and beverage. The default
meat is bacon, eggs are over easy, potatos is hash browns,
toast is white, and beverage is coffee.
The function prints:
Here is your bacon and scrambled eggs with home fries
and rye... |
d88c8949572368324be28df108c36d3482e17da2 | zheyuanKelvin/leetcode_template | /binary_search.py | 485 | 4.03125 | 4 | #binary search:
'''
Points:
update start as mid + 1
return start at the end
f(mid): three sum questions, 'sum == target'
g(mid): usually 'nums[mid] > target'
'''
def binary_search(start, end):
while start < end:
mid = start + (end - start) // 2
if f(mid): #optional
return mid
... |
503376e36f2b23c9bda0a60c15746a38192c0afe | gulci-poz/lpthw | /ex1.py | 6,468 | 4.09375 | 4 | # -*- coding: utf-8 -*-
# linia z kodowaniem musi być pierwsza, nawet przed import
import math
print "Hello World!"
print "Hello Again"
print "I like typing this."
print "This is fun."
print "Yay! Printing."
print "I'd much rather you 'not'."
print 'I "said" do not touch this.'
print u"Sebastian Gulczyński"
print u"ę... |
83ea96f0e8792231d2532175a4b553e32b8b6f1c | ChicksMix/programing | /unit 7/hickshouse.py | 1,796 | 3.984375 | 4 | import turtle
def main():
t=turtle.Turtle()
t.hideturtle()
roof(t)
house(t)
door(t)
windows(t)
def roof(t):
t.pencolor("black")
t.pensize(2)
t.fillcolor("brown")
t.up
t.begin_fill()
t.goto(-100,0)
t.down()
t.goto(100,0)
t.goto(0,150)
t.goto(-100,0)
t.... |
22e8fee1b519831e83455f6505c1d90a1fa37a6d | vikasbaghel1001/Hactoberfest2021_projects | /python project/Binary_search.py | 424 | 3.765625 | 4 | def search(a:list,element,x,y):
mid=y+1//2
if(a[mid]==element):
return mid
elif(element>a[mid]):
return search(a,element,mid+1,y)
elif(element<a[mid]):
return search(a,element,0,mid-1)
else:
return "not found"
import random
L1=[x fo... |
769b8ad326294ddf17b174be872d2a2885bdd24e | mohnoor94/ProblemsSolving | /src/main/python/staircase.py | 3,075 | 4.03125 | 4 | def number_of_ways(n):
"""
*** 'Amazon' interview question ***
Staircase problem with allowed steps of only 1 or 2 at a time.
Problem statement and more details: https://youtu.be/5o-kdjv7FD0
"""
if n == 0 or n == 1:
return 1
result = s1 = s2 = 1
for i in range(2, n + 1):
... |
59a574c8ed8c2475affcde251e4417aad71eada6 | akraturi/sem6 | /nft/percept.py | 1,550 | 3.53125 | 4 | import math
import time
def activation_function(x):
if x >= 0:
return 1
else:
return 0
def sigmoidal_activation_function(x):
return 1/(1+math.exp(-x))
w1 = -0.1
w2 = 0.1
bias = 0.3
learning_rate = 0.1
patterns = []
gate = int(input("Press 1 for AND\n Press 2:NAND\n Press 3:OR:"))
swit... |
0fc094f5a94ee3477608557169596f5018f3fd6f | Kristyli2009/MatrixMultiplication | /codes/RegInputFromFile.py | 3,268 | 4.125 | 4 | #!/usr/bin/env python3
import time
import csv
def input_data():
""" A function to read data from a file and store them in a list and return it"""
numbers = []
data_file = input("Please enter the file name with extension: ")
with open(data_file) as file:
for line in file:
numbers.ap... |
08010dc7047c15c6c0fe43803392c27fc312cbbf | kpratapaneni/Masters_Classwork | /AI_480/hw7/agents.py | 2,333 | 4.15625 | 4 | from abc import abstractmethod
class Agent(object):
def __init__(self, name):
self.name = name
def __str__(self):
return "Agent_" + self.name
@abstractmethod
def will_buy(self, value, price, prob):
"""Given a value, price, and prob of Junk,
return True if you wa... |
9a42b1a4a7a2eaa90fcad2ef6c5d14c066b1a121 | kristaps/aoc2020 | /day09.py | 1,634 | 3.921875 | 4 | #!/usr/bin/env python3
from argparse import ArgumentParser
from typing import List
from itertools import combinations
def check_number(n: int, latest: List[int]):
# Reduce combination count by eliminating numbers that are
# too large to sum up to n with any of the other numbers
max_valid = n - min(latest... |
531f18c778cadb16a132cd6cd778446fe0d1196b | Hibatallah98124/emoji | /emoji.py | 490 | 3.625 | 4 | import turtle
lion=turtle.Turtle()
lion.up()
lion.goto(0,-100)
lion.down()
lion.begin_fill()
lion.fillcolor("yellow")
lion.circle(100)
lion.end_fill()
lion.up()
lion.goto(-67,-40)
lion.setheading(-60)
lion.width(5)
lion.down()
lion.circle(80,120)
lion.fillcolor("black")
for i in range(-35,105,70):... |
387736725b1aeb39c7eb1ec6dc3dc3671f6a65e1 | ornelasf1/python_interpreter2 | /hw4/hw4_testcase4.py | 138 | 3.625 | 4 | a = 5
b = 3
c = 2
if a>3:
print("1 conditiion satified")
else:
print("nothing satisfied")
else:
print("nothing satisfied 2")
|
f78f453bb1377dcd960c2738449f179ab4bb3365 | WeaselE/Small-Programs | /Infinite Divide By Two.py | 215 | 3.5 | 4 | from decimal import *
from time import sleep
def divide_by_two(nl):
num = nl / 2
return num
getcontext().prec = 100
n = Decimal(1.0)
while n != 0:
n = divide_by_two(n)
print(n)
# sleep(0.025)
|
f75d1f107990ba8eccd6f1593dfef5c1b459b67d | bnconti/Exercises-Primer-Python | /ch4/24_Bernoulli_trials.py | 1,040 | 3.984375 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# Exercise 4.24: Compute probabilities with the binomial distribution
# Author: Bruno N. Conti
"""
SAMPLE RUN:
Probability of getting 2 heads when flipping a coin 5 times: 31.25%
Probability of getting 4 ones in a row when throwing a die 4 times: 0.08%
Probability of brea... |
2a1e4ada9aaf7b254530a78425a428cab7d7ed9a | TheScouser/algorithms | /arrays/6_string_compression.py | 485 | 3.75 | 4 | def compress(string):
compressed = []
current_char = string[0]
count = 0
for i in range(len(string)):
if current_char != string[i]:
compressed.append(current_char+str(count))
count = 0
current_char = string[i]
count += 1
elif i == len(string) - 1:
count+=1
compressed.append(current_char+str(co... |
e251aca45100a6f3ab8825581eeaca755657d085 | jakobend/adventofcode | /day4/__main__.py | 523 | 3.890625 | 4 | """
Runs doctests and then calculates the answer to the puzzle.
"""
import sys
import os
import doctest
from . import is_simple_passphrase, is_anagram_passphrase
with open(os.path.join(os.path.dirname(__file__), "input.txt"), "rU") as f:
PASSHPHRASES = [
line.strip().split(" ")
for line in f
]... |
80558d10df9675497d9bf179edd5670252ca2fa4 | QuantumMagician/Python_Challenge | /Day04/day04.functions.py | 827 | 4.125 | 4 | # built-in function lists
"""float(), type(), int(), input(), """
# def doesn't invoke automatically
x = 10
print('Aloha')
def name():
print("I'm a quantummagician, and I love math.")
print('OK')
x = x+4
print(x)
# parameter is a variable in the function
def hello(word): #word=parameter
if word == 'ed': #'e... |
6ecd881844e228170499941b56ea62da32718cab | Goular/PythonModule | /05廖雪峰Python教程/04.高级特性/02迭代.py | 114 | 3.609375 | 4 | for x, y in [(1, 1), (2, 4), (3, 9)]:
print(x, y)
for i,value in enumerate(['A','B','C']):
print(i,value) |
5fa47e9c73a151e96277a306b6d4f1606e09338a | AJCaceres/Python-is-easy | /Homework_5.py | 186 | 4.0625 | 4 |
for numbers in range(1,100):
if (numbers%3 == 0) & (numbers%5==0):
print("FizzBuzz")
elif numbers%3 == 0:
print("Fizz")
elif numbers%5 == 0:
print("Buzz")
else: print(numbers) |
54c83d4135e991d246fd0767f85ee4f6c0fd543e | CrzRabbit/Python | /leetcode/0645_E_错误的集合.py | 1,194 | 3.5625 | 4 | '''
集合 s 包含从 1 到 n 的整数。不幸的是,因为数据错误,导致集合里面某一个数字复制了成了集合里面的另外一个数字的值,导致集合 丢失了一个数字 并且 有一个数字重复 。
给定一个数组 nums 代表了集合 S 发生错误后的结果。
请你找出重复出现的整数,再找到丢失的整数,将它们以数组的形式返回。
示例 1:
输入:nums = [1,2,2,4]
输出:[2,3]
示例 2:
输入:nums = [1,1]
输出:[1,2]
提示:
2 <= nums.length <= 104
1 <= nums[i] <= 104
'''
from typing import Li... |
660725efc46a30ba612bb05271872ea165265142 | virgax7/ProjectEuler | /src/questions-21-40/q30.py | 705 | 3.75 | 4 | # Surprisingly there are only three numbers that can be written as the sum of fourth powers of their digits:
#
# 1634 = 14 + 64 + 34 + 44
# 8208 = 84 + 24 + 04 + 84
# 9474 = 94 + 44 + 74 + 44
# As 1 = 14 is not a sum it is not included.
#
# The sum of these numbers is 1634 + 8208 + 9474 = 19316.
#
# Find the sum of all... |
9e116279884fc61ebe0d86019e84b49c89599ba3 | igotaname6/roguelike_game | /hot_cold.py | 2,321 | 4.1875 | 4 | import random
import time
def user_input(n):
correct_number = None
while correct_number is None:
try:
number = int(input("Its your {} attempt,type a three-digit number: ".format(n)))
if number > 999 or number < 100:
raise ValueError
correct_number = ... |
dd334fe884f7617c70978550a6879d2be2fbba8b | wobuxiangtong/algorithm | /basics/sort/quick_sort.py | 898 | 3.796875 | 4 | #趣图
#https://idea-instructions.com/quick-sort/
def quick_sort_1(arr):
if len(arr) <= 1:
return arr
pivot = arr[len(arr) // 2]
left = [x for x in arr if x < pivot]
middle = [x for x in arr if x == pivot]
right = [x for x in arr if x > pivot]
return quick_... |
6d4e7d1ca8d3d46685c9719180aca8fca60d7586 | phucodes/lc101-git | /vigenere.py | 1,027 | 3.671875 | 4 | from helpers import alphabet_position, rotate_character
def encription_key(text, rot):
counter = 0
enc_key_phrase = ""
enc_key_list = []
counter = ((len(text)//len(rot))+1)
enc_key_phrase += rot * counter
enc_key_list = list(enc_key_phrase)
return enc_key_list
def encrypt(text, rot)... |
ad196e72f7132a36df0916d1bbcc91fb89de940c | Raj-Bisen/python | /SumofFactors.py | 739 | 4.09375 | 4 | # Accept number from user and return addition of its factors
# input : 6
# output : 1 + 2 + 3 = 6
def AdditionFactors(no):
iCnt = 1
iSum = 0
for i in range(1,int(no/2)+1): # no1 = 6
if no % iCnt == 0:
iSum = iSum + iCnt
iCnt = iCnt +1
return iSum
... |
136d4734f6ce4421381dafd02a080ba2770fe212 | tkhura5/FlightsDelay_StatisticalModels | /Scripts/Models/Model_Time_Series.py | 625 | 3.5625 | 4 | import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.dates import DateFormatter, WeekdayLocator, DayLocator, MONDAY,YEARLY
import datetime
from datetime import *
#Reading the dataframe
df = pd.DataFrame()
df=pd.read_csv('flights.csv',low_memory=False)
df['DEPARTURE_DELAY'] = df['DEPAR... |
6ec6cbb8822930d8a97246919869e9599fbcf811 | krohak/Project_Euler | /LeetCode/Medium/Set Matrix Zeroes/revise/1.py | 1,342 | 3.578125 | 4 | def set_matrix_zeroes(arr):
m = len(arr)
n = len(arr[0])
print(m, n)
row_zero = 0
col_zero = 0
i = 0
while i<m:
if arr[i][0] == 0:
col_zero = 1
i+=1
j = 0
while j<n:
if arr[0][j] == 0:
row_zero = 1
j+=1
# print(row... |
dae23fdb2cbcd508a0daab4c28aad6331075e421 | partho-maple/coding-interview-gym | /leetcode.com/python/334_Increasing_Triplet_Subsequence.py | 1,263 | 3.859375 | 4 |
# Solution 1: Two pointer technique
class Solution(object):
def increasingTriplet(self, nums):
"""
:type nums: List[int]
:rtype: bool
"""
firstNum, secondNum = float('inf'), float('inf')
for num in nums:
if num <= firstNum:
firstNum = n... |
f6c14f0c94dabce371433e8f01adc168551d86b6 | aztlanleuc/stile-interview-project-task | /Devon McKenzie Project Team Task.py | 4,529 | 4.53125 | 5 | '''
Devon McKenzie
Project Team Task
String recognition
'''
# get the required input from the user
filename = input("What is the file to be scanned (do not include the .txt extension)? ") # the file to be opened
search_type = input("Which search would you like to run ('simple' or 'full')? ").lower() # which fu... |
0acb1df03885834b7c45df594f90bef4ed26a8a7 | doba23/Python_academy_Engeto | /4_lesson/use_case_2.py | 243 | 4.09375 | 4 | from time import sleep
num_seconds = int(input('How many seconds to you need?: '))
while num_seconds:
print(num_seconds)
num_seconds = num_seconds - 1
if num_seconds > 0:
sleep(1)
else:
print('Time has gone!') |
5dfb274e73589d2c7b80bb6e3554cbf23e6ae957 | nacho-vlad/chess-engine | /app/game.py | 1,536 | 3.546875 | 4 | from app.rustchess import Chessboard
class Game:
"""A game of chess. It aslo records all moves made, and
starts from the standard starting position. The game stops
on a keyboard interrupt.
Parameters
----------
white : Player
player for white
black : Player
player for b... |
d3ad9fc60eecb2ee170487c61a1d4a59b8442ce7 | ddari/my_python | /del_element_list.py | 120 | 3.71875 | 4 | l=list(map(str,input('Введите список:').split()))
A=[i for i in l if i=='John' or i=='Paul']
print (A)
|
ed4c9b55ae93ed33463976f8f061bfce61483ef3 | Scruf/BluebiteAssignment | /question3.py | 569 | 3.59375 | 4 | class Band:
def __init__(self, genre="rock", name='Unknown'):
self.genre = genre
self.name = name
class RollingStones(Band):
def __init__(self, genre="rock"):
Band.__init__(self, genre,name="Rolling Stones")
self.genre = genre
def __str__(self):
return self.name
class RedHotChiliPeppers(Band):
def __ini... |
97bfc2f2997c549e4dd2412fb627e9f55b8beeeb | MojitoBar/Python_Study | /python_study/lab6_12_1.py | 656 | 3.640625 | 4 | """
챕터: day6
주제: exception
문제: 사용자로부터 1과 10사이의 숫자를 입력받아, 1부터 해당 숫자까지의 합을 구하라.
만약 숫자가 아닌 값이 입력되면, "숫자를 입력하세요"라는 문장을 출력한 후 다시 입력을 받는다.
작성자: 주동석
작성일: 2018. 11. 27
"""
# exception을 사용하여 프로그래밍
while(True):
s = 0
try:
n = int(input("1과 10사이의 숫자를 입력해 주세요: "))
for i in range(1, ... |
803daa4c5b6015b923b960e7d97d96d2becc0c4f | RuzhaK/pythonProject | /Fundamentals/MidExamSecond/ProblemOne.py | 422 | 3.78125 | 4 | cost = float(input())
months = int(input())
budget = 0
for i in range(months):
if (i + 1) % 2 != 0 and i + 1 > 1:
budget -= 0.16 * budget
elif (i + 1) % 4 == 0:
budget = budget * 1.25
budget += 0.25 * cost
if cost <= budget:
print(f"Bravo! You can go to Disneyland and you will have {bu... |
e1ab6a9b1131d513cc83b038759b9cceba83d329 | ksingh7/python-programs | /Guess_secret_Number.py | 847 | 4.03125 | 4 | def guessNumber():
low = 0
high = 100
guess = 0
while low < high:
mid = (low + high) / 2
print "Is your secret number " + str(mid) + "?"
response = raw_input("Enter 'h' to indicate the guess is too high. Enter 'l' to indicate the guess is too low. Enter 'c' to indicate I guessed ... |
913e1bd3cb39822625c37ff2ad11ad7a3808036c | fingerman/python_fundamentals | /intro/3_diff_instances_obk.py | 221 | 3.734375 | 4 | a = 5
b = 5
print(id(a))
print(id(b))
print(a is b)
print(type(a))
c = [1, 2]
d = [2, 2]
print(id(c))
print(id(d))
print(type(c))
# is compares the value of the objects/instances, not values
print(c == d)
print(c is d)
|
4bc0d730b708bd407e20e000413e3db49dc2229b | Bradleywboggs/call-data-test | /src/tasks/extract.py | 397 | 3.796875 | 4 | import csv
from typing import Dict, List
# NOTE depending on the potential size of the data files, using a generator may be
# a better option here, however for purposes of this exercise and this particular file,
# we'll simply parse the file.
def get_data(file_name) -> List[Dict[str, str]]:
with open(file_na... |
8d9f10cd0dd656e63ddf75733e99e9aa7e67ffa5 | wengjinlin/Homework | /Day05/Calculator/calculator.py | 398 | 3.90625 | 4 | import func
while True:
func.menu_print()
choice = input(">>:")
if choice == "2":
break
if choice == "1":
formula = input("请输入公式:")
formula = formula.replace(" ", "").strip()
res = func.calculation(formula)
print("计算结果为:"+res)
py_res = eval(formula)
... |
329883c416c0983269daa35552bb90e284b33525 | YiqiongZhou/Leetcode | /1108.ip-地址无效化.py | 529 | 3.546875 | 4 | #
# @lc app=leetcode.cn id=1108 lang=python
#
# [1108] IP 地址无效化
#
# @lc code=start
class Solution(object):
def defangIPaddr(self, address):
"""
:type address: str
:rtype: str
"""
ans=[]
for char in address:
ans.append(char)
if char=='.':
... |
d3683ae91e4a6ba6c47c9556a68b683b83f94e6b | Midnex/edi-835-parser | /edi_835_parser/elements/__init__.py | 365 | 3.765625 | 4 | from abc import ABC, abstractmethod
class Element(ABC):
def __set_name__(self, owner, name):
self.private_name = '_' + name
def __get__(self, obj, objtype=None):
return getattr(obj, self.private_name)
def __set__(self, obj, value):
value = self.parser(value)
setattr(obj, self.private_name, value)
@abs... |
259bb6514157db4abda14eb4b641e336a90b0b76 | mazh661/distonslessons | /HomeWork2/example3.py | 126 | 3.96875 | 4 | a_dict = {
1:"one",
2:"two",
3:"three"
}
keys = a_dict.keys()
keys = sorted(keys)
for key in keys:
print(key) |
ca8dc8231f5b4fb59ecf4a8bcddbef2cf11c301e | carinazhang/deeptest | /第二期/上海-爱笑的眼睛/第二次任务_快学Python 3练习/List.py | 522 | 3.578125 | 4 | # -*- coding=utf-8 -*-
#_author_ == u"smile eyes"
if __name__=="__main__":
list_demo = [1,2,3,4,5,6,7]
print(u"内置函数处理list示例: ")
# 计算list_demo中元素个数
print(len(list_demo))
# 返回list_demo中最大值的元素
print(max(list_demo))
# 返回list_demo中最小值的元素
print(min(list_demo))
# 将li... |
d7a487f1465373449621defa738aeb2bb63f0dce | wkreiser/Kreiser-IQT-Project | /Python/Object_Oriented/Calculator/CalcFunctions/calcFunctions.py | 1,470 | 4.25 | 4 | #Error checking for integer input
def get_user_input():
userInput = raw_input("Enter an integer: ").rstrip()
try:
userInput =int(userInput)
except ValueError:
print("Try again.\n")
userInput = get_user_input()
return userInput
#Function to print the mathematical operations l... |
4d59e18cc15928b7e8bee89e6f31eace73e67e31 | Yuan98Yu/solutions-to-leetcode-cn | /solutions/[212]单次搜索Ⅱ.py | 2,009 | 3.59375 | 4 | from typing import List
from itertools import product
class TrieNode(dict):
def __init__(self, parent=None, val=None) -> None:
super().__init__()
self.word = False
self.val = val
self.parent = parent
self.count = 0
class Solution:
def findWords(self, board: List[Lis... |
6bd58deaf984bc355d8f447fdfe8990792875cc1 | JoGomes19/LA2 | /Treino/Torneio 1/LA_2/ordenaNumeros.py | 312 | 3.703125 | 4 | import sys
def getChave(l):
return l[0]
l = []
for s in sys.stdin:
x = s.split(",")
l.append(x)
l = [[int(float(j)) for j in i] for i in l] # converte uma lista de listas de string para lita de lista de ints
l.sort(key = getChave) # ordena uma lista de listas em relacao a chave!
for i in l:
print(i)
|
a43f4d803add8a227eee48b5b5ebad63ef5a4574 | surya-232/assignment | /assignment3.py | 1,391 | 4.03125 | 4 | print("question1")
print("enter the list items")
list=[]
x=input("1")
y=input("2")
z=input("3")
print("the list is")
list=[x,y,z]
print(list)
print("\n")
print("question2")
#['google','apple','facebook','microsoft','tesla']
list2=['google','apple','facebook','microsoft','tesla']
print(list2)
print(list.extend(list2))
... |
32d4489d79a9f21a75e1b3322b50091346765fa6 | vincent-vega/adventofcode | /2018/day_06/6.py | 2,187 | 3.875 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
import re
def _manhattan(a: (int, int), b: (int, int)) -> int:
return abs(a[0] - b[0]) + abs(a[1] - b[1])
def _closest(locations: dict, target: (int, int)) -> int:
min_distance = min_name = None
for n, coordinate in locations.items():
if coordinate... |
d95c06acb5a1c8649c30865ade7444a7fafd2f11 | Wjun0/python- | /day05/05-函数结合return可以让多层循环终止-扩展.py | 651 | 3.90625 | 4 | # is_ok = False
# for value1 in range(1, 4):
# print("外层循环:", value1)
# for value2 in range(5):
# print("内层循环:", value2)
# if value2 == 3:
# is_ok = True
# break
#
# if is_ok:
# break
# 简写方式:
def show():
for value1 in range(1, 4):
print("外层循环:", ... |
836e07d1b666e2223057ff1c011e5a8eada3cf1a | akevinblackwell/Raspberry-Pi-Class-2017 | /SortAssignment.py | 2,714 | 4.5 | 4 | '''
Raspberry Pi Assignment - Sorting
Sorting is simply reordering a list of items in a logical order, such as alphabetical or in increasing order.
Sounds simple, huh? And it is for small lists of items. But computers are often asked to sort very large lists
of items. And the bigger they get, the more computing po... |
283cd95648b5552e286e1e14358ad6d08620d515 | a313071162/letcode | /letcode_27_移除元素.py | 2,010 | 3.828125 | 4 | #!/usr/bin/env python
#!/usr/bin/python
# -*- coding: UTF-8 -*-
"""
@File:letcode_27_移除元素.py
@Data:2019/7/30
@param:
@return:
"""
# python偷懒方法
class Solution:
def removeElement(self, nums: list, val: int) -> int:
if val not in nums or not nums:
return len(nums)
for value in nums[::-1... |
e13d9523e192ac1d763ee20485b9ef0ebfb9f0f1 | Scottjhollywood/MovieWatchlist | /main/Watchlist_Editor.py | 2,103 | 4 | 4 | from Movie_Extractor import FileExtractor
def edit_watchlist(choices):
movie_list = FileExtractor.extract_movie_dict("movies_length.txt")
print("==================")
print("Watchlist Editor")
print("==================")
print("1. Add movie(s) to your watchlist")
print("2. Remove movie... |
3f41fe21dd41a7c4949ba461775ad8007c1b8580 | pranithajemmalla/Cracking_The_Coding_Interview | /Data Structures/ArraysAndStrings/1.4 Palindrome Permutation.py | 1,526 | 4.0625 | 4 | # Palindrome Permutation
# Given a string, write a function to check if it is a permutation of a palindrome
class PalindromePermutation:
def __init__(self):
self.input_str = None
def using_hash_table(self):
str_dict = dict()
for s in self.input_str:
if s != " ":
... |
933fcff407c1cc2cb8c49b8efeee0b68b2b19762 | aayush17002/DumpCode | /Foobar/invert.py | 152 | 3.796875 | 4 | g={0:[],1:[0,2,3,4],2:[3,4],3:[1,2],4:[0]}
h={}
for x in g:
v=g[x]
for node in v:
if node in h:
h[node].append(x)
else:
h[node]=[x]
print(h) |
f64b418c0d542b478d89b588bb032f54d64825d5 | ivanlyon/exercises | /kattis/k_4thought.py | 1,687 | 3.71875 | 4 | '''
Precompute equations of fixed operations and number.
Status: Accepted
'''
###############################################################################
def eval2(text):
"""Evaluate an expression without using eval()"""
numbers, operators = [], []
for glyph in text.split():
if glyph.isdigit... |
faaac8523add98bcd3c00ccb352f059368738b37 | mchhhhhhhhhhh/gameRPG | /gameRPG.py | 4,338 | 3.984375 | 4 | class hero:
def __init__(self,name,health,attack,geo_x,geo_y):
self.name=name
self.health=health
self.attack=attack
self.geo_x=geo_x
self.geo_y=geo_y
def attack_to_hero(self,damage):
self.health=self.health-damage
return self.health
def forwa... |
660f0a5039a7f1ed54cab4800fe56c770f251e00 | WiceCwispies/HeiTerryAsteroids | /src/GA/chromosome.py | 1,379 | 3.59375 | 4 | import numpy as np
class Chromosome:
def __init__(self, string):
self.string = string
self.fitness = 0
self.normFitness = 0
def updateString(self,string):
self.string = string
def updateFitness(self,fitness):
self.fitness = fitness
def updateNormFi... |
52a931bd34a44daa303251d5d0512aab9796c71a | Niranch/Py-codecollection | /FindingListRunnerup.py | 403 | 3.6875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Thu Aug 20 19:31:59 2020
@author: Niranch
"""
from array import *
n=5
mylist=[6,6,6,6,6]
mylist.sort()
flag=False
while n>0:
if mylist[n-2]!=mylist[n-1]:
runnerup = mylist[n-2]
flag=True
else:
n=n-1
if(flag) or (n<0):
... |
93f2875455f7933c5acbed538dea1b05490bba4e | shehryarbajwa/Algorithms--Datastructures | /Algorithms-Project-2/Project/Problem_3.py | 3,817 | 3.625 | 4 | import sys
class HuffNode(object):
def __init__(self, char, freq):
self.char = char
self.freq = freq
self.left = None
self.right = None
def is_tree_leaf(self):
if (self.left or self.right) is None:
return True
else:
return False
def... |
d1ce43b63d53dbeab48ce3af36ef20482130a389 | hannah-544/python | /Arithmetic operators.py | 477 | 4.28125 | 4 | #Types of operators
# Examples of Arithmetic Operator
x = 9
y = 4
# Addition of numbers
add = x+y
# Subtraction of numbers
sub = x - y
# Multiplication of number
mul = x * y
# Division(float) of number
div1 = x / y
# Division(floor) of number
floor = x // y
# Modulo of both number ... |
60efa0774f1a9f5c0b9b2606a213b50fa28fdb3f | tomfedrizzi/python-2020 | /Ejercicios alf, tipo de datos simples.py | 5,662 | 4.40625 | 4 | # #Ejercicio 1
# Escribir un programa que muestre por pantalla la cadena ¡Hola Mundo!.
print("¡Hola Mundo!")
# #Ejercicio 2
# Escribir un programa que almacene la cadena ¡Hola Mundo! en una variable y luego muestre por pantalla
#el contenido de la variable.
X="¡Hola Mundo!"
print(X)
# #Ejercicio 3
# Escribir un p... |
277d6e3f339efd0c2f0212a171e17d50d98e05aa | JonLagrange/Machine-Learning | /kerasLearn/mlp.py | 1,908 | 3.53125 | 4 | import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
class hello_world:
def __init__(self):
self.mnist = input_data.read_data_sets("mnist_data/", one_hot=True)
def inference(self):
self.input = tf.placeholder(tf.float32, [None, 784]) #输入28*28的图
sel... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.