blob_id stringlengths 40 40 | repo_name stringlengths 5 127 | path stringlengths 2 523 | length_bytes int64 22 545k | score float64 3.5 5.34 | int_score int64 4 5 | text stringlengths 22 545k |
|---|---|---|---|---|---|---|
d511046a1f0122508166178fe20db5581ee406a5 | katmatchett/mastersthesis | /Woods IB Task/Woods IB Task Script.py | 18,181 | 3.546875 | 4 | from psychopy import core, visual, event, gui, data, sound
from random import randint, sample, choice, shuffle
from itertools import chain
import os, csv
#------ Define some utility functions ------
def display_instructions(window, message, size=1):
"""Display a message onscreen and wait for a keypress.
A... |
138475ee6b374aa4740493e20ea8f7464f7d94ea | sung0471/PyTorch_SBD | /utils/time_control.py | 990 | 3.5625 | 4 | import time
import datetime
class TimeControl:
def __init__(self):
self.now_time = None
@staticmethod
def now_day_str():
curr_day = datetime.datetime.now()
curr_day_str = '{}-{}-{}'.format(curr_day.year, curr_day.month, curr_day.day)
return curr_day_str
@staticmethod
... |
15b590175e6972c50273ba75dfdb1a2586eedc0b | Rishavanand9/Workspace | /logIN.py | 1,021 | 3.515625 | 4 | from tkinter import*
import tkinter
from tkinter import messagebox as tkMessageBox
class fifa:
def __init__(self):
window = Tk()
window.title("Enter id & Password ")
window.minsize(width=300,height=300)
window.configure(background='black')
l1 = Label(window, text="Userna... |
46ee109df73dea6e703d44cad42fc79576aacbc3 | BCarley/Euler | /euler14b.py | 1,267 | 3.78125 | 4 | """
Euler 14
n > n/2 (n is even)
n > 3n + 1 (n is odd)
for which number, n, can we produce the longest chain?
in this I have attempted to use a more complete cache, involving all the numbers that are generated by the generate_list
function but the process of creating the list open ended list is slowing ever... |
7bf711a3f89aff3c0e255c03f0fe7227c8e2386f | BCarley/Euler | /euler15.py | 624 | 3.5625 | 4 | """
Euler 15
Starting in the top left corner of a 2x2 grid,
and only being able to move to the right and down, there are exactly 6 routes to the bottom right corner
How many such routes are there through a 20x20 grid?
This works, but it is incredibly slow, maybe removing the join?
"""
import itertools
... |
9955da59f028cae548810557304e640b0b9d1980 | BCarley/Euler | /euler14.py | 936 | 3.875 | 4 | """
Euler 14
n > n/2 (n is even)
n > 3n + 1 (n is odd)
for which number, n, can we produce the longest chain?
"""
import itertools
import time
start = time.time()
cache = [0] * 1000001
cache[1] = 1
def generate_chain(num, cache):
"""find the chain length for each number"""
init = num
... |
93203e79843601b3cb05106895987c6a3aa8743b | Monika-88/profil-software-recruitment-task | /people_utils.py | 2,706 | 3.6875 | 4 | import json
from datetime import datetime, date
from pathlib import Path
# verify whether a given year is a leap year
def years_to_leap_year(year):
def _is_leap(year):
if year % 4 == 0:
if year % 100 == 0:
if year % 400 == 0:
return True
else... |
0e159611cdc33f8e59f61744b4960387de429592 | chrissieb123/Lambda-calculus | /Abstraction.py | 4,011 | 3.78125 | 4 | from LambdaTerm import LambdaTerm
from Variable import Variable
import Utility
class Abstraction(LambdaTerm):
"""Represents a lambda term of the form (λx.M)."""
# list of bound variables
boundvar = []
# create an abstraction using a variable for the head and a lambda term for the body
def __init_... |
fa9503cba44309d8da96a9dce0b2088931169ba1 | sebalp1987/anomaly_detection_answers | /preprocessing/sql_to.py | 2,214 | 3.578125 | 4 | import sqlite3
import pickle
import STRING
import os
import json
def sql_to_pickle(folder_in, db_file):
# We bring the files we want to transform from SQL to Pickle
files_name = [f for f in os.listdir(folder_in) if f.endswith('.csv')]
# Connect to DB
connection = sqlite3.connect('{}.db'... |
0fa2259f7b692512ccfd9fc074ffd8640762853a | racer97/ds-class-intro | /python_basics/class02/exercise_6.py | 2,246 | 4.25 | 4 | '''
Edit this file to complete Exercise 6
'''
def calculation(a, b):
'''
Write a function calculation() such that it can accept two variables
and calculate the addition and subtraction of it.
It must return both addition and subtraction in a single return call
Expected output:
res = calculation(40, 10)
print... |
920bb672454ccfdf1f0be5abac9819ece2059ba4 | shahzaibqazi/Coding-Problems | /LeetCode/Python/linkedlist-reverse-linked-list.py | 679 | 3.90625 | 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:
temp = ListNode(0, head)
prev, curr, end = temp, temp.next, None
... |
fc6662184144d622a1a21a4c7082410291f490b5 | shahzaibqazi/Coding-Problems | /LeetCode/Python/linkedlist-remove-linked-list-elements.py | 495 | 3.59375 | 4 | # Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def removeElements(self, head: ListNode, val: int) -> ListNode:
temp = ListNode(0, head)
node = temp
while node.next... |
d1c9aebed7d735cb5b8f82a5c16ba219fe2b063f | MeNsaaH/python-parallelism-concurrency-talk | /parallelism/04 - coroutine.py | 1,925 | 3.78125 | 4 | """ Simple Coroutine Python """
from collections import namedtuple
# run and inspect coroutine
# A coroutine is only good enough it has entered the running state and can receive values
# A functin generator can be used to prime the coroutine for usage
from functools import wraps
# Special sets of generators w... |
195f2ad45a3a34b3bac9e9d71da58d5870a0ec48 | dyuwan/BARDOS-Chatbot | /Therapists/filter.py | 346 | 3.671875 | 4 | import pandas as pd
def filtering(city):
df = pd.read_csv('/Users/dyuwan/Downloads/Therapists-{}.csv'.format(city))
df=df.head(8)
for k in df.head(1):
if "Unnamed" in k:
df.drop(k, axis = 1, inplace = True)
df.to_csv('/Users/dyuwan/Downloads/Therapists-{}.csv'.format(city))
... |
11b3b1838a08dc5f7c37a2e37f91b8b2fe959645 | Kitware/UPennContrast | /devops/girder/plugins/AnnotationPlugin/upenncontrast_annotation/server/helpers/connections.py | 2,920 | 3.71875 | 4 | import math
import numpy as np
def pointToPointDistance(coord1, coord2):
"""Get the distance between two points using points coordinates.
If both points have z coordinate, get the XYZ distance, else get the XY distance
Points coordinates are represented by {x: x_coord, y: y_coord, z?: z_coord}.
Args:
... |
c0abdcde80105665a5d39375f7ce6a40207a09d1 | ekieff/hangman-challenge | /hangman.py | 1,223 | 4.03125 | 4 | from random import seed
from random import randint
# start with a list of words
# return a randomized word from that list as the value
shrug= ' ¯\_(ツ)_/¯ '
words = ['dogs', 'couch', 'teapot', 'recursion', 'javascript']
seed()
secret_word = words[randint(0,(len(words)))]
print('Welcome to Hangman! You have 6 guesses to... |
e197a2e98f11de20034696d01302654d1c29c1b6 | mnivelles/astar-with-quadtree | /algorithme/astar_noeud.py | 927 | 3.609375 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
class AStarNoeud(object):
def __init__(self, ancetre, quadnoeud, cout_chemin, cout_estime):
self.ancetre = ancetre
self.quadnoeud = quadnoeud
self.cout_total = cout_chemin + cout_estime
self.cout_chemin = cout_chemin
self.cout_es... |
30132cd72458b94cd244412d9dcdc108a5674c6f | yatikaarora/turtle_coding | /drawing.py | 282 | 4.28125 | 4 | #to draw an octagon and a nested loop within.
import turtle
turtle= turtle.Turtle()
sides = 8
for steps in range(sides):
turtle.forward(100)
turtle.right(360/sides)
for moresteps in range(sides):
turtle.forward(50)
turtle.right(360/sides)
|
60ecd4017616060d20a51bb2558e85be6cdb50bb | ladyada/Adafruit_Learning_System_Guides | /Getting_Started_With_Raspberry_Pi_Pico/definite_loop/code.py | 128 | 3.90625 | 4 | """Example of definite loop."""
print("Loop starting!")
for i in range(10):
print("Loop number", i)
print("Loop finished!")
|
5ecaab2f7e9c8a17bd09aa81240b0465a0704c69 | muskankumarisingh/loop | /palindrome number.py | 194 | 3.921875 | 4 | n=int(input("Enter the number:"))
i=n
sum=0
while(n>0):
digit=n%10
sum=sum*10+digit
n=n//10
if(i==sum):
print("i is a palindrome number")
else:
print("i is not a palindrome") |
8165bb818668a10b217822c81dcc965cd82edfb2 | muskankumarisingh/loop | /loop14.py | 253 | 3.703125 | 4 | n=int(input("enter number"))
a=2
c=1
while a>0:
i=2
while i<a:
if a%i==0:
break
i+=1
else:
print(a)
if c==n:
break
c+=1
a+=1
Loop prime number user jitna dale utna woo first se print kare Jaise 5 daale to first five prime number de |
09acb25a8dc6dc662bfc51c815b17c8390d37720 | shubhangiranjan11/Hackaloop | /loop6.py | 85 | 3.578125 | 4 | i=0
sum=0
while i<=10:
if i%2==0:
sum=sum+i
print(sum)
i=i+1
|
f6ca58d4f4c3b5f62e26e6b2e3992ba2122d0555 | shubhangiranjan11/Hackaloop | /loop9.py | 172 | 3.84375 | 4 | user=int(input("any number"))
i=1
c=0
while i<=user:
if user%i==0:
c=c+1
i=i+1
if c==2:
print("prime number")
else:
print("not prime number")
i=i+1
|
f0962e44eee61bfcb7524c68c346c7fb620269ec | EllipticBike38/PyAccademyMazzini21 | /es_ffi_01.py | 1,128 | 4.34375 | 4 | # Write a function insert_dash(num) / insertDash(num) / InsertDash(int num) that will insert dashes ('-') between each two odd numbers
# in num. For example: if num is 454793 the output should be 4547-9-3. Don't count zero as an odd number.
# Note that the number will always be non-negative (>= 0).
def insertDash(... |
97edcf6001a2006d223dce8a48fc03fa1bea6bf9 | EllipticBike38/PyAccademyMazzini21 | /es11.py | 717 | 4.09375 | 4 | # --applicazioni di zip
def what_date_is_the_n_day_of_the_year(n):
mm = ['gennaio', 'febbraio', 'marzo', 'aprile', 'maggio', 'giugno',
'luglio', 'agosto', 'settembre', 'ottobre', 'novembre', 'dicembre']
durations = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
coppie = list(zip(durations, ... |
5db285c5e2574a9a23f49cf3948236fd582ec340 | Deepsprings/MachineLearning | /figure/LDA.py | 2,227 | 3.609375 | 4 | import matplotlib.pyplot as plt
import numpy as np
def test1():
x1 = np.random.uniform(-2, 7, 35)
n1 = np.random.uniform(-2, 2, 35)
y1 = 0.85*x1 -3 + n1
x1_m = np.mean(x1)
y1_m = np.mean(y1)
x2 = np.random.uniform(0, 5, 15)
n2 = np.random.uniform(-2, 2, 15)
y2 = 0.6*x2 -7 + n2
x2... |
d84c42ac605a801894bc0debcd52a848c6b0aedc | YuYuxiang1997/ProjectEuler | /problem010.py | 456 | 3.90625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sun Mar 10 01:47:13 2019
@author: pengu
"""
from math import floor,sqrt
def getprimes(max):
def check_prime(n):
threshold = floor(sqrt(n))
for i in range(2,threshold+1):
if n%i == 0:
return False
return True
primes = [... |
0eb0de1212cc9ad6d4bf782681cffe284a868430 | sambloom92/adventofcode | /day_10/adapters_pt2.py | 2,918 | 3.59375 | 4 | import os
from itertools import combinations
from math import prod
from typing import Iterable, List
from conf import ROOT_DIR
from day_10.adapters_pt1 import get_step_sizes
from day_10.utils import get_adapters
def split_into_sublists(input_values: List[int]) -> List[List[int]]:
"""
split an ordered list of... |
89bd039562349b4a280c3dd43faa16ac440487f5 | atagen/haishoku | /haishoku/alg.py | 5,845 | 3.765625 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Date : 2017-05-15 15:10
# @Author : Gin (gin.lance.inside@hotmail.com)
# @Link :
# @Disc : alg about palette
import random
import math
def clusterGen(k, colors):
""" Generate k random colors
The palette will show k colors.
Also, the k's v... |
84a2325fab890f207479408c40396921d24d3fe1 | bryarcole/The-Portfolio | /Python/SmallWorks/Exceptions.py | 1,092 | 3.75 | 4 | def main():
try:
option = 0
while (option != 4):
print()
print("1 - Divide by zero")
print("2 - Open a nonexistent file")
print("3 - Bad list index")
print("4 - Quit")
print()
op... |
a75e52aa4bad23d2f6b830aae3257704327315cc | bryarcole/The-Portfolio | /Python/SmallWorks/BryarColeExtraCredit.py | 2,973 | 4.0625 | 4 | def FarhToCels():
number = int(input('Please enter the degrees in Fahrenheit: '))
cels = ((5/9)*(number - 32))
print("The current degrees in Celcius is", cels)
def MilesToKilos():
number = int(input('Please enter the number of miles: '))
kilos = number * 1.609
print(number,'miles is equivale... |
7dd29d23f7c236f03de6cb38d86ffe6602fef4c6 | bryarcole/The-Portfolio | /Python/LearnPythonTheHardWay/ex6.py | 585 | 3.796875 | 4 | x = "There are %d types of people." %10 #interger insert here
binary = "Binary"
do_not = "don't"
y = "Those who know %s and those who %s." %(binary, do_not)#double string insert here
print x
print y
print "I said: %r." %x #string insert here
print "I also said: '%s'." %y #string insert here
hilarious = False
joke_ev... |
fe01e46b4b092ac6ac3280795909cb6b8a5769f2 | bryarcole/The-Portfolio | /Python/LearnPythonTheHardWay/ex31.py | 1,128 | 3.78125 | 4 | print "You enter a dark room with two doors. Do you go thorugh door #1 or door # 2"
door = raw_input(">" )
if door == "1":
print "Theres a giant bear here earting a cheescake. What do you do?"
print "Option '1'. Take the cake"
print "Option '2'. Scream at the bear."
bear = raw_input("> ")
if bea... |
95e81c68544f7e73c195b18a9d543efef61d3c93 | ZbigniewPowierza/pythonalx | /funkcje/zadanie_8.py | 1,145 | 3.90625 | 4 | # napisz funkcje ktora policzy maksimum z 3 podanych liczb
# max_of_three(10, 1, 17)
#17
# w celu rozwiazania mozna napisac wiecej niz jedna funkcje
lista = [10, 2, 5]
def max_of_two(x, y):
if x > y:
return x
return y
def max_of_three(a, b, c):
if c > max_of_two(a, b):
return c
retur... |
b2d97e2d16fac84b4e1792e5c0d138d3e110b269 | ZbigniewPowierza/pythonalx | /Kolekcje/listy.py | 635 | 3.875 | 4 | my_list = [1, "a", "ala", "kot", 121]
print(my_list[0])
my_list2 = [1, 2, 3, my_list]
print(my_list2[3])
print(my_list2[3][2])
print(dir(my_list)) #sprawdzamy jakie metody działają na liście
print(my_list.append(10))
# my_list.append(10)
print(my_list)
print(my_list.pop())
print(my_list.pop())
print(my_list)
#łąc... |
ee29a2219b214eae2383fa91b2bd3ce032608e7f | ZbigniewPowierza/pythonalx | /obsluga_bledow/obsluga_bledow.py | 594 | 3.671875 | 4 | lista = [1, 0, 10, 'a']
# for i in lista:
# try:
# print(10/i)
# except ZeroDivisionError:
# print("Dzielisz przez zero")
# except TypeError:
# print("Dzielisz prze 'nie-liczbę'")
# except Exception:
# pass
# finally:
# print("wykonałem sie")
lista = [1, 0, ... |
987dcbfa1c2878c6b277e67b024d5b8a27c1d8de | xdongz/Leetcode | /05.Roman2Integer/roman2int.py | 492 | 3.5 | 4 | #Python3
class Solution:
def romanToInt(self, s):
"""
:type s: str
:rtype: int
"""
dict={'M':1000,'D':500,'C':100,'L':50,'X':10,'V':5,'I':1,'IV':4,'IX':9,'XL':40,'XC':90,'CD':400,'CM':900}
i=0
sum=0
while i<len(s):
if s[i:i+2] in dict:
... |
adc2cf027c04747b606fe2cd5d1e8a0e36acbb12 | mattnworb/algorithm-studies | /python/jun-problem.py | 1,129 | 4.03125 | 4 | """
I have an continous integer array starting from 1. For example
1, 2, 3, 4.
First I reordered them, then I replaced one of the integer with another one in the range.
So, you end up with something like:
3, 1, 3, 2.
Write a program prints out the missing number and the duplicate number. Assume this is a
giant ar... |
f6739991872c9d7450e770d6297cbd462b793a35 | Gauravkarki490/Attendance-System-using-face-detection | /main.py | 6,638 | 3.609375 | 4 | #use to form gui
from tkinter import*
#tkk imported because it has some stylies toolkit
from tkinter import ttk
from tkinter.messagebox import askyesno
#pillow used to import images
from PIL import Image,ImageTk
from student import Student
from Train import Train
from face_recog import Face_rec
from Atten... |
8a345c3accc0359f08df67b6e765fbc2f45cf3d9 | stern1978/IS-211-Software-Application-Progamming-II | /IS211_Assignment8/pig_extended.py | 8,340 | 3.734375 | 4 | #!user/bin/env python
# -*- coding: utf-8 -*-
'''
This module shows update of a simple game called Pig using Factory and Proxy patterns.
'''
import random
import time
import argparse
parser = argparse.ArgumentParser(description = 'Play Pig - 1 Player or 2 Player')
parser.add_argument('--player1',type = str, help = '... |
a752294a8efa2a621ad55f7523f5e118310c8b07 | stern1978/IS-211-Software-Application-Progamming-II | /IS211_Assignment6/conversions_refactored.py | 2,297 | 3.640625 | 4 | #!usr/bin/env python
# -*- coding: utf-8 -*-
'''Week 6 - Assignment 2'''
absoluteZeroC = -273.15
absoluteZeroK = 0
absoluteZeroF = -459.66
mi_yard = 1760.0
mi_m = 1609.34
m_yard = 1.09361
yard_m = .9144
zeroError = 'Lower limit Error. Input is less than Absolute Zero.'
numberError = 'Entry is not a number.'
canNotCon... |
ba6e0574e900be6eed7368ef339d1c1407ea1450 | noahmarble/Ch.05_Looping | /5.0_Take_Home_Test.py | 2,949 | 4.28125 | 4 | '''
HONOR CODE: I solemnly promise that while taking this test I will only use PyCharm or the Internet,
but I will definitely not ask another person except the instructor. Signed: ______________________
1. Make the following program work.
'''
print("This program takes three numbers and returns the sum.")
total = 0
... |
404b24fb4e1be8176289ab434a6330a22dcd20a4 | jkmrto/EulerProject | /script1.py | 267 | 3.65625 | 4 | import Funciones as fun
lista = list(range(1, 1000, 1))
def filtering(number, numbers):
for i in numbers:
if fun.is_div(number, i):
return True
return False
multiples = [l for l in lista if filtering(l, [3, 5])]
print(sum(multiples))
|
c83665d8eb9bcff974737e4705bb285b8b3384cf | FFFgrid/some-programs | /单向链表/队列的实现.py | 1,528 | 4.125 | 4 | class _node:
__slots__ = '_element','_next'#用__slots__可以提升内存应用效率
def __init__(self,element,next):
self._element = element #该node处的值
self._next = next #下一个node的引用
class LinkedQueue:
"""First In First Out"""
def __init__(self):
"""create an empty queue"""
self._hea... |
3e47cf6c1386dbfc7071f073f3eeb9e5bedd12f5 | FFFgrid/some-programs | /排序算法/快速排序.py | 508 | 4 | 4 | def quicksort(seq):
if len(seq) < 2: #当序列只有一个元素时就不需要排序
return seq
else:
base = seq[0] #核心思想就是找一个数作为一个基准数(可以直接取第一个数),将剩下的数分为比基准小的(left)和比基准大的(right)两组
left = [elem for elem in seq[1:] if elem < base]
right = [elem for elem in seq[1:] if elem > base]
return quicksort(left) ... |
4e1dcd156c6f0aa64b195f723fb0af1602920c54 | groboclown/petronia | /src/petronia/base/util/rwlock.py | 3,420 | 3.75 | 4 | """Simple reader-writer locks in Python
Many readers can hold the lock XOR one and only one writer.
Source: https://majid.info/blog/a-reader-writer-lock-for-python/
License: public domain.
"""
from typing import Optional
import threading
from ..errors import PetroniaLockTimeoutError
# version = """$Id: rwlock.py,v 1.... |
aef702c3a000b08c8bf2e56c090b475cf17be6a2 | Nikita-Voloshko/Lesson7 | /cell.py | 1,359 | 3.765625 | 4 | class cell():
def __init__(self, my_cell):
self.my_cell = my_cell
def __add__(self, other):
if (self.my_cell > 0):
return self.my_cell + other.my_cell
else:
return "Число должно быть больше 0"
def __sub__(self, other):
if (self.my_cell > 0):
... |
e788494a1562140877a8ba0ef88b16c95dfb776b | sausages-of-the-future/registry | /scripts/address.py | 1,548 | 3.53125 | 4 | #! /usr/bin/env python3
import os
import sys
import json
def get_addresses(file):
with open(file) as f:
lines = f.readlines()
return lines
def get_points(lat_lng):
lat, lng = lat_lng.split()
return [float(lat), float(lng)]
def split_numbers_street_and_lat_lng(line):
numbers = line.split(... |
9a4116d46b97a1c158225db561db642d6542bd31 | nikhilymc/HOMEWORK | /python/count.py | 276 | 3.609375 | 4 | a=raw_input("enter the string")
n=0
p=0
k=0
j=0
for i in a:
if i in "aeiou":
n=n+1
elif i in "sldkclksdc":
p=p+1
elif i in " ":
k=k+1
elif i in "?":
j=j+1
print "number of vowels",n
print "number of const",p
print "number of word",k+1
print "number of ?",j
|
1af9c9746f729b7f308737cb9440df4bf0a98316 | nikhilymc/HOMEWORK | /python/palindrom.py | 115 | 3.984375 | 4 | a=raw_input("enter the string")
c=a.upper()
b=c[::-1]
if c==b:
print "string is palindrom"
else:
print "not"
|
fb4e6db6ba3e0a4d2c722973cb8321e714fb722c | krish1802/Messaging-And-RCE | /Sender.py | 788 | 3.8125 | 4 | import socket
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)#Connecting Via UDP Protocol
ip = str(input("Enter Server IP: "))#Put in server IP
port = int(input("Enter Server Port: "))#Put in Server PORT
#This funcition Connects client to the server for remote code execution
def command(ip, port):
username =... |
af7e5c6d548b98891d452c7550531e22e204896e | kkkalyadin/python | /task2.py | 194 | 3.984375 | 4 | time=int(input("Введите время в секундах:"))
hours = time // 3600
min = (time - hours * 3600) // 60
sec = time - (hours * 3600 + min * 60)
print (f"{hours}:{min}:{sec}") |
4b5522c791b39412bd0065b0e74a532ff0fb1cba | wuli133144/py_learn | /Node/sNode.py | 472 | 3.640625 | 4 |
class sNode(object):
def __init__(self):
self.pre=None
self.next=None
self.value=None
def __init__(self,value):
self.pre=None
self.next=None
self.value=value
def value1(self):
return self.value
def __cmp__(self, other):
if other.value... |
f411890b27f30e63e0db90e3db405761db3d35af | wuli133144/py_learn | /stack.py | 2,795 | 3.859375 | 4 | import os
import math
import os.path
class stack(object):
def __init__(self):
self.size=0
self.container=list()
self.minConn=None
pass
def getsize(self):
return self.size
def push(self,v):
self.size+=1
self.container.append(v)
if (se... |
253b09c2c2be22dff633265b5b5f1e535f2a6746 | ssky10/2018-2_Python | /실습수업 과제/09_1102_과제2.py | 276 | 3.765625 | 4 | import turtle
t = turtle.Turtle()
t.shape("turtle")
n = int(turtle.textinput("n각형 그리기","몇각형을 원하시나요?"))
length = int(turtle.textinput("n각형 그리기","한변의 길이는?"))
for i in range(n):
t.forward(length)
t.left(360/n)
input() |
78a491155ecd6b7087dcde0215d497ba1494ffbd | ssky10/2018-2_Python | /실습수업 과제/09_1102_과제3.py | 203 | 3.609375 | 4 | num = int(input("정수를 입력하세요:"))
for i in range(num,0,-1):
check = 0
for j in range(i,0,-1) :
if i%j == 0 :
check += 1
if check == 2 :
print(i)
|
6a116956038cdcba7cf70c929ae32da3a92e5100 | ssky10/2018-2_Python | /실습수업 과제/09_0928_과제3.py | 237 | 3.5625 | 4 | import turtle
t = turtle.Turtle()
t.shape("turtle")
x = int(input("이동할 좌표의 x값 입력:"))
y = int(input("이동할 좌표의 y값 입력:"))
t.goto(x,y)
dis = (((0-x)**2)+((0-y)**2))**0.5
t.write("선의 길이 = "+str(dis)) |
be1f26e540ee567a8378184494acba7f9c5e1d64 | NickDennis2580/DailyCodingProblem | /Problem #33 Running Median.py | 472 | 3.59375 | 4 |
# My solution
def runningAverage(x):
medians = []
temp = []
for i in range(0,len(x)):
temp.append(x[i])
temp.sort()
if i == 0:
medians.append(x[0])
elif len(temp) % 2 == 0:
medians.append((temp[int(len(temp)/2)] + temp[int(len(temp)/2 - 1)])/2)
... |
0fdd75fa5df88337f5ad6e787207e0f1c9283d44 | kokospapa8/algorithm-training | /baekjoon/2908.py | 75 | 3.671875 | 4 | a, b = input().split()
a = a[::-1]
b = b[::-1]
print(a if a>b else b)
|
acacb8ab70e19a779eb6217d8e520b88d711fe4b | kokospapa8/algorithm-training | /baekjoon/2438.py | 81 | 3.734375 | 4 | length = int(input())
a = "*"
for i in range(1,length+1):
print(a)
a=f"{a}*"
|
5816115749d95421b3a443ccae1699325a2ed5dc | kokospapa8/algorithm-training | /baekjoon/10039.py | 161 | 3.5 | 4 | x= []
for _ in range(5):
x.append(int(input()))
def fail(score):
return score if x > 40 else 40
x = [40 if i<40 else i for i in x]
print(int(sum(x)/len(x)))
|
ee685984158786fc5910cc1fd74e24fef48b3109 | kokospapa8/algorithm-training | /baekjoon/2742.py | 81 | 3.59375 | 4 | length =int(input())
for i in range(1,length+1):
print(length)
length-=1
|
4ec0af5d563cffabad1d4ed98cfcf4f733a6b569 | gysss/LeetCode1-Array | /18最大连续1个数.py | 435 | 3.65625 | 4 | """
给定一个二进制数组, 计算其中最大连续1的个数。
"""
def findMaxConsecutiveOnes( nums):
"""
:type nums: List[int]
:rtype: int
"""
count = 0
ans = []
for i in nums[:]:
if i != 1:
ans.append(count)
count = 0
else:
count+=1
ans.append(count)
return max(an... |
79a379314195f957a4535eac0369aecd32a00664 | zan-xhipe/spaceship | /core/crew/generation/name/name.py | 1,025 | 3.953125 | 4 | #! /usr/bin/python3
class Name():
def __init__(self, first="", middle=[], last=""):
self.first = first
self.middle = middle
self.last = last
def format(self, form):
result = ""
for i in form:
result += self.parse_name(i)
return result
... |
8ee015ece87e3d953abe58e186a924fc6b5fc4b7 | BoddupalliSaisrikar/LU-DVWP_-ASSIGNMENTS | /day 2 assignment.py | 421 | 3.765625 | 4 | # Assignment -1
# Create a data frame with 10 rows on random numbers and 4 coloumns, ( coloumns labelled as a,b,c,d)
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
%matplotlib inline
import seaborn as sns
from numpy.random import randn, randint, uniform, sample
df = pd.DataFrame(randn(... |
1593fa9b29f7f7c84662373465184c2b9d60e398 | lienordni/ProjectEuler | /123.py | 572 | 3.546875 | 4 | prime=[]
def setprimes(n): # Needs prime[]
for x in range(2,n+1):
if(x<11):
if(x==2 or x==3 or x==5 or x==7):
prime.append(x)
continue
else:
continue
i=0
c=True
while(prime[i]**2<=x):
if(x%prime[i]==0):
c=False
break
i+=1
if(c):
prime.append(x)
set... |
3b4a2b901b1830063f3eca8cffad5e41ba5e7d6c | lienordni/ProjectEuler | /205.2.py | 329 | 3.578125 | 4 | a=[0]*9
n=[0]*37
for a[0] in range(1,5):
for a[1] in range(1,5):
for a[2] in range(1,5):
for a[3] in range(1,5):
for a[4] in range(1,5):
for a[5] in range(1,5):
for a[6] in range(1,5):
for a[7] in range(1,5):
for a[8] in range(1,5):
n[sum(a)]+=1
for i in range(1,37):
print... |
629338e2ab34b62d8eb22f0d65fae449a2982154 | lienordni/ProjectEuler | /243.py | 2,635 | 3.546875 | 4 | import math
prime=[]
def setprimes(n): # Needs prime[]
for x in range(2,n+1):
if(x<11):
if(x==2 or x==3 or x==5 or x==7):
prime.append(x)
continue
else:
continue
i=0
c=True
while(prime[i]**2<=x):
if(x%prime[i]==0):
c=False
break
i+=1
if(c):
prime.append(x)
def iridium(... |
acd5bbdae42f81db8d10dedbd996d647ac555ddc | lienordni/ProjectEuler | /101.py | 576 | 3.953125 | 4 | def function(n):
return (1+n**11)//(1+n)
# return n**3
def interpolation(x,y,xn): # x and y are arrays. # Returns the y element corresponding to xn
s=0
n=len(x)
for i in range(0,n):
p=y[i]
for j in range(0,n):
if j==i:
continue
p*=(xn-x[j])/(x[i]-x[j])
s+=p
if s==int(s):
return i... |
ba356f08e27f93c79d000aa5780c049ea8e2a48e | lienordni/ProjectEuler | /37.py | 1,229 | 3.90625 | 4 | prime=[]
def setprimes(n):
for x in range(2,n+1):
if(x<11):
if(x==2 or x==3 or x==5 or x==7):
prime.append(x)
continue
else:
continue
i=0
c=True
while(prime[i]**2<=x):
if(x%prime[i]==0):
c=False
break
i+=1
if(c):
prime.append(x)
import math
def li... |
c5d951ec10a1b9278f4b1b39258e6a06b40c0c9a | RafalKornel/phys-simulations | /project1/2main.py | 1,292 | 3.53125 | 4 | #!/usr/bin/python3.7
import matplotlib.pyplot as pl
import random
import numpy as np
count = 16
radius = 0.05
def collision(r1, r2, radius):
d = ( (r1[0] - r2[0])**2 + (r1[1] - r2[1])**2 )**0.5
print(d)
return d < 2 * radius
class Circle:
def __init__(self, radius, pos):
self.r = radius
... |
4c9ffc1beec1daf92543c55ddb8dca9188941632 | amresnick/Python_modules | /Diving/Dive.py | 1,857 | 3.625 | 4 | class Diver:
def __init__(self, tank_volume, tank_pressure):
self.tank_volume = tank_volume
self.tank_pressure = tank_pressure
self.baseline = tank_volume/tank_pressure
def depth_to_pressure(self, depth):
return (depth/33.0) + 1 # ATA
def calc_SAC(self, used_psi, depth, tim... |
a523f6debe610b124a2c8d7342d9cfe67edba692 | zkapetanovic/IntroToNN | /HW2/load_cifar.py | 5,339 | 3.65625 | 4 | import pickle
import numpy as np
def unpickle(filename):
fo = open(filename, 'rb')
data = pickle.load(fo, encoding='bytes')
fo.close()
return data
#Step 1: define a function to load traing batch data from directory
def load_training_batch(folder_path,batch_id):
###load batch using pickle###... |
c8f88cd3466856a6c69fd773c133fdc80b88c9e4 | DJMIN/leetcode | /20. 有效的括号.py | 1,217 | 3.5 | 4 | class Solution:
def isValid(self, s):
"""
:type s: str
:rtype: bool
"""
d = {
'(':')',
'[':']',
'{':'}',
}
if not s:
return True
def retneibu(s):
print(s)
houwei = s.find(d.get(s... |
a6e09a61e76d92c8b4a784be1937a25915045ab9 | BaptisteH3089/MEP | /creation_dict_bdd.py | 33,970 | 3.640625 | 4 | """
@author: baptistehessel
Creates the main dictionary with all the information about the pages of a
client.
The dict_pages is of the form:
{id_page: dict_page, ...}.
The dict_page includes several dictionary or list:
dict_page = {'arts': ..., 'cartons': ..., ...}.
The name of the object created is dict_page... |
00e30401d0237a2abe1522bbe8436ba2f773332f | SpencerReitz/ChessGame | /Chess.py | 1,092 | 3.78125 | 4 | # Top 2 lines just get rid of message saying hi from pygame community in your terminal
from os import environ
environ['PYGAME_HIDE_SUPPORT_PROMPT'] = '1'
import pygame
from pygame import mouse
from Board import Board
## Makes the game screen and names the window
pygame.init()
pygame.font.init()
pygame.display.set_capt... |
3081b981b3c1cc909ea8a84005bb3a47150af8db | Kelsi-Wolter/practice_and_play | /interview_cake/superbalanced.py | 2,487 | 4.1875 | 4 | # write a function to see if a tree is superbalanced(if the depths of any 2 leaf nodes
# is <= 1)
class BinaryTreeNode(object):
'''sample tree class from interview cake'''
def __init__(self, value):
self.value = value
self.left = None
self.right = None
def insert_left(self, value... |
6c27739896b5e2dfb67e55f2aa402d100c560c44 | kongzhidea/leetcode | /Rotate Array.py | 429 | 3.5 | 4 | class Solution:
# @param nums, a list of integer
# @param k, num of steps
# @return nothing, please modify the nums list in-place.
def rotate(self, nums, k):
l = []
ln = len(nums)
if ln == 0:
return
k = k - (k/ln)*ln
for i in range(k):
l.a... |
b93631e78166e3f89116584c18c5ed5862e49a1c | kongzhidea/leetcode | /Add Two Numbers.py | 793 | 3.65625 | 4 | # Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
# @return a ListNode
def addTwoNumbers(self, l1, l2):
ret = ListNode(-1)
start = ret
step = 0
while l1 !=None or l2 != None:
... |
d3b25de64807268ba580d9b8ed86e73ecb705e65 | kongzhidea/leetcode | /Power of Two.py | 212 | 3.5 | 4 | class Solution(object):
def isPowerOfTwo(self, n):
if n <= 0 :
return False
count = 0
while n > 0:
count += n&1
n = n >> 1
return count == 1 |
2cd91d3ba8aee03a4a174cefa4f68a5631715f31 | celetrik/bug-free-umbrella | /game.py | 515 | 3.5625 | 4 | # import random() feature from global module
from sys import argv
import random
script, player_name = argv
# set secret number range
lucky_numbers = random.random(1, 20)
# print (f"Hello , {player_name}")
# print("i'm thinking of a number between 1 and 20")
# print("Take a guess ")
# number = []
# guess = [input(),... |
2db9a0902d2156c3259a6eab59196b7df443ae7f | tkl-labo/NLP | /parsing/ishiwatari/cky.py | 2,555 | 3.578125 | 4 | # coding: utf-8
import sys
import itertools
from collections import *
def read_rules(filename):
grammar = defaultdict(list)
lexicon = defaultdict(list)
for line in open(filename, 'r'):
token = line.rstrip().split(' ')
if len(token) == 3:
grammar[token[0]].append(token[1:])
elif len(token) == 2:
lexicon[... |
2b99761e0c7f25f9cc7ff668f57900f1bc37ebe4 | syn1911/Python-spider-demo | /02spider/05.py | 4,041 | 4.0625 | 4 | # 数据信息提取:
import requests
from bs4 import BeautifulSoup
html = """
<html><head><title>The Dormouse's story</title></head>
<body>
<p class="title" name="dromouse"><b>The Dormouse's story</b></p>
<p class="story">Once upon a time there were three little sisters; and their names were
<a href="http://example.com/elsie" cl... |
a5f3ad733cbd219548ac46c9255d6844139ec0b1 | syn1911/Python-spider-demo | /02spider/08pyquery学习.py | 1,252 | 3.671875 | 4 | # 最像jquery 解析器
# 小实战,并且在此复习下soup 用法
# 爬取电影排行榜。抓取http 链接 https://movie.douban.com/top250
# 问题?怎么去操作翻页?需要以后去解决
# 使用pyquery 解决 类似于jquery
from pyquery import PyQuery as pq
import requests
headers = {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.88 Safa... |
876259e4bc9d00a29b2f557cb072a28907744fed | syn1911/Python-spider-demo | /00base/04.py | 3,641 | 3.609375 | 4 | # 字典结构
# 加单的字典结构
alien_0={'color':'green','point':5}
print(alien_0['color'])
print(alien_0['point'])
# 获取原来的点数,并增加自己的点数
people_0={'color':'red','point':10}
print("我自己存在的分数为:",people_0['point'])
newPoints=alien_0['point']
print("打败NPC,获取的分数为",newPoints)
print("此分数将加到我自己上")
people_0['point']=15
print("我自己存在的分数为:",peopl... |
670b7214859a130672426879491bb6384418fffc | syn1911/Python-spider-demo | /01improve/01.py | 1,420 | 3.734375 | 4 | # 提高篇,必须学习1-14中的语法内容,不然可能不懂分析过程
# 变量
# 1.首先找到3个人的身份证号。
# 2.放到3个变量中。
# 3.然后用切片工具把每个人的生日找出来并打印出来
# 分析:
# 首先创建一个列表,存放三个身份号码
# 然后通过遍历的方式,找出列表数字的生日
# 按照上面的要求分析:
# 定义三个变量,
# 然后切片找出生日,并打印
# 自己的方式
idCard = ['110120194906066533', '110120194908086533', '110120194902026533']
for ids in idCard:
print("自己的思路")
print("生... |
ff8bedbf08ae0261428f825f4d82ac0a5fac18cd | mth-prog/passwordGENERATOR | /passwordgenerator/arquivo pjp03.py.py | 2,626 | 3.5625 | 4 | from random import *
#Tipo da senha
Mat = []
Alu = open('MATR.txt','r')#Abre o arquivo da Matricula para ser lido
lendo = Alu.readline()
while lendo != '':
lendo = lendo.rstrip()
Mati = int(lendo)
Mat.append(Mati)
lendo = Alu.readline()
Alu.close()
senha = open('SENHAS.txt','w')# Abre... |
7a509a21141efc3cb25eeb3d61f69acf6766f5e1 | Adib234/python-cp-cheatsheet | /codesignal/string/findEmailDomain.py | 232 | 3.5625 | 4 | """
For address = "prettyandsimple@example.com", the output should be
findEmailDomain(address) = "example.com";
"""
def findEmailDomain(address):
return address.split('@')[-1]
def findEmailDomain(address):
return address[address.rfind('@')+1:] |
6fd06319af4fce6c776b03031f4851a273dc2bb7 | Adib234/python-cp-cheatsheet | /codesignal/string/variableName.py | 389 | 3.515625 | 4 | """
For name = "var_1__Int", the output should be
variableName(name) = true;
For name = "qq-q", the output should be
variableName(name) = false;
"""
def variableName(name):
if not name or name[0].isdigit():
return False
for c in name:
if not c.isalnum() and c != '_':
return False
... |
59fba76bee96eb2e350239127af2889dfc763d0a | tae-hyunkim/Univ_code | /2020.2학기/소프트웨어프로젝트/class06_Make_file_실습_과제/iterfibo_code.py | 1,046 | 3.515625 | 4 | import time
import random
def fibo(n):
if n <= 1:
return n
return fibo(n - 1) + fibo(n - 2)
'''
반복문 활용 파보나치 수열을 구하기 위해서 처음 0,1의 값을 가진 수열을 만들고
해당 값들의 index값 활용 리스트를 수정하며 작업을 진행 최종적으로 계속 삽입하는 방식이 아닌
매번 2개의 값을 수정하는 방식을 취하며 리스트 내의 공간도 확보함.
'''
def iterfibo(n):
if n <= 1:
return n
fn = [0,1]... |
d07187c10b0ce6fa2f23f17cc531b86d819016f6 | tae-hyunkim/Univ_code | /2020.2학기/과학과소프트웨어적사고/pyfile/에라토스테네스-김태현-20152640-1006.py | 571 | 3.671875 | 4 | import math
print("\n>>에라토스테네스의 체를 활용하여 소수를 출력하는 파일 입니다.")
input_number = int(input('>>탐색할 범위의 값을 입력해 주세요:'))
max_iter = int(math.sqrt(input_number))
number_list = list(range(1,input_number+1))
for i in range(2,max_iter+1):
if i in number_list:
for j in range(i+i,input_number+1,i):
number_li... |
172030f50c16834d5b1da3901fc4fe5cfbd4fe41 | tae-hyunkim/Univ_code | /2020.2학기/소프트웨어프로젝트/class06_Make_file_실습_과제/제어문.py | 366 | 3.75 | 4 | number = ['one','two','three','four','five']
for i in number:
if i == 'one': # continue는 다음 루프로 넘어가라는 의미
continue
elif i == 'two': # next는 다음에 존재하는 구문으로 넘어가라는 의미
next
elif i == 'four': # break는 반복문을 끝내라는 의미
break
print("Number is ", i)
|
b50d32c1aab0341185d37df839f89a539a3529ae | tae-hyunkim/Univ_code | /2020.2학기/과학과소프트웨어적사고/pyfile/day-김태현-20152640.py | 650 | 3.5 | 4 | import datetime
DayofWeek = ['월요일','화요일','수요일','목요일','금요일','토요일','일요일']
criteria = input("기준연월일을 입력해 주세요(ex20190308):")
day = datetime.datetime(int(criteria[:4]),int(criteria[4:6]),int(criteria[6:]))
print("입력하신 기준 날짜는 {} 입니다.".format(day.strftime("%Y-%m-%d")))
later = int(input("기준날짜에서 더하고 싶은 일수를 입력해 주세요: "))
ne... |
2adde14814324fd15fc5bfa61184264203e51d63 | tae-hyunkim/Univ_code | /2020.2학기/과학과소프트웨어적사고/pyfile/fibo-김태현-20152640.py | 1,129 | 3.953125 | 4 | import time
# for loop문을 활용할 때 list에 처음 두개의 값을 삽입한 후 결과를 계속해서 삽입해서 추가하는 방식으로 활용할 예정이다.
def fibonachi(n):
if (n==1) or (n==2):
return 1
else:
return fibonachi(n-1) + fibonachi(n-2)
n = 30
start = time.time()
print(n,fibonachi(n))
print("1) Running fibonachi(%d) takes %f"%(n,time.time()-start)... |
b27bf8051a15561fe50ca758ba82425cd59cd781 | tae-hyunkim/Univ_code | /2020.2학기/과학과소프트웨어적사고/pyfile/김태현-20152640-activation-function.py | 831 | 3.6875 | 4 | import math
'''
sigmoid 식을 풀어서 활용하면 e**x / ( 1 + e**x)이다.
이를 활용하기 위해 e**x 활용하여 구해보자.
'''
# 항의 개수를 10으로 하니 오차가 너무 커서 sigmoid function이 제대로 그려지지 않습니다.
def e_x50(x):
num = 0
for i in range(50):
num = num + x**i/math.factorial(i)
return num
def e_x(x):
num = 0
for i in range(10):
num ... |
d7955a29d3177efa8b6f558a9a26bd3a7c5f2c61 | mulualem04/ISD-practical-4 | /ISD practical4Q8.py | 282 | 4.15625 | 4 | # ask the user to input their name and
# asign it with variable name
name=input("your name is: ")
# ask the user to input their age and
# asign it with variable age
age=int(input("your age is: "))
age+=1 # age= age + 1
print("Hello",name,"next year you will be",age,"years old")
|
dea6662f177466907965874b0dff08e26c076608 | kitana-eh/kitana-eh.github.io | /python/for_loops_ex.py | 3,494 | 4.125 | 4 | fruits = ["kiwi", "strawberry", "plum"]
results = []
for item in fruits:
results.append(item)
print(results)
numbers = [1, 2, 3, 4, 5]
results =[]
for item in numbers:
results.append(item + 5)
print(results)
# Exercise 1 on page 16 of Python Programming Concepts II slides: Given a list of 5 numbers
# a for... |
863e5ed6991e9f1b684bc81a3104bc3edb22f8a3 | kath92/Password-saver | /password_saver.py | 690 | 3.53125 | 4 | import codecs
def encode(text, user_key):
return codecs.encode(encode_or_decode(text, user_key), "unicode_escape")
def decode(cipher, user_key):
return encode_or_decode(codecs.decode(cipher, "unicode_escape"), user_key)
def encode_or_decode(text, user_key):
result = ""
index = 0
for c in text:... |
e3664d19127e6677dc0dbd78538ca298e48ebcd2 | gkevinb/aoc-2020 | /day5/first.py | 853 | 3.578125 | 4 | input = "FFFBBBFRRR"
def binary_to_decimal(binary):
decimal = 0
order = 1
for b in binary[::-1]:
decimal += order * int(b)
order *= 2
return decimal
def find_seat_id(boarding_pass):
row_binary = boarding_pass[:7].replace("B", "1").replace("F", "0")
column_binary = boarding_pas... |
d2ce3096532b3ba628594e7115fdfcfb58698a42 | sabernn/VRP-RL | /tester.py | 293 | 3.625 | 4 |
import numpy as np
import matplotlib.pyplot as plt
A=np.random.random([10,3])
# print(A)
plt.plot(A[:,0],A[:,1],'o')
for i,e in enumerate(A[:,0]):
plt.text(A[i,0],A[i,1]," {0} ,{1}".format(i,round(A[i,2],1)))
idx=np.array([3,4,6,2,8,1,9,5,7,0])
plt.plot(A[idx,0],A[idx,1])
plt.show() |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.