blob_id stringlengths 40 40 | repo_name stringlengths 5 127 | path stringlengths 2 523 | length_bytes int64 22 3.06M | score float64 3.5 5.34 | int_score int64 4 5 | text stringlengths 22 3.06M |
|---|---|---|---|---|---|---|
9ae11d8cc57f5cf243312e80a71757398a2b1ed9 | Mengeroshi/python-tricks | /2.Efective-Functions/2.1lambda.py | 413 | 4.0625 | 4 | """ Lambda are single statement anonymous function """
add = lambda x, y: x + y
print(add(5, 3))
print((lambda x, y: x + y)(10, 20))
"""Sorting iterables with alt key """
tuples = [(1, 'd'), (2, 'b'), (4, 'a'), (3, 'c')]
tuples.sort(key=lambda x: x[1])
print(tuples)
""" this are the same"""
lel = list(range(-5,... |
edfe6a185579a75050b43f778ced88e263e092e1 | Mengeroshi/python-tricks | /1.Patterns-For-Clear-Python/2.1.with.py | 186 | 3.75 | 4 | with open('hello.txt', 'w') as f:
f.write("hello, world!")
#another way to write same code of with
f = open('hello.txt', 'w')
try:
f.write('hello world')
finally:
f.close() |
c0d0697f27c61f5800d36abcd0a9f38991e2773e | Mengeroshi/python-tricks | /2.Efective-Functions/1.6_objects_behave_like_func.py | 177 | 3.515625 | 4 | class Adder:
def __init__(self, n):
self.n = n
def __call__(self, x):
return self.n + x
plus_3 = Adder(3)
print(plus_3(4))
print(callable(plus_3)) |
10f120dc49d89ee274e6f0258bffcfe0a2a8d711 | Mengeroshi/python-tricks | /4.1.3.defaultdict.py | 347 | 3.6875 | 4 | """ default dict is dict subclass that returns a callable if the key cannot be found """
from collections import defaultdict
dd = defaultdict(list)
dd['dogs'].append('Rufus') # <---accessing to missimg key creates it and initializes it using default factory
dd['dogs'].append('Kathrin')
dd['dogs'].append('Mr Sniffle... |
c562dc0f6d4ab184c8a3b273567eeea000046026 | hagmanen/aoc2019 | /day21.py | 1,120 | 3.71875 | 4 | from intcomputer import intcomputer, input_ctrl
def main():
filename = 'day21_input.txt'
with open(filename, 'r') as f:
text = f.read()
program = [int(numeric_string) for numeric_string in text.split(",")]
imp_str = 'NOT A J\nNOT C T\nOR T J\nAND D J\nWALK\n'
comp_input = [ord(c... |
31da991ff741554de4a9e5e5f06be538f9a45fe1 | TPIOS/Small-Python-exercise | /nltk_exercise/chapter 1/lx01.py | 478 | 3.8125 | 4 | import re
mystring = "Monty Python ! And the holy Grail ! \n"
# print(mystring.split())
# print(mystring.strip())
# print(mystring.upper())
# print(mystring.replace('!',''''''))
# if re.search('Python', mystring):
# print("We found Python")
# else:
# print("No")
# print(re.findall('!',mystring))
... |
37edc4cb5cf76bb72b008ae6fd73d227f74cc59a | byteford/cx-interview-questions | /shopping_basket/shopping_basket/offers.py | 2,514 | 3.796875 | 4 | from . import utility
#To be implemented by other offers to add diffrent funcionality with each offer
class offer():
_multi = False
#sets up the offer
def __init__(self, **kwargs):
pass
#returns a float of the discount
def discount(self,**kwargs):
pass
#returns if the offer is f... |
54cdd55e67935f57596fe4d3c2945b504e665daf | Bladesmc/python-calculator | /factorial.py | 268 | 3.875 | 4 | def main():
print "the number of possible arrangements for a deck of cards is:\n" + str(factorial(52))
def factorial(n):
if n < 1:
return 1
else:
rN = n*factorial(n-1)
return rN
if __name__ == "__main__":
main()
|
1c77967940f1f8b17e50f4f2632fb34a13b3daf0 | sweetysweat/EPAM_HW | /homework1/task2.py | 692 | 4.15625 | 4 | """
Given a cell with "it's a fib sequence" from slideshow,
please write function "check_fib", which accepts a Sequence of integers, and
returns if the given sequence is a Fibonacci sequence
We guarantee, that the given sequence contain >= 0 integers inside.
"""
from typing import Sequence
def check_fibonacci... |
d10cd2ab04df7e4720f72bf2f5057768e8bfad3f | sweetysweat/EPAM_HW | /homework8/task_1.py | 1,745 | 4.21875 | 4 | """
We have a file that works as key-value storage,
each line is represented as key and value separated by = symbol, example:
name=kek last_name=top song_name=shadilay power=9001
Values can be strings or integer numbers.
If a value can be treated both as a number and a string, it is treated as number.
Write a wrappe... |
e13c26d81818de3cf64ed616d2371ae084552d4e | sweetysweat/EPAM_HW | /homework2/task5.py | 933 | 4 | 4 | """
Some of the functions have a bit cumbersome behavior when we deal with
positional and keyword arguments.
Write a function that accept any iterable of unique values and then
it behaves as range function:
assert = custom_range(string.ascii_lowercase, 'g') == ['a', 'b', 'c', 'd', 'e', 'f']
assert = custom_range(stri... |
1606b576295949aba9086faa032f3f551f804029 | xzhacker123/JsonTools | /json_utils/run_new.py | 3,513 | 3.5625 | 4 | # -*- coding: utf8 -*-
__author__ = 'Alex.xu'
import sys
class Stack():
def __init__(self):
self.stack = []
self.top = -1
def push(self, x):
self.stack.append(x)
self.top = self.top + 1
def pop(self):
''''''
if self.is_empty():
raise... |
dee8d17c68e2dc2e4e7514efab1cbfc6012bbbd8 | BasilArackal/TCSCodeVita | /CodeVita2016/Round1/CodeVita2016-2/solns/c.py | 322 | 3.78125 | 4 | def funk(mom):
totSweets = 0
for no in mom:
totSweets = totSweets + int(no)
return totSweets
def countThree(mom):
count = 0
for no in mom:
if(int(no)%3==0):
count = count + 1
return count+1
n = int(input())
mom = input().split()
if(funk(mom)%3==0):
print("Yes " + str(countThree(mom)))
else:
print("No"... |
0682dad3b4bf3825a68203cfba3e44dac8717bf9 | BasilArackal/TCSCodeVita | /CodeVita2016/Round1/CodeVita2016-2/solns/b.py | 207 | 3.578125 | 4 | import math
def nCr(n,r):
f = math.factorial
return f(n) / f(r) / f(n-r)
N, K = input().split()
N= int(N)
K = int(K)
res = 0
for k in range(0, K+1, 2):
res = res + int(nCr(N,k))
print( str(res) )
|
9c77241329e3d8e15dfdafb978272844f1697b0d | AT-Fieldless/python | /daily_exercise/0011.py | 463 | 3.734375 | 4 | # -*- coding: utf-8 -*-
# 敏感词文本文件 filtered_words.txt,里面的内容为以下内容,当用户输入敏感词语时,则打印出 Freedom,否则打印出 Human Rights。
s = set()
def define():
file = open("filtered_words.txt")
for eachline in file:
s.add(eachline.rstrip('\n'))
if __name__ == '__main__':
define()
temp = raw_input()
if temp in s:
... |
4209cfd3b879e1c02531a7e8dae52dee26d2cce0 | bahadirsensoz/PythonCodes | /fahrenheit.py | 266 | 4.28125 | 4 | while(True):
print("CELSIUS TO FAHRENHEIT CONVERTER")
celsius = float(input("Please enter your degree by celcius:"))
#Ali Bahadır Şensöz
fahr=1.8*celsius+32
print("Your temperature " +str(celsius) + " Celsius is " +str(fahr) + " in Fahrenheit.")
|
d8aa4ae8c2cee23df820c18d73109975a079a027 | EmilioMuniz/ops-401d2-challenges | /class42.py | 1,870 | 3.6875 | 4 | #!/usr/bin/env python3
# Script: ops-401d2-challenge-class42.py
# Author: Emilio Muniz
# Date of latest revision: 6/02/2021
# Purpose: Attack tools Part 2 of 3.
# Import libraries:
import nmap
# Declare variables:... |
9508589a5b285805d6cc8d80d6c3a8a7732b3dc0 | bangdasun/leetcode-bangdasun | /2017/Algorithms/252-easy-MeetingRooms.py | 1,032 | 3.9375 | 4 | """
LeetCode 252
Easy
Meeting Rooms
Given an array of meeting time intervals consisting of start and end times [[s1,e1],[s2,e2],...] (si < ei),
determine if a person could attend all meetings. For example, Given [[0, 30],[5, 10],[15, 20]], return false.
"""
def meeting_rooms(intervals):
"""
Sort the meeting... |
50e50015e425e4ba5a924775ded68b79cba31edc | sawall/advent2017 | /advent_6.py | 2,729 | 4.21875 | 4 | #!/usr/bin/env python3
# memory allocation
#
#### part one
#
# The debugger would like to know how many redistributions can be done before a blocks-in-banks
# configuration is produced that has been seen before.
#
# For example, imagine a scenario with only four memory banks:
#
# The banks start with 0, 2, 7, and 0 bl... |
3f20d400e5da5a21660eda19a5cb456888367074 | Kevinskwk/ILP | /Midterm/Midterm-Ma Yuchen-2.py | 174 | 3.703125 | 4 | i=1
a=0
b=1
while b<=10**999:
a,b=b,a+b
i+=1
print ("The "+str(i)+"th term is the first term to have 1000 digits.\n")
print ("The number is:\n"+str(b))
|
65c1080bcbaf60e4d4bfab7d33d8f18a796dd42d | Kevinskwk/ILP | /week3/week3 6.py | 227 | 3.609375 | 4 | lista=[1,2,3,4,5,6,7,8,8]
l=len(lista)
n=False
for x in range(l):
for y in range(l):
if x!=y and lista[y]==lista[x]:
n=True
if n==True:
print ('Yes')
else:
print('No')
|
b7254172d3a752293aa0314c38e5f627509ebc67 | aymhh/School | /conditional-statements/numberSeries.py | 814 | 3.984375 | 4 | import time
x = input("What number do you want to start the count from?\n")
while not x.isnumeric():
x = input("That is not a number...\nWhat number do you want to start the count from?\n")
xInt = int(x)
y = input("What number do you want to end the count on?\n")
while not y.isnumeric():
y = input("What numbe... |
910db0a0156d0f3c37e210ec1931fd404f1357e9 | aymhh/School | /Holiday-Homework/inspector.py | 1,095 | 4.125 | 4 | import time
print("Hello there!")
print("What's your name?")
name = input()
print("Hello there, " + name)
time.sleep(2)
print("You have arrived at a horror mansion!\nIt's a large and spooky house with strange noises coming from inside")
time.sleep(2)
print("You hop out of the car and walk closer...")
time.sleep(2)
pri... |
24d025d8a89380a8779fbfdf145083a9db64fc07 | shahad-mahmud/learning_python | /day_16/unknow_num_arg.py | 324 | 4.15625 | 4 | def sum(*nums: int) -> int:
_sum = 0
for num in nums:
_sum += num
return _sum
res = sum(1, 2, 3, 5)
print(res)
# Write a program to-
# 1. Declear a funtion which can take arbitary numbers of input
# 2. The input will be name of one or persons
# 3. In the function print a message to greet every ... |
78c20cf1465a7b633372c8635ae011b2d2db84df | shahad-mahmud/learning_python | /day_3/even_odd.py | 151 | 4.40625 | 4 | # even if -> number % 2 == 0
number = int(input('Enter a number: '))
if number % 2 == 1:
print('Odd')
else:
print('Even')
# -3 / 2 = -2, 1 |
c20d7062f3a08c081d7c38a35da3963ef553421e | shahad-mahmud/learning_python | /day_5/tricks.py | 109 | 3.890625 | 4 | while True:
number = int(input('Enter a number (-1 to stop): '))
if number == -1:
break
|
b7109f030f7149817c937e569dd19a58fbeda29e | shahad-mahmud/learning_python | /day_14/uri_1013.py | 525 | 3.640625 | 4 | def max_num(a, b):
if a > b:
return a
return b
def abs(x):
if x >= 0:
return x
return -x
inp = input()
inp = inp.split()
a, b, c = int(inp[0]), int(inp[1]), int(inp[2])
m_num = max_num(a, max_num(b, c))
# s_m = max_num(b, c) if m_num == a else max_num(
# c, a) if m_num == b else m... |
382a8a2f5c64f0d3cd4c1c647b97e19e2c137fda | shahad-mahmud/learning_python | /day_3/if.py | 417 | 4.1875 | 4 | # conditional statement
# if conditon:
# logical operator
# intendation
friend_salary = float(input('Enter your salary:'))
my_salary = 1200
if friend_salary > my_salary:
print('Friend\'s salary is higher')
print('Code finish')
# write a program to-
# a. Take a number as input
# b. Identify if a number is po... |
ec55765f79ce87e5ce0f108f873792fecf5731f6 | shahad-mahmud/learning_python | /day_7/python_function.py | 347 | 4.3125 | 4 | # def function_name(arguments):
# function body
def hello(name):
print('Hello', name)
# call the funciton
n = 'Kaka'
hello(n)
# Write a program to-
# a. define a function named 'greetings'
# b. The function print 'Hello <your name>'
# c. Call the function to get the message
# d. Modify your function and add a... |
f26bfae29250589012708c5fbee61d598acc3e02 | rewatevijaykumar/python-webscrap-beautifulsoup | /deadly-earthquake.py | 1,106 | 3.59375 | 4 | # Web Scrapping Using BeautifulSoup
# List of deadly earthquakes since 1900
from bs4 import BeautifulSoup
import requests
url = 'https://en.wikipedia.org/wiki/List_of_deadly_earthquakes_since_1900'
r = requests.get(url)
html_content = r.text
html_soup = BeautifulSoup(html_content, 'html.parser')
earthquak... |
b0824befae2b1d672ac6ec693f97e7c801366c0c | srinivasdasu24/regular_expressions | /diff_patterns_match.py | 1,534 | 4.53125 | 5 | """
Regular expression basics, regex groups and pipe character usage in regex
"""
import re
message = 'Call me at 415-555-1011 tomorrow. 415-555-9999 is my office.'
phoneNum_regex = re.compile(
r'\d\d\d-\d\d\d-\d\d\d\d') # re.compile to create regex object \d is - digit numeric character
mob_num = phoneNum_re... |
9d422749ea092c68345a08d83a7d6f49878d4a36 | missile777/learning | /lesson2.py | 447 | 3.828125 | 4 | import unittest
def reverse(n: list):
# do this function
return list(reversed(n))
class TestListMethod(unittest.TestCase):
def test_get_reverse1(self):
nums = [10, 20, 40, 80]
self.assertListEqual(reverse(nums), [80, 40, 20, 10])
def test_get_reverse2(self):
nums = [10, 20, ... |
100afd225a0be3eb88af57181652a24805db3080 | igor-rufino/C214-unittest | /tests/test_lances.py | 2,354 | 3.5 | 4 | import unittest
from src.dominio import Cliente, Lance, Leilao
class TestLances(unittest.TestCase):
def setUpClass():
# SetUp antes de todos os testes da classe
pass
def setUp(self):
# SetUp antes de cada testes da classe
self.phyl = Cliente("Phyl")
self.lance_do_phyl... |
f14563d83628511d21cd06a2d8799f8405549747 | asya5/code-analyse-klas-1e | /no.py | 795 | 3.625 | 4 | #does the user give an input to num?
#assignment analyse case 1 to 5 checked and correct
#CASE 1
num = 123456786
x = [int(a) for a in str(num)]
n = x.pop()
z = (sum(x))
if z%10== n:
print('VALID')
else:
print ('INVALID')
#CASE 2
num = 123456789
x = [int(a) for a in str(num)]
n = x.pop()
z = (sum(x))
i... |
3865e404fdf198c9b8a6cb674783aa58af2c8539 | rehul29/QuestionOfTheDay | /Question8.py | 561 | 4.125 | 4 | # minimum number of steps to move in a 2D grid.
class Grid:
def __init__(self, arr):
self.arr = arr
def find_minimum_steps(self):
res = 0
for i in range(0, len(self.arr)-1):
res = res + self.min_of_two(self.arr[i], self.arr[i+1])
print("Min Steps: {}".format(res))
... |
0a95bf073d27303f600b76a53cb2ad616a757407 | hamiltonmneto/College | /Pesquisa_Ordenação_de_Dados/selection_sort.py | 615 | 3.75 | 4 | def select_max(A, left, right):
max_pos = left
i=left
while i<= right:
if A[i] > A[max_pos]:
max_pos = i
i = i + 1
return max_pos
def selection_sort(A):
for i in range (len(A) - 1, 0, -1):
max_pos = select_max(A,0,i)
if max_pos !=i:
... |
5b8c4351f132c0695d521ed31ede600e6689d453 | sfyc23/KotlinWeeklyBuilder | /common/add_spaces.py | 1,309 | 3.75 | 4 | import sys
import functools
# Some characters should not have space on either side.
def allow_space(c):
'''
:param c: str
:return: Bool True 允许加空格,False 不允许加空格
'''
return not c.isspace() and not (c in ',。;「」:《》『』、[]()*_')
def is_latin(c):
'''
判断是否为英文字符,或者是数字
:param c: str
:return... |
6bb8df8f913d958ec9f6d4d18972cba9c1b53dfb | hashmand/Python_Programs | /Tkinter GUI Program/Login.py | 792 | 3.671875 | 4 | import tkinter as tk
from tkinter import messagebox
def hello():
l1 = tk.Label(win, bg="yellow",text=msg, width=20)
l1.place(x = 50, y = 250)
win = tk.Tk()
win.geometry("500x500+50+50")
l2 = tk.Label(win, bg="yellow",text="username", width=20)
l2.place(x = 50, y = 50)
l3 = tk.Label(win, bg="yellow",text="passw... |
7736a04d75a89f40c01f912cdd8c50b6399243e7 | hashmand/Python_Programs | /Tkinter GUI Program/button.py | 446 | 3.671875 | 4 | import tkinter as tk
from tkinter import messagebox
def hello():
msg = e1.get()
l1 = tk.Label(win, bg="yellow",text=msg, width=20)
l1.place(x = 50, y = 250)
win = tk.Tk()
win.geometry("500x500+50+50")
e1 = tk.Entry(win, bg="yellow",width=20)
e1.place(x = 50, y = 50)
b1 = tk.Button(win, text = "Click Me",... |
525e3c9b48be4b2e2320c38a0712e84e716050a4 | hhayoung/python-basic | /day02_print.py | 1,020 | 3.9375 | 4 |
# 기본 출력
print('hello python')
print("hello python")
print()
print('''hello python''')
print("""hello python""")
# saparator 옵션
print('T','E','S','T',sep='/')
# separator를 이용해서 TEST 출력
print('T','E','S','T',sep='')
# 2020-07-14 출력
print('2020','07','14',sep='-')
# test@naver.com
print('test','nave... |
a9130f9ff185e788be9908f75a0594ec89ebbcbe | missdavid7/LPTHW | /ex5.py | 755 | 3.53125 | 4 | my_name = 'Zed A.Shaw'
my_age = 35 # not a lie
my_height = 74 # inches
my_weight = int(180) #lbs
my_eyes = 'blue'
my_teeth = "white"
my_hair = "brown"
print "Let's talk about %r." % my_name
print "He's %r inches tall." % my_height
print "He's %d lbs heavy." % my_weight
print "Actually that's too heavy."
print "He's g... |
2b5896a2583a6e84dd7ca815ae87ef3059647f0e | Ashi-s/coding_problems | /FT_Coding/Akuna/almostequivalent.py | 1,538 | 3.515625 | 4 | # def almost(s,t):
# if len(s) != len(t):
# return ["NO"]
# s_d = {}
# t_d = {}
# for i, j in zip(s,t):
# if i not in s_d:
# s_d[i] = 1
# else:
# s_d[i] += 1
# if j not in t_d:
# t_d[j] = 1
# else:
# t_d[j] += 1
# ... |
639cb33ebaaedf49bc3ae027c66b067d83ed435c | Ashi-s/coding_problems | /FT_Coding/nutanix/primeString.py | 826 | 3.78125 | 4 | import math
def isPrime(n):
for i in range (2,int(math.sqrt(n))+1):
if n%i==0:
return False
return True
def primeString(string):
res = []
for i in string:
ascii = ord(i)
if isPrime(ascii):
res.append(i)
else:
s = True
j = ascii
... |
a61490294c12a1362f591338340ca251a09c6f0a | Ashi-s/coding_problems | /DevPost/letterOnlyOccursOnce.py | 1,485 | 3.828125 | 4 | '''
Input: "eeeeffff"
Output: 1
Why? We can delete one occurence of e or one occurence of 'f'.
Then one letter will occur four times and the other three times.
Input: "aabbffddeaee"
Output: 6
Why:
For example, we can delete all occurences of 'e' and 'f'
and one occurence of 'd' to obtain the ... |
568f7b406b12c5d04875290d51d3da935ddf8801 | kaitlynning/String-Concatenating | /0229.py | 1,125 | 3.953125 | 4 | row =int(input('Insert num: '))
for i in range(row):
for _ in range(i + 1):
#end=add space no newline
print('*', end = '')
#wrap text
print()
for i in range(row):
for j in range(row):
if j < row -i - 1:
print(' ', end = '')
else:
print('*', end = '')
print()
for i in range(row):
for j in range(ro... |
06a6612ce00ab2fb58911d9e06ab1f3a39f07021 | Rohika379/-Ridge-Regression-and-Lasso-Regression | /computer new.py | 7,969 | 3.546875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Tue Apr 13 20:41:32 2021
@author: USER
"""
import pandas as pd
#loading the dataset
computer = pd.read_csv("D:/BLR10AM/Assi/25.lasso ridge regression/Datasets_LassoRidge/Computer_Data (1).csv")
#2. Work on each feature of the dataset to create a data dictionary a... |
22661986936f2a7479a52080943c1e351903608c | supercatex/Connect4 | /Agent.py | 5,709 | 3.53125 | 4 | #!usr/bin/env python
import random
import copy
from GameBoard import GameBoard
import numpy as np
class Agent(object):
def __init__(self, name, player, game):
self.name = name
self.player = player
self.game = game
def get_choice(self):
return self.game.get_user_input()
class RandomAgent(Agent):
def ge... |
e4dd34a7234efac3c151931ce62e092ed32fba9f | Ameenakeem/Guess-game | /Guess game.py | 1,141 | 4 | 4 | win = 0
lose = 0
while True:
import random
comp = random.randint(1,5)
choose = int(input("Guess any number 1-5: "))
if comp == 1:
print("bot = 1")
elif comp == 2:
print("bot = 2")
elif comp == 3:
print("bot = 3")
elif comp == 4:
print("bot ... |
e671a6a094f5e1315c2088294bb2c2b85734d3b6 | PisciTec/PP | /PythonBasics-OO/python-twitter-searcher.py | 283 | 3.734375 | 4 | import math
def areasquare(lado):
return lado**2
print('Alo mundo')
numero = []
soma = 0
math.pi
soma = float(input("Escreva aqui o quanto você ganha por hora:"))
horas = float(input("Escreva aqui o quanto você trabalha em horas:"))
print('Esse é o seu salário:',soma*horas)
|
4bd0e226f38b81ed7c10e9cc30102b6238b63e26 | abc8737/python-private-demo | /zhibo8/MySQLPy.py | 1,915 | 3.875 | 4 | # coding=utf-8
'''
Python连接MySQl
'''
import pymysql
class Python_MySQL():
'''
host:主机名
userName:数据库拥有者
password:数据库登录密码
tableName:数据库名
'''
def __init__(self, host, userName, paassword, tableName):
self.host = host
self.userName = userName
self.password = paasswo... |
45ca0cfc0b54d9d9f142d53f24c2d4d41ac241dc | emisticg/ai2-2017 | /lab3-functions.py | 8,868 | 4.34375 | 4 | #
# Exploring Arguments and Parameters
#####################################
#
# Familiar Functions
#####################################
print("\n############## Familiar Functions ##############\n ")
def print_two(a, b):
print("Arguments: {0} and {1}".format(a, b))
# print_two() #invalid
print_two(4, 1... |
e920de82ab3d6bd364e6e2c884011cd69f84dffd | nickkeesG/CSC_project | /expert_vs_crowd/expert_vs_crowd_sim.py | 1,326 | 3.578125 | 4 | import numpy as np
import matplotlib.pyplot as plt
def expert_chooses(crowd):
expert = max(crowd)
if np.random.uniform(0,1) < expert:
return 1
else:
return 0
def crowd_chooses(crowd):
ballots = []
for c in crowd:
if np.random.uniform(0,1) < c:
ballots.append(1)
... |
a5200321001956e5d2321ee175b7f4c984e83b4a | yunlongmain/python-test | /gen.py | 450 | 4 | 4 | # -*- coding: utf-8 -*-
print("\n生成器")
# 生成器
def gen():
i = 10
yield i
i += 1
yield i
for j in gen():
print(j)
def gen():
for i in range(4):
yield i
for j in gen():
print(j)
# 生成器 表达式
gen = (x for x in range(4))
for j in gen:
print(j)
# 表推导
print("\n表推导")
L = []
for x in... |
3692d89377ea9e7fe97e49d1f0c55ed6f31fe438 | yunlongmain/python-test | /lib-test/test-itertools.py | 1,091 | 3.640625 | 4 | # coding=utf-8
from itertools import *
# 无穷循环器
'''
count(5, 2) #从5开始的整数循环器,每次增加2,即5, 7, 9, 11, 13, 15 ...
cycle('abc') #重复序列的元素,既a, b, c, a, b, c ...
repeat(1.2) #重复1.2,构成无穷循环器,即1.2, 1.2, 1.2, ...
repeat也可以有一个次数限制:
repeat(10, 5) #重复10,共重复5次
'''
# imap函数与map()函数功能相似,只不过返回的不是序列,而是一个循环器
rlt = map(pow, ... |
fc8f181a8762672b7d63af6a7d6155119e4d704a | ywtail/leetcode | /12_169.py | 885 | 3.65625 | 4 | # coding:utf-8
# Majority Element 多数元素
nums=map(int,raw_input().split())
def majorityElement_1(nums):
"""
:type nums: List[int]
:rtype: int
"""
n=len(nums)
dic={}
for i in range(n):
if nums[i] in dic:
dic[nums[i]]+=1
else:
dic[nums[i]]=1
if d... |
008d052de6adf2f904b77235bc96b95612bd13ac | ywtail/leetcode | /71_389_2.py | 823 | 3.546875 | 4 | # coding:utf-8
# 389. Find the Difference 找不同
# 42ms beats 93.97%
class Solution(object):
def findTheDifference(self, s, t):
"""
:type s: str
:type t: str
:rtype: str
"""
x = list(s) + list(t)
ans = 0
for i in range(len(x)):
ans ^= ord(x[i... |
b24b8cb5a6a7200c99bc112b9d5812eb9726bc60 | ywtail/leetcode | /35_58.py | 616 | 4.125 | 4 | # coding:utf-8
# Length of Last WordLength of Last Word 最后一个词的长度
s=raw_input()
def lengthOfLastWord(s):
"""
:type s: str
:rtype: int
"""
t=s.split()
if len(t)==0:
return 0
else:
return len(t[-1])
print lengthOfLastWord(s)
"""
题目:
给定一个字符串s由大写/小写字母和空格字符''组成,返回字符串中最后一个字的长度。
如果最后一个字不存在,返回0。
注意:单词定义为仅由非空格字符组成... |
83763bde554e2262ccaadf7eb716cd092a2ac367 | ywtail/leetcode | /23_231.py | 411 | 4 | 4 | # coding:utf-8
# Power of Two 二的幂
n=int(raw_input())
def isPowerOfTwo(n):
"""
:type n: int
:rtype: bool
"""
if n<=0:
return False
elif n==1:
return True
else:
while n>1:
if n%2==0:
n=n/2
else:
return False
return True
print isPowerOfTwo(n)
"""
2
True
题目:
给定一个整数,写一个函数来确定它是否为2的幂。
(注意:有可... |
ac1df34f0634dee917a178c5a4c39ff245d4ad2e | ywtail/leetcode | /6_14.py | 982 | 3.59375 | 4 | # coding:utf-8
# Longest Common Prefix 最长公共前缀
strs=raw_input().split()
def longestCommonPrefix(strs):
"""
:type strs: List[str]
:rtype: str
"""
n=len(strs)
num=0
if n>0:
num=len(strs[0])
for i in range(1,n):
if num==0:
break
temp=0
... |
e4d764310e6f59fefd2de5024ff317f3bcf5e146 | ywtail/leetcode | /70_204.py | 892 | 3.5625 | 4 | # coding:utf-8
# 204. Count Primes 素数数
# 869ms beats 62.89%
class Solution(object):
def countPrimes(self, n):
"""
:type n: int
:rtype: int
"""
if n <= 2:
return 0
re = [1] * n
for i in range(2, int(n ** 0.5) + 1): # 只需要到 sqrt(n)
if re... |
2523c9163f640eb7570f3a17c6d2d6838baaaed0 | ywtail/leetcode | /58_566_2.py | 1,973 | 3.625 | 4 | # coding:utf-8
# 566. Reshape the Matrix 重塑矩阵
# 205ms beats 26.08%
class Solution(object):
def matrixReshape(self, nums, r, c):
"""
:type nums: List[List[int]]
:type r: int
:type c: int
:rtype: List[List[int]]
"""
n = len(nums)
m = len(nums[0])
... |
9021ca9e375c5114fddfb39e507b95902ce923f8 | ywtail/leetcode | /66_121_2.py | 1,731 | 3.796875 | 4 | # coding:utf-8
# 121. Best Time to Buy and Sell Stock 买卖股票
# 59ms beats 34.93%
class Solution(object):
def maxProfit(self, prices):
"""
:type prices: List[int]
:rtype: int
"""
n = len(prices)
if n < 2:
return 0
max_cur = 0
max_sofar = 0
... |
8c5a93b99d7878cea460afd9d488dbbadf9a39df | SRI-VISHVA/Pandas | /day_6/analytics_3.py | 1,213 | 3.875 | 4 | # Objective
# To find the average age of male and female candidates using pandas
import pandas as pd
import numpy as np
from day_6.list_tuple import main_list
from datetime import date, datetime
from datetime import date
today = date.today()
def calculate_age(born):
today = date.today()
return today.year - ... |
f2852937a8ccd26a097ba7094852c2c13fe536dd | WassimBenzarti/DataScienceCheckpoints | /Checkpoint1/ex1.py | 176 | 3.90625 | 4 | text = input("Hello, please talk\n")
print("Your talk is {} chars long".format(len(text)))
print("words={}, spaces={}".format(
len(text.split(" ")),
text.count(" ")
)) |
5a8494efaee7fde7782fa3a5910a786e76ca7f96 | WassimBenzarti/DataScienceCheckpoints | /Checkpoint1/ex2.py | 159 | 3.890625 | 4 | a = int(input("Type a:\n"))
b = int(input("Type b:\n"))
print("input: a={}, b={}".format(a,b))
c = a
a = b
b = c
print("input: a={}, b={}".format(a,b)) |
836473508e62183e7d8b269440a89a106000f11d | AdrianGallo98/TweepySE | /plot1.py | 912 | 3.546875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Mon Sep 21 14:02:49 2020
@author: Adrian Gallo
"""
import matplotlib.pyplot as plt
import matplotlib.animation as animation
from matplotlib import style
import pandas as pd
style.use('fivethirtyeight')
fig = plt.figure()
ax1 = fig.add_subplot(1,1,1)
x = []
pos = []
neg = []
ne... |
fd12f0e509ecf0c186a156a645d1b078166527de | nielsenjared/algorithms | /11-array-partition/main.py | 545 | 3.921875 | 4 | def swap(arr, left, right):
temp = arr[left]
arr[left] = arr[right]
arr[right] = temp
return arr
# TODO Hoare
def partitionLomuto(arr, left = 0, right = None):
if right == None:
right = len(arr) - 1
pivot = arr[right]
index = left
for i in range(left, right):
... |
7787ec8e52e7c9fece089e8ba745f0e69add93ad | nielsenjared/algorithms | /01-swap/main.py | 122 | 3.96875 | 4 | x = 123
y = 456
def swap(x, y):
temp = x
x = y
y = temp
return (x, y)
result = swap(x, y)
print(result) |
729e39a20eabb246536a39ea6585699262088905 | nielsenjared/algorithms | /16-insertion-sort/main.py | 388 | 4.0625 | 4 | def insertion_sort(list):
for curr in range(1, len(list)):
temp = list[curr]
prev = curr - 1
while(prev >= 0):
if (list[prev] > temp):
list[prev + 1] = list[prev]
list[prev] = temp
prev = prev - 1
return list
list = [10, 1, 9... |
5b7c929f5305f9aee2af8c5e1ec7c02358a60a8c | jittania/core-problem-set-recursion | /part-1.py | 1,193 | 3.890625 | 4 | # There are comments with the names of
# the required functions to build.
# Please paste your solution underneath
# the appropriate comment.
#=============================================================================
# factorial
def factorial(n):
if n == 0:
return 1
try:
return factorial(n-... |
1c55fb74f1c254f4520b91e3c96e1df42aa45743 | lazistar/Nado_Practice | /data type/data type_변수.py | 560 | 3.546875 | 4 | # 애완동물을 소개해 주세요~
animal = "강아지"
name = "연탄이"
age = 4
hobby = "산책"
is_adult = age >= 3
# print("우리집" + animal + "의 이름은" + name + "이에요")
# hobby = "공놀이"
# print(name, "는 ", age, "살이며,", hobby, "을 아주 좋아해요.")
# print(name + "는 어른일까요? " + str(is_adult))
print("우리집 {0}의 이름은 {1}에요.".format(animal, name))
print("{0}는 {1}살이며... |
5b13b24acbbc286305aa9cda7adc9afd7709104f | sjNT/checkio | /Elementary/Fizz Buzz.py | 1,288 | 4.15625 | 4 | """
"Fizz buzz" это игра со словами, с помощью которой мы будем учить наших роботов делению. Давайте обучим компьютер.
Вы должны написать функцию, которая принимает положительное целое число и возвращает:
"Fizz Buzz", если число делится на 3 и 5;
"Fizz", если число делится на 3;
"Buzz", если число делится на 5;
"""
... |
e0fc07696c72475b1dcfa376084f2ef16bfb0b22 | sjNT/checkio | /Elementary/Second Index.py | 1,607 | 3.890625 | 4 | """
Даны 2 строки. Необходимо найти индекс второго вхождения второй строки в первую.
Разберем самый первый пример, когда необходимо найти второе вхождение "s" в слове "sims".
Если бы нам надо было найти ее первое вхождение, то тут все просто: с помощью функции index или find мы можем узнать,
что "s" – это самый перв... |
5e7cb56c67e23bf802c689e64f15619e25fde9a7 | sjNT/checkio | /Home/Time Converter (24h to 12h).py | 1,426 | 3.84375 | 4 | """
Вы предпочитаете использовать 12-часовой формат времени, но современный мир
живет в 24-часовом формате и вывидите это повсюду.
Ваша задача - переконвертировать время из 24-часового формата в 12-часовой,
использкя следующие правила:
- выходной формат должен быть 'чч:мм a.m.' (для часов до полудня) или 'чч:мм p.m.' (... |
f6328df30cd69193ea4182ba56d55c88fd3f5781 | dtekluva/first_repo | /variance/variance.py | 887 | 3.96875 | 4 | # numbers = [4,5,3,6,5]
# mean_nums = sum(numbers)/len(numbers) # ALSO OUR X_BAR
# print("MEAN : ", mean_nums)
# for number in numbers:
# print(number, round(number - mean_nums, 1), (number - mean_nums)**2)
###############################
# A MORE DESCRIPTIVE APPROACH #
###############################
nu... |
1e30e88c79c0941f93ce4239a74eb38d4dcd02f5 | dtekluva/first_repo | /datastructures/ato_text.py | 1,616 | 4.125 | 4 | # sentence = input("Please enter your sentence \nWith dashes denoting blank points :\n ")
# replacements = input("Please enter your replacements in order\nseperated by commas :\n ")
# ## SPLIT SENTENCE INTO WORDS
# sentence_words = sentence.split(" ")
# print(sentence_words)
# ## GET CORRESPONDING REPLACEMENTS
# rep... |
798c8c8298cdfe9cc86bed320be8ab80e4aae5ba | dtekluva/first_repo | /class3.py | 5,130 | 3.84375 | 4 | # math_score = input("Please enter math score : ")
# english_score = input("Please enter english score : ")
# math_score = int(math_score)
# english_score = int(english_score)
# print()
# print("Qualified for Engineering".ljust(26), ":", math_score >= 80 and english_score >= 70)
# print("Qualified for Business".ljust... |
49498d9b2b5aa8355dc9924b7c42fe307b383f09 | edusanketdk/interview-practice | /multiply number strings/solution3.py | 924 | 3.765625 | 4 | # for very large numbers
# without directly using multiplication
def multiplyStrings(s1, s2):
isneg1, isneg2 = 1 if s1[0]=='-' else 0, 1 if s2[0]=='-' else 0
s1, s2 = s1[1:] if isneg1 else s1, s2[1:] if isneg2 else s2
finalsign = "-" if isneg1+isneg2 == 1 else ""
ans = [0]*(len(s1)+len(s2))
id1, i... |
1db69ed4f41ead6b2ebca457dfcb7200641dc09b | edusanketdk/interview-practice | /rotate matrix/solution1.py | 550 | 3.9375 | 4 | def rotateby90(a, n):
for i in range((n+1)//2):
for j in range(n//2):
a[i][j], a[n-i-1][n-j-1], a[n-j-1][i], a[j][n-i-1] = \
a[j][n-i-1], a[n-j-1][i], a[i][j], a[n-i-1][n-j-1]
"""
from the rotation pattern it is observed that
the rotation of each element can be visualised as a... |
e945ee5667f6a6b11fa47f3f4a60e2838253b019 | edusanketdk/interview-practice | /reverse alternate k nodes/solution1.py | 521 | 3.609375 | 4 | # simplest approach
def reverse_alt_k(head, k):
ar = []
cur = head
while cur:
ar.append(cur.val)
cur = cur.next
br = []
for i in range(0, len(ar), k):
cur = ar[i:i+k]
cur.reverse()
for j in cur:
br.append(j)
newll = linked_list()
for i ... |
02b914177c985cfa117a75923d0899134c53a8ee | NewbieAI/NewbieAI.github.io | /scripts/segments/neuralnet3.py | 4,644 | 3.671875 | 4 | class DeepNeuralNet:
# The class contains at least 0 hidden layer
# and exactly 1 output layer
# To create a dnn object, specify the structure
# and the output units of the network. The class
# will automatically initiate the weights and
# bias in each layer. The loss function should
# also... |
3782aeec5e97417d57515bd8b9bd54d1c4f5559a | Fernandomn/Ufba | /MATD74 - Algoritmos e Grafos/Atividades/Lista1/1015_DISTANCIAPONTOS.py | 347 | 3.65625 | 4 | import math
a = input()
b = input()
ponto1 = a.split(' ')
ponto2 = b.split(' ')
ponto1[0], ponto1[1] = float(ponto1[0]), float(ponto1[1])
ponto2[0], ponto2[1] = float(ponto2[0]), float(ponto2[1])
difX = ponto1[0]-ponto2[0]
difY = ponto1[1]-ponto2[1]
distancia = math.sqrt(math.pow(difX, 2) + math.pow(difY, 2))
print('... |
1bf46f3ccc9861cfb285358497fa83fcc2c41969 | FedeVerstraeten/tda1-fiuba | /tp1/src/all_sorting.py | 5,851 | 3.640625 | 4 | #!/usr/bin/python
import random
from random import randint
import time
import sys
import csv
import pprint
SIZE_ARRAY = 10000
MAX_NUM = 10000
NUM_ARRAYS = 10
sys.setrecursionlimit(15000000)
###################### Heap Sort ##################################
def swap(i, j, arr):
arr[i], ar... |
b9a6f5dfa9f184d24f941addd3aa219dcc16a1bd | harrylb/anagram | /anagram_runner.py | 2,436 | 4.3125 | 4 | #!/usr/bin/env python3
"""
anagram_runner.py
This program uses a module "anagram.py" with a boolean function
areAnagrams(word1, word2)
and times how long it takes that function to correctly identify
two words as anagrams.
A series of tests with increasingly long anagrams are performed,
with the word length and ... |
9e6405c1f69759cf3d8891a3f97a544b2f30eca2 | babooloon/CLRS_Algorithm-DataStructure_Python | /CoutingSort.py | 889 | 3.859375 | 4 | #!/usr/bin/env python2
# -*- coding: utf-8 -*-
"""
Created on Wed Nov 8 12:10:34 2017
@author: paulyang
"""
# Time Complexity: O(n + k)
# Auxiliary Space: O(k)
def countingSort(nums):
# Ensure that nums are non negative
assert min(nums) >= 0, 'Numbers in nums must be nonnegative.'
# Find the maximum numb... |
1faee04db261806a066f59bf6ddc7785ff98a060 | Kang-kyunghun/python_EX | /Example2.py | 4,587 | 3.609375 | 4 | # 파이선 예제 연습 2주차
# 1. 입력을 정수 n 으로 받았을 때, n 이하 까지의 피보나치 수열을 출력하는 함수를 작성하세요.
n = int(input('정수 n을 입력하세요: '))
a = [1,1]
i=2
if n == 1:
print(a[0])
if n == 2:
print(a[:2])
if n >2 :
while i < n :
a.append(a[i-2]+a[i-1])
i = i + 1
print(a)
# 2. 사용자로부터 주민등록번호를 입력 받아 출생 연도를 출력하세요.
id_num = ... |
c2c9a7d73a7bed548a9ca5628671b9545862be00 | myzasani/billy_the_drone | /Billy/Flight2.py | 1,564 | 3.625 | 4 | import tello
# Create Billy
billy = tello.Tello()
# Flight path from Station 1 to all station sequentially
station = [[2, "cw", 90, "forward", 100], [3, "ccw", 90, "forward", 80], [4, "ccw", 90, "forward", 40],
[5, "ccw", 90, "forward", 40], [6, "cw", 90, "forward", 60], [1, "ccw", 90, "forward", 40]]
# S... |
7008f73c39d0cffbb93e317e2e4371b16e4a1152 | ozgecangumusbas/I2DL-exercises | /exercise_01/exercise_code/networks/dummy.py | 2,265 | 4.21875 | 4 | """Network base class"""
import os
import pickle
from abc import ABC, abstractmethod
"""In Pytorch you would usually define the `forward` function which performs all the interesting computations"""
class Network(ABC):
"""
Abstract Dataset Base Class
All subclasses must define forward() method
"""
... |
f4a5bfa334b7eaf380789f6c2113a4cf84c23cce | mastan-vali-au28/Python | /Day-01/Convert.py | 253 | 3.578125 | 4 | #python data types
n1=0O17
n2=0B1110010
n3=0X1c2
n=int(n1)
print("octal 17 is:",n)
n=int(n2)
print("Binery 1110010 is:",n)
n=int(n3)
print("HexaDecimal 1c2 is:",n)
"""
int
float
complex
bool
str
bytes
bytearray
list
tuple
dict
range
set
Mapping
"""
|
210eec095633773aa996af34caae5daa9b8d3e17 | Miragecore/python_study | /opencv/blob/disjoint.py | 1,133 | 3.671875 | 4 |
class disJointItem():
def __init__(self,label):
self.parent = self
self.rank = 0
self.label = label
def FindRoot(self):
if self.parent != self :
self.parent = self.parent.FindRoot()
return self.parent
'''
if self.parent == self :
return self
else :
return Find(self.parent)... |
99b12df31f0c8ef5b6d195435787d3a26bc0254c | arijitlaik/uw-bits | /mesh_refine/spring_refinement/scripts/myarray.py | 677 | 3.5 | 4 | from numpy import *
# a small set of helper functions to
# call common array creation functions
# these are useful to ensure that
# all arrays are created as double-precision
# floats, no matter what data are provided
# as argument. For example array([1,3,4]) normally returns
# an array with data of type int, but arra... |
0940f4182a8a5bae239930e6e51cc57879041a1d | CthulhuF/Programming | /pyatnashki_2.py | 3,252 | 3.84375 | 4 | from math import fabs
n = int(input("Enter a grid size (3 or 4)"))
pole = [[] for i in range(n)]
pole_win = [[] for k in range(n)]
if n == 3:
pole_numb = 9
empty_value = [2, 2]
else:
pole_numb = 16
empty_value = [3, 3]
def init():
active_line = 0
for k in reversed(range(1, pole... |
2d215c42bd8db5ac96ec1f2594ce5883def6f864 | anilkumarravuru/Group-Spanning-Tree | /random_graph_generator.py | 1,116 | 3.546875 | 4 | # Anil Kumar Ravuru
import random
def print_graph(G_adj_list):
for i in range(len(G_adj_list)):
for j in range(len(G_adj_list[0])):
print(format(G_adj_list[i][j],'2d'),end=' ')
print()
def print_graph_to_file(G_adj_list):
with open('sample_graph.txt', 'w') as fp:
for i in range(len(G_adj_list)):
fp.writ... |
c7a1d26abadc1ecdcd820ade5c9a03231186a2d0 | adcaes/programming-puzzles | /leetcode/min_stack.py | 973 | 3.671875 | 4 | '''
https://oj.leetcode.com/problems/min-stack/
Design a stack that supports push, pop, top, and retrieving the minimum element in constant time.
push(x) -- Push element x onto stack.
pop() -- Removes the element on top of the stack.
top() -- Get the top element.
getMin() -- Retrieve the minimum element in th... |
a477f9345fcd496943a6543eba007b5a883bc1d0 | Ayaz-75/Prime-checker-program | /pime_checker.py | 267 | 4.125 | 4 | # welcome to the prime number checker
def prime_checker(number):
for i in range(2, number):
if number % i == 0:
return "not prime"
else:
return "prime"
num = int(input("Enter number: "))
print(prime_checker(number=num))
|
8f3ac6c4bd1468f3ef699529f3d4f21b04035586 | juliapochynok/LearnKorean_project | /final_console/main.py | 1,046 | 3.984375 | 4 | import fileinput
import random
from classes import WordController, User
def main():
'''
Main function. Responsible for program's work.
'''
file_name = make_userfile()
fl = open(file_name, "a")
user = User(file_name)
iterat = True
while iterat == True:
print(menu())
secti... |
c481288f70a5a90afed1aaa7c581cc0ef8af8cf2 | czardoz/dsa | /AVLTrees/trees.py~ | 5,925 | 3.5625 | 4 | '''
Created on Sep 5, 2012
@author: czardoz
'''
def printval(node):
if node is not None:
print node.data
class Node:
def __init__(self, data, left = None,
right = None, parent = None):
self.left = left
self.right = right
self.parent = parent
self.data ... |
9ce94185f2abae34925c7942961a27a8e696c7a7 | czardoz/dsa | /MergeSort/sort.py | 874 | 3.609375 | 4 | '''
Created on Aug 19, 2012
@author: czardoz
'''
def merge(a, b):
result = []
j = 0
i = 0
# swap if lengths not as assumed
# a is shorter than b
if len(a) > len(b):
temp = a
a = b
b = temp
while 1:
if a[i] < b[j]:
result.append(a[i])
i+... |
549e0ff8f318cf667c0094bbb1be8fa31c8eb429 | TylerGrantSmith/agricola | /agricola/choice.py | 1,233 | 3.53125 | 4 | class Choice(object):
def __init__(self, desc=None):
self.desc = desc
def validate(self, choice):
pass
class YesNoChoice(Choice):
def __init__(self, desc=None):
super(DiscreteChoice, self).__init__(desc)
class DiscreteChoice(Choice):
def __init__(self, options, desc=None):
... |
52230fa21f292174d6bca6c86ebcc35cc860cb69 | kisyular/StringDecompression | /proj04.py | 2,900 | 4.625 | 5 | #############################################
#Algorithm
#initiate the variable "decompressed_string" to an empty string
#initiate a while True Loop
#prompt the user to enter a string tocompress
#Quit the program if the user enters an empty string
#Initiate a while loop if user enters string
#find the first bracket and... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.