blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
d70e9835da17abb072152e5629dd4edf84981ce6 | iliachigogidze/Python | /Algorithms2/SingleNumber.py | 684 | 3.640625 | 4 | '''
gadaecema list romelshic yvela ricxvi meordeba garda ertisa da unda davabruno is erti
mag:
[2,2,1] >> 1
[4,4,3,2,2] >> 3
'''
def singleNumber1(nums):
print('NUMS: ', nums)
for i in nums:
counter = 0
for j in nums:
if i == j:
#print('i = ',i, ' j = ',j)
... |
7996dc470caeb1a779a06151cd83515dbc889a3a | lllidan/PythonPractice | /SomeProgram/randomCode.py | 632 | 3.53125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sun Oct 8 22:46:33 2017
@author:zexin
mail:yzxforwork@163.com
wechat:yangzexinlikewow
github:https://github.com/lllidan
input:a length of code
ouput:a string consist of numbers and Words(both capital and small letter)
You are not prepared
"""
import random
source=[]
for i in... |
c986041d052a8277823443edf49a8be596978f70 | RTalha/machine-learning-algorithms | /linear regression/linear_regression.py | 1,573 | 3.609375 | 4 | #!/usr/bin/env python2
# -*- coding: utf-8 -*-
"""
Created on Tue Sep 18 21:38:11 2018
@author: rana
"""
import matplotlib.pyplot as plt
import sklearn as skt
import numpy as np
import pandas as pd
def calculate_theta(theta_1,m,data_set):
#derivative of slop also
theta_1_new = 0
for i in range(m):
... |
50167fde84ed515e7a2088d8c1ecddfd98826391 | deepika087/CompetitiveProgramming | /Leetcode_Challenge/Nov 12/Repeated Substring Pattern.py | 1,389 | 3.640625 | 4 | """
Accepted: But this is hack.
Corresct solution should make use of LPS Array http://www.geeksforgeeks.org/find-given-string-can-represented-substring-iterating-substring-n-times/
"""
class Solution(object):
def repeatedSubstringPattern(self, str):
"""
:type str: str
:rtype: bool
""... |
4d0d81ce0681d62195a6fd90ae7b7c254b53d4ce | NV25/NBT | /Strings/RegexMatch.py | 1,764 | 3.921875 | 4 | """
Given an input string (s) and a pattern (p), implement regular expression matching with support for '.' and '*'.
'.' Matches any single character.
'*' Matches zero or more of the preceding element.
The matching should cover the entire input string (not partial).
Note:
s could be empty and contains only lowercase... |
ef586bc70d0622aeeeb9a95afb3dfb264b35d988 | bangarangler/python_stuff | /errors.py | 274 | 4.0625 | 4 | # try except else finally
while True:
try:
num = int(input('please enter a number: '))
except ValueError:
print('thats not a number')
else:
print('Good job, thats a number')
break
finally:
print('runs no matter what')
print('rest of logic here')
|
ba28da5e361fb33a908a479be1d2e289d6aafc89 | CUGshadow/Python-Programming-and-Data-Structures | /Chapter 11/ComboBoxDemo.py | 1,206 | 3.53125 | 4 | from tkinter import *
class ComboBoxDemo:
def __init__(self):
window = Tk() # Create a window
window.title("Combo Box Demo") # Set title
# Create PhotoImage objects
self.usImage = PhotoImage(file="us.gif")
self.caImage = PhotoImage(file="ca.gif")
# Crea... |
eedaecb099b8905f1e30228324f579962190c628 | Manuel-Python/Cryptography-Python | /stream_cipher.py | 3,296 | 3.515625 | 4 | import random
class KeyStream:
def __init__(self, key=1):
self.next = key
def rand(self): #Linear congruential generator
self.next = (1103515245*self.next + 12345) % 2**31
return self.next
def get_key_byte(self):
return (self.rand()//2**23) % 256
def encrypt(key, message)... |
185b6968ad466b4d2322b27e0f0d7006e5d27f90 | puttak/ML_course-1 | /labs/ex02/template/gradient descent.py | 1,080 | 3.84375 | 4 | # -*- coding: utf-8 -*-
"""Gradient Descent"""
def compute_gradient(y, tx, w, kind='mse'):
"""Compute the gradient."""
error = y - tx.dot(w)
if kind == 'mse':
return -tx.T.dot(error)/len(y)
elif kind == 'mae':
return -np.sign(error).dot(tx)/len(y) #Sum rows
else:
raise NotIm... |
538194e126adbf05a6321c0e9c88b60efd6e0c66 | gogomillan/holbertonschool-higher_level_programming | /0x11-python-network_1/8-json_api.py | 815 | 3.609375 | 4 | #!/usr/bin/python3
"""
Python script that takes in a letter and sends a POST request to
http://0.0.0.0:5000/search_user with the letter as a parameter.
"""
import requests
import sys
if __name__ == "__main__":
url = "http://0.0.0.0:5000/search_user"
if len(sys.argv) < 2:
q = ""
else:
q = s... |
f8e67d01015b657c28ea1cbb70a06fade1f7a421 | jpchato/pdx_code | /programming_101/unit_1/exercise_4.py | 409 | 3.578125 | 4 | bike = 'bicycle'
upper_bike=bike.capitalize()
print (upper_bike)
guitar = 'guitar'
upper_guitar = guitar.capitalize()
print (upper_guitar)
envelope = 'envelope'
upper_envelope = envelope.capitalize()
print(upper_envelope)
violin = 'vIoLiN'
upper_violin = violin.upper()
lower_violin = violin.lower()
print (upper_viol... |
61ce544b2c94f023e775ed5977bed0cf4a7c62da | AverageProgram/2020-2021-CS-3-4 | /RPG.py | 3,576 | 4.125 | 4 | import random
import time
def printText(sentence):
for char in sentence:
print(char, end = '')
time.sleep(.004)
print()
items= ["sword","Bow","Potion"]
playerHealth= 20
inventory= []
running = True
while(running == True):
printText("*** RPG ***")
name= input("What is y... |
1ee5eb1ed1b7162709adb4500c17845704d2ccb5 | resultsmayterry/Kinetek_IAP | /ota_scripts/HexUtility.py | 8,856 | 3.8125 | 4 | #!/usr/bin/env python3
import can
# The following is a utility class with functions to help read data from a hex file
# It relies on reading from a hex file and keeps track of the current position
# Hex file details
# Entries in hex files follow this format
#
# :llaaaatt[dd...dd]cc
#
# : signifies the sta... |
36cd7bf1520186f2af1536fc11d58cadcdd38e81 | mehrdad-shokri/Data-Science-45min-Intros | /python-oop-101/simple_module.py | 2,055 | 4.125 | 4 | #!/usr/bin/env python
# -*- coding: UTF-8 -*-
__author__="Josh Montague"
__license__="MIT License"
import sys
######################
# part 1
#
my_int = 4
my_s = "hello world!"
def square(number):
"""Return the squared value of 'number'."""
try:
return number**2
except TypeError as e:
... |
a68d1965b9ae8172a9f003b64770ff008ef12ce2 | HLOverflow/school_stuffs | /Year2/Algorithm/mergesort.py | 945 | 4.1875 | 4 | # python 2
def mergesort(array):
low = 0
high = len(array) - 1
mid = (low + high)/2
if (len(array)==1): return array
else:
array1 = mergesort(array[: mid+1])
array2 = mergesort(array[mid+1:])
return merge(array1, array2)
def merge(array1,array2):
#print... |
4da3d69d4a9ad0983b0f2a4c2b603ad2b7ee1d3b | nirakarmohanty/Python | /controlflow/IfElseExample.py | 278 | 4.375 | 4 | print('If Else Example ,Checking Even and Odd number ')
value =int(input('Enter one integer value : '))
print('You entered the value as : ',value)
if value%2==0:
print('The entered value is an Even number')
elif value%2!=0:
print('The entered value is an Odd number')
|
3c296b8c8c3f456f03d51c185b976d6c16b6a201 | persional0524/pythonAlgrothmLiu | /Nowcoder/JZ/JZ7.Fibonacci.py | 2,671 | 4.09375 | 4 | #!/usr/bin/python3
# -*- encoding: utf-8 -*-
"""
@File : J27.Fibonacci.py
@Contact : liutao0705@live.com
@License : (C)Copyright 2021-2022
@Modify Time @Author @Version @Desciption
------------ ------- -------- -----------
2021/5/15 5:18 下午 Lita 1.0 None
"""
"""
如果是按... |
bdd427f1157fa39d2550ed060fa886a3b948a239 | Stx666Michael/alien_invasion | /bullet.py | 2,223 | 3.5625 | 4 | import pygame
from pygame.sprite import Sprite
class Bullet(Sprite):
def __init__(self,ai_settings,screen,ship):
super().__init__()
self.screen = screen
self.ai_settings = ai_settings
self.image = pygame.image.load('images/love1.png')
self.rect = self.image... |
998afe2eda0c442c68f383fe1836561d9bb366e2 | berkcangumusisik/CourseBuddiesPython101 | /4. Hafta/02 - Dictionaries/04 - IkiListe.py | 425 | 4.125 | 4 | """İki listeyi bir sözlüğe eşleyen ve yeni sözlüğü döndüren bir işlev yazın.
Misal:
list1 = [1, 2, 3]
list2 = [8, 9, 10]
new_dictionary = {1:8 , 2:9 , 3:10}"""
def two_list(list1, list2):
new_dict = dict()
if len(list1)!=len(list2):
raise IndexError
for key in list1:
new_dict[key] = lis... |
1ac6b593b2b1df274bbf3acf1ce23df8a0b8589b | hjchoe/T2-python | /garbagegenerator.py | 1,790 | 3.53125 | 4 | # James Choe
# Assignment 4.3.1- Garbage Generator
# 2/25/2021
import random
#f = open("/Users/hjcho/Dropbox/programming/T2 python/garbage.txt", 'w+')
f = open("/Users/School_Account/Dropbox/programming/T2 python/garbage.txt", 'w+')
while True:
numofgar = input("\nEnter how many garbage characters you want:\n")
... |
63dba01ad2997caf3bd3bf45c4c97e3a3c3cb86f | Heansum/pythonStudy | /chapter5/ex_2_6.py | 133 | 3.640625 | 4 | # List Slicing
numberList = [14, 75, 32, 94]
print(numberList[1:3])
print(numberList[:3])
print(numberList[:])
print(numberList[1:]) |
2b10416e3d05ae167ae644db07bbc29a48feb4b9 | zzy1120716/my-nine-chapter | /ch04/0120-word-ladder.py | 4,558 | 3.921875 | 4 | """
120. 单词接龙
给出两个单词(start和end)和一个字典,找到从start到end的最短转换序列
比如:
每次只能改变一个字母。
变换过程中的中间单词必须在字典中出现。
样例
给出数据如下:
start = "hit"
end = "cog"
dict = ["hot","dot","dog","lot","log"]
一个最短的变换序列是 "hit" -> "hot" -> "dot" -> "dog" -> "cog",
返回它的长度 5
注意事项
如果没有转换序列则返回0。
所有单词具有相同的长度。
所有单词都只包含小写字母。
"""
"""
方法一:分层遍历的BFS
"""
class Solutio... |
1542d61d75b93a4f842ad81cad56e4b48756501b | DipAnchor/python-practise | /codewars/mstack.py | 832 | 3.921875 | 4 | #this code not work
class mstack:
def __init__(self):
self.list=[]
def pop(self):
return self.list.pop()
def push(self,x):
return self.list.append(x)
def top(self):
print "top is>"
return self.list[-1]
def getMin(self):
min=self.list[0]
for i i... |
763c4122695531a8de231f3982bdfb070097cf87 | AkshayLavhagale/SW_567_HW_01 | /HW_01.py | 1,585 | 4.3125 | 4 | """ Name - Akshay Lavhagale
HW 01: Testing triangle classification
The function returns a string that specifies whether the triangle is scalene, isosceles, or equilateral,
and whether it is a right triangle as well. """
def classify_triangle(a, b, c):
# This function will tell us whether the triangle ... |
b96fb19640fdd2da7fbc4159320f9b89fc6a98ed | CharlesIvia/data-visualization | /scatterplot_sns.py | 921 | 3.59375 | 4 | import pandas as pd
import random
import matplotlib.pyplot as plt
import seaborn as sns
# CREATE DATA
# Create an empty dataframe
df = pd.DataFrame()
# Add columns
df["x"] = random.sample(range(1, 1000), 5)
df["y"] = random.sample(range(1, 1000), 5)
df["z"] = [1, 0, 0, 1, 0]
df["k"] = ["male", "male", "male", "fem... |
3ccf98d66bae85666c362318084abdcb6ad41ed8 | tahamohkawy/data-science | /regression/startups/my_multiple_linear_regression_Backward_elimination_automate.py | 3,737 | 3.953125 | 4 | # Importing the libraries
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
import os
# Importing the dataset
dataset = pd.read_csv('50_Startups.csv')
#Split the data into independent variables and dependent variables
X = dataset.iloc[:, :-1].values
y = dataset.iloc[:, 4].values
#... |
ecdc84ccbc23ef1af10fbb58745d30c634980e79 | uniqstha/PYTHON | /questions of day3/Q2.py | 196 | 4.03125 | 4 | #write a program to find the sum of the first n positive numbers. sum = (n*(n+1))/2
n=int(input('Enter n positive number'))
sum=(n*(n+1))/2
print(f'The sum of first n positive number is {sum} ')
|
8824c6b35667703c8d61eb3e267170f4fc573ca0 | htianwvu/Finance-analysis | /Time value of cash flow, NPV, annnuity and rental.py | 2,514 | 3.9375 | 4 | import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
# setting interest rat to 2%
r = 0.02
cf = pd.DataFrame({'Year':[1,2,3,4,5], "cash_flow":[100,100,100,100,100]})
cf["pv"] = cf['cash_flow'] / (1.0 + r)**cf['Year'] # present value
npv = cf["pv"].sum()
cf
npv
# plot net present value ... |
2cf60ecf4f816b319582201b4e64cb80330e7387 | liuspencersjtu/MyLeetCode | /138-Copy-List-with-Random-Pointer.py | 866 | 3.703125 | 4 | # Definition for singly-linked list with a random pointer.
# class RandomListNode(object):
# def __init__(self, x):
# self.label = x
# self.next = None
# self.random = None
class Solution(object):
def copyRandomList(self, head):
"""
:type head: RandomListNode
:rt... |
a19cc14e92f1411c73f52d68c8909071f73c9a4d | Shubhankar-wdsn/Cyberpunkstyle_plotting | /Rought.py | 170 | 3.65625 | 4 | import pandas as pd
import matplotlib.pyplot as plt
df = pd.DataFrame({'A': [1,3,4,6,1,3,2],
'B': [3,2,5,7,3,6,1]})
df.plot(marker='o')
plt.show() |
4862981a9166a3f912b62f31cb11874bb231a4b8 | tarinidash/python_assignments | /assignment-2/question_3.py | 340 | 4.25 | 4 | # question_3.py
# The program converts Celsius temperature into Fahrenheit
# Date: 01/19/2020
# Author: Tarini Dash
def main():
print("Conversion table from Celsius to Fahrenheit")
# body of the program
print("Celsius Fahrenheit")
print("-------------------")
for i in range(0,110,10):
print(... |
770eb5ee69a4be50f41237a68dbc12a274c8c73e | gummoe/practice | /tests/test_queue.py | 1,042 | 3.515625 | 4 | import unittest
from Stacks_and_Queues.queue import Queue
class QueueTest(unittest.TestCase):
def test_is_empty_is_true(self):
queue = Queue()
self.assertTrue(queue.is_empty())
def test_is_empty_is_false(self):
queue = Queue()
queue.queue = [1, 2, 3]
self.assertFal... |
0cf9a22f16117857e170030b0f7b826eb3f72324 | syurskyi/Python_Topics | /115_testing/_exercises/_templates/temp/Github/_Level_1/UnitTestExamples-master(2)/UnitTestExamples-master/test_calc.py | 1,593 | 3.53125 | 4 | # Corey Schafer
# Python Tutorial: Unit Testing Your Code with the unittest Module
# https://www.youtube.com/watch?v=6tNS--WetLI
______ u__
______ calc
c_ TestCalc?.?
#def test_add(self): # must start with test_
# result = calc.add(2,8)
# self.assertEqual(result,11)
#We can rewrite the above as:
___ test_add
... |
fd4717ef72a02c29945b0943f45d41fe27e28346 | ishantk/ENC2020PYAI1 | /Session31D.py | 198 | 3.625 | 4 | import numpy as np
A = np.array([
[1, 2, 3],
[4, 5, 6],
])
print(A)
print(A.shape)
print()
# Transpose of Matrix
B = A.T
print(B)
print(B.shape)
print()
C = B.T
print(C)
print(C.shape) |
e40363705994d09592125604f0338c2dab46838c | Anton-K-NN/Python-prakticum-Stepic | /Caesar cryt.py | 1,431 | 4.0625 | 4 | '''
Реализуйте функцию caesar(text, key), возвращающую зашифрованный текст, работающую только с латинским алфавитом.
text - исходных текст, который надо зашифровать (или расшифровать)
key - ключ (сдвиг)
Ключ может быть отрицательным или больше 26
Из преобразуемого текста удаляются все пробелы и знаки препинани... |
60fc210e5a27ace863049e455d4815ba75a839b2 | webwesen/leetcode | /1281-subtract-the-product-and-sum-of-digits-of-an-integer.py | 436 | 3.640625 | 4 | # https://leetcode.com/problems/subtract-the-product-and-sum-of-digits-of-an-integer/
class Solution:
def subtractProductAndSum(self, n: int) -> int:
ans = 0
myproduct = 1
mysum = 0
while (n != 0):
myproduct = myproduct * (n % 10)
mysum ... |
4685b008daa8b48c270bac531300a3909a10982b | EvaOEva/python1 | /02-文件读写.py | 3,275 | 3.5625 | 4 | # 文件访问模式:
# 1. r:只读, 文件不存在会崩溃
# 2. w: 只写
# 3. a: 追加写入
# 4. rb: 以二进制方式读取文件数据
# 5. wb: 以二进制方式写入文件数据
# 6. ab: 以二进制方式追加写入文件数据
# 7. r+, w+, a+, 支持读写, 但是要看前面的主模式
# 8. rb+, wb+, ab+ 支持二进制方式读写操作
# -------------r模式-----------------
# # 打开文件使用open函数
# file = open("1.txt", "r", encoding="utf-8") # 默认是r模式,r表示只读
# # 读取文件中的数据
# c... |
873da90b4507ff00d6df361fa60372f8dbd6409e | thehungrysmurf/bt_client | /sandbox/socket_tests/socket_server_chat.py | 494 | 3.53125 | 4 | import socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind(("", 12345))
s.listen(3)
print "Server is ready, waiting for client to connect..."
while True:
client_socket, address = s.accept()
print "A client has connected from address %s, port %s."%(address[0], address[1])
while True:
... |
50c425379c3f0a102e013f1b7aac552a772a33e5 | bcolb/python_practice | /HackerRank/Algorithms/Implementation/sherlock_and_squares.py | 366 | 3.9375 | 4 | import math
def count_squares(start, end):
s = math.floor(math.sqrt(start))
count = 0
while s*s <= end:
if s*s >= start:
count += 1
s += 1
return count
t = int(input())
for i in range(0, t):
s = input()
parts = s.split(' ')
start = int(parts[0])
end = int(p... |
ff096ecd3736e9331368434c1b4bb838f08dd5f5 | vishnuraj212/vishnu_fullstack | /python/day1/input.py | 198 | 3.9375 | 4 | name=input("Hey what's your name?")
print(name)
age=18
print(age)
pi=3.14
print(pi)
country="India"
print(country)
x=y=z=100
print(x,y,z)
name,age,location="Ajy",24,"Cochin"
print(name,age,location) |
f80c180e5bb2582e61a03a172f456050829c9ebc | AdamZhouSE/pythonHomework | /Code/CodeRecords/2091/60631/281331.py | 494 | 3.5625 | 4 | s=input()
if s=='1000 1000':
d=input()
if d=='394 640':
print(274)
elif d=='456 912':
print(380)
elif d=='439 614':
print(349)
elif d=='936 144':
print(554)
elif d=='52 95':
print(551)
elif d=='50 122':
print(566)
elif d=='0 1':
pri... |
87731c95a0b403c1e3df27e76ba9d43b3e2324ce | digvijay-16cs013/FSDP2019 | /Day_02/pattern.py | 242 | 4.1875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Wed May 8 16:56:03 2019
@author: Administrator
"""
val = int(input('Enter value to construct the pattern : '))
for i in range(val):
print('* ' * i)
for i in range(val):
print('* ' * (val - i)) |
45320560f87f8b81fe6631483125c95bdb4854f5 | YulinGUO/LeetCodes | /110/BBT.py | 1,306 | 4.1875 | 4 | __author__ = 'yulin'
'''
Given a binary tree, determine if it is height-balanced.
For this problem, a height-balanced binary tree is defined as:
a binary tree in which the depth of the two subtrees of every node never differ by more than 1.
'''
class TreeNode(object):
def __init__(self, x):
self.val = x... |
f6d1f647314402614269a9164695b39490de2cfd | jakesciotto/jhu | /en605.649/pa5/nn.py | 5,066 | 4 | 4 | # -----------------------------------------------------------
# nn.py
#
# Jake Sciotto
# EN605.649 Introduction to Machine Learning
# Johns Hopkins University
# Fall 2020
#
# Modified from source:
# https://github.com/zHaytam/FlexibleNeuralNetFromScratch/blob/master/neural_network.py
# ---------------------... |
0ac555ba65f250f5a85aebbcb7556833bf14e2c8 | jmathes/projecteuler | /python/p41.py | 504 | 3.890625 | 4 | """
We shall say that an n-digit number is pandigital if it makes use of all the digits 1 to n exactly once. For example, 2143 is a 4-digit pandigital and is also prime.
What is the largest n-digit pandigital prime that exists?
"""
import primes
import digits
from itertools import permutations
for i in xrange(9, 0, ... |
38209ef31885d60f7eb4b94241befc9846b6c99a | liuqun5050/myScript | /py第六天/单元测试/test1.py | 461 | 3.546875 | 4 |
# 导入UnnitTest包
import unittest
from unittest import TestCase
from Day02.Code.lx01 import Calc
ca = Calc()
# 定义一个类
class Testlx01(TestCase):
def setUp(self):
print("开始...")
def test001(self):
ca.add(10,10)
self.assertEqual(20, 20)
def test002(self):
ca.sub(2,1)
se... |
91ceb017b5502648f89e077cb41e64bc6fa4c8b6 | surapat12/DataStructAlgo-Grader-KMITL | /Week11/FindLoop.py | 883 | 3.5625 | 4 | class Graph:
def __init__(self, vertices_lst):
self.weight = dict()
for src in vertices_lst:
self.weight[src] = dict()
for dest in vertices_lst:
self.weight[src][dest] = 0
def add_edge(self, start, end, weight=1, bidir=False):
self.weight[start][e... |
5064d96604481f9a3229487e82fbebd4f2ac10e0 | johannest18/tiletraveller | /medfollum.py | 3,549 | 3.796875 | 4 | #1. það var auðveldara að búa til þessa gerð forrits því það var minna af endurtekningum. Þessi var flóknari en samt auðveldara að búa þetta til
#2. Ég held þessi sé læsilegri.
#3. Helsti kostur seinni gerðar forritsins er að ef það þarf að stækka svæðið sem ferðast má um eða breyta því þá er það mjög einfalt
#í þessa... |
9f6a1b9e3408a03b7da13440521ce62ae2bdf7ef | srirachanaachyuthuni/Basic-Programs-Python | /insert_element.py | 434 | 4.25 | 4 | '''
Given a sorted array and a target value, return the index if the target is found. If not, return the index where it would be if it were inserted in order.
'''
def searchInsert(nums, target):
for i in range(0,len(nums)):
if (nums[i] == target):
return(i)
for i in range(0,len(nums)):
... |
e0c31adefde0517ffafeb4eed541d006686ba0af | wechuli/python | /refresher/functions/inbuilt-functions/min-max.py | 409 | 4.1875 | 4 | print(max([1, 2, 3, 4, 55, 334]))
print(max(33, 4, 3, 244))
print(max('a', 'b', 'c'))
print(min([1, 2, 3, 4, 55, 334]))
print(min(33, 4, 3, 244))
print(min('a', 'b', 'c'))
names = ['Arya', 'Samson', 'Dora', 'Tim', 'Ollivander']
# find the length of the shortest name
print(min(len(name) for name in names))
# we can... |
2156f24c3b1d8e4c8229cf2bcdeb26f8c36479e4 | XiaoqiMa/StudyNotes | /Algorithms/leetcode/[78]子集.py | 1,103 | 3.5625 | 4 | # 给定一组不含重复元素的整数数组 nums,返回该数组所有可能的子集(幂集)。
#
# 说明:解集不能包含重复的子集。
#
# 示例:
#
# 输入: nums = [1,2,3]
# 输出:
# [
# [3],
# [1],
# [2],
# [1,2,3],
# [1,3],
# [2,3],
# [1,2],
# []
# ]
# Related Topics 位运算 数组 回溯算法
# leetcode submit region begin(Prohibit modification and deletion)
class Solution(object):
... |
06ea8f2e412fc018628f4d1cb75441e1c0ccc85b | ReCir0/UCU_Programming | /Lab5/continuation.py | 2,622 | 3.84375 | 4 | def calculate_expression(expression):
'''
>>> calculate_expression("Скільки буде 8 відняти 3?")
5
>>> calculate_expression("Скільки буде 7 додати 3 помножити на 5?")
50
>>> calculate_expression("Скільки буде 10 поділити на -2 додати 11 мінус -3?")
9
>>> calculate_expression("Скільки буде... |
308e92c4dc6f53a773e2e8320463fdb7eb0925b4 | manpreet1994/topgear_python_level2 | /q5.py | 2,347 | 4.5625 | 5 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Sep 23 12:16:54 2020
@author: manpreet
python assignment level 2
Level 2 assignment:
-------------------
program 1:
write a python program using regex or by any other method to check
if the credit card number given is valid or invalid. your python ... |
5d67145e6eeba9d64a50a125a6bf32a9d2d22099 | chaitrak05/CA2020_Assignment_Chaitra | /Functions/uppercaselist_5.py | 210 | 4 | 4 | list = []
def uppercase(l,list):
list.append(l.upper())
return list
while True:
l = input()
if l:
list = uppercase(l,list)
else:
break
for l in list:
print(l)
|
9753712a813fcbe123bfd27f3a7f06f53083186f | hayeonk/leetcode | /sols/replace_words.py | 933 | 3.59375 | 4 | class Node(object):
def __init__(self):
self.terminate = False
self.children = {}
class Solution(object):
def replaceWords(self, dict, sentence):
self.root = Node()
def add(word):
node = self.root
for c in word:
if c not in node.c... |
6f034b799673af4e2e814e0af26778aee4e46414 | GuanYangCLU/AlgoTestForPython | /Classic/sort_1.py | 925 | 3.859375 | 4 | def quicksort(arr):
sort(arr, 0, len(arr)-1)
def sort(arr, lo, hi):
if hi <= lo:
return
else:
j = partition(arr, lo, hi)
sort(arr, lo, j-1)
sort(arr, j+1, hi)
def partition(arr, lo, hi):
i = lo #compare value at the first of array
left = lo+1
right = hi
wh... |
9892917e7326a5ced75212332324a5eb532ae68a | mesanju/law-of-large-numbers | /Law of large numbers .py.html | 783 | 3.875 | 4 | #!/usr/bin/env python
# coding: utf-8
# In[ ]:
# In[18]:
Reference: www.superdatascience.com
""""
Test the Law of Large Numbers for N random normally distributed numbers with
mean=0 and standard deviation=1
Create a Python script that will count how many of these numbers fall between -1 and 1
and divide that ... |
0e1c8001846f8d9bae1f08f7d905490eee3a9ffc | OsheenShrestha22/40ChallengingPythonProgram | /Challenge Problem 37 Casino Blackjack App.py | 8,977 | 4.15625 | 4 | import random
import time
class Card():
"""Simulate a single card with rank, value and suit."""
def __init__(self,rank,value,suit):
"""Initialize card attributes"""
self.rank = rank
self.value = value
self.suit = suit
def display_card(self):
"""Show the rank ana su... |
82f925cf35257c2692dec4a420e96246ad669b91 | Wyingying/wwpython | /day06/_single_cycle_link_list.py | 3,085 | 3.921875 | 4 | '''
循环链表的实现
'''
class Node(object):
'''节点'''
def __init__(self,item):
self.elem = item
self.next = None
class SingleCycleLinkList(object):
'''单项循环链表'''
def __init__(self,node=None):
self.__head = node
if node:
node.next = node
'''链表是否为空'''
def is_empty(self):
return self.__head==None
'''链表的长度'''
d... |
82df57b526b2ed2e493cf07380d608afc2355561 | PadmaNuthalapati/audio-video | /audio video/instance ex2.py | 308 | 3.625 | 4 | class SavingsAccount:
def assign(self,ac,bal):
self.acno=ac
self.bala=bal
def display(self):
print("acno=",self.acno)
print("balance=", self.bala)
a=SavingsAccount()
a.assign(101,124568.00)
a.display()
b=SavingsAccount()
b.assign(102,12458778.00)
b.display()
|
b91c1543346918a1734828041bb78341d232ec39 | olegbukatchuk/python-beginners | /tk_listbox.py | 533 | 3.734375 | 4 | from tkinter import *
import tkinter.messagebox as box
window = Tk()
window.title('Listbox Example')
frame = Frame(window)
listbox = Listbox(frame)
listbox.insert(1, 'HTML5 in easy steps')
listbox.insert(2, 'CSS3 in easy steps')
listbox.insert(3, 'JavaScript in easy steps')
def dialog():
box.showinfo('Selectio... |
533d507bc555d60d42e850256a3cd0995741f265 | ds-t-tran/pandas-tutorial | /sort.py | 250 | 4 | 4 | import pandas as pd
# Sắp xếp df tăng dần theo cột nào đó
df = pd.DataFrame({'name': ['Nam', 'Hiếu', 'Mai', 'Hoa'], 'age': [18,18,17,19]})
print('Before sort\n', df)
df = df.sort_values('age', ascending=True)
print('After sort\n', df) |
43f6e7b4ca39083cbd4818404b84a039eac88a46 | jdht1992/PythonScript | /class/class8.py | 1,418 | 4.1875 | 4 | class Pets:
dogs = []
def __init__(self, dogs):
self.dogs = dogs
# Parent class
class Dog:
# Class attribute
species = 'mammal'
# Initializer / Instance attributes
def __init__(self, name, age):
self.name = name
self.age = age
self.is_hungry = True
# In... |
c1dac67a1b0aa32b95e2d4f34f4ecc0c7f5840f2 | uniinu1/python_study | /HR_practice5week.py | 2,762 | 3.765625 | 4 | #리스트에 대해 공부합니다.
#리스트 선언, 초기화
'''
oddnumber = [1,3,5,7,9]
cafes = ['star','bene','yoger','friends']
A = [1,5,'A','CC','B']
listINlist = [[1,3,5,6,7], cafes, oddnumber, 1,3,'Abc']
print(oddnumber)
print(cafes)
print(A)
print(listINlist)
#리스트 값에 인덱싱을 통해 접근이 가능하다.
a = oddnumber[3] #리스트도 항상 인덱스는 0부터 시작... |
33f52e2a86ffa8be0297704f4fa6d6dd4c074727 | Anshul-GH/python_basics | /OOPs/project_banking_system.py | 4,405 | 3.921875 | 4 | ## My Solution ##
# from random import randint
# class Account:
# def __init__(self, name, deposit):
# self.name = name
# self.deposit = deposit
# self.account_number = randint(10000, 99999)
# print(f'Your assigned account # is: {self.account_number}')
# def display_acct_detai... |
6bdf0c2f66eb7dab9b36c6ef407b2f25e99d30fe | Uche-Clare/python-challenge-solutions | /Uche Clare/Phase 1/Python Basic 1/Day-4/Task 30.py | 207 | 4.1875 | 4 | #program that will accept the base and height of a triangle and compute the area.
base=float(input('Enter base ='))
height=float(input('Enter height ='))
areatriangle= ((1/2)*base*height)
print(areatriangle) |
61973502dcc8f8cacfb06147d53b6d259af86ddd | Suykum/100DaysOfCode_Python | /turtle/turtle_example.py | 1,036 | 3.671875 | 4 | from turtle import Turtle, Screen
import random
timmy = Turtle()
colours = ["CornflowerBlue", "DarkOrchid", "IndianRed", "DeepSkyBlue", "LightSeaGreen", "wheat", "SlateGray",
"SeaGreen"]
def draw_hexagon():
timmy.shape("classic")
num_sides = 2
while num_sides <= 8:
timmy.color(random.... |
7351f1ef766a1e9d50fc9f36679c633bb04a3ee6 | zhihui2015/learnPython | /python_forward/process_thread/multi_thread_v0.3.py | 650 | 3.71875 | 4 | """
Author: Zheng Zhihui
Version:0.3
Date:2019/07/20
Description: ThreadLocal
"""
import threading
local_student = threading.local()
def pop_name_local():
name = local_student.name
print("hello, {} in {}".format(name, threading.current_thread().name))
def push_name_local(name):
local_s... |
09215cebe0acca0c346b160ba92e0bd14b260d46 | PacktPublishing/Python-Object-Oriented-Programming-Cookbook | /Chapter03/C03R04_CreatingInterfaces.py | 18,619 | 3.640625 | 4 | #!/usr/bin/env python
"""
The complete code of Ch. 3, Recipe 5 -- Creating interface requirements
"""
# - Import the abc module to provide abstraction mechanisms
import abc
class BasePerson(metaclass=abc.ABCMeta):
"""
Provides baseline functionality, interface requirements, and
type-identity for objects that can... |
2b4de0c1306c6705404341e3478ee3275d95b16c | snehil0801/python_work | /cigar_party.py | 578 | 4.09375 | 4 | #When squirrels get together for a party, they like to have cigars. A squirrel party is successful when the number of cigars is between 40 and 60, inclusive. Unless it is the weekend, in which case there is no upper bound on the number of cigars. Return True if the party with the given values is successful, or False ot... |
30bdc0feef380744fadbbe31b0accbebd2b42187 | Michal-Malkowicz/python-advanced | /1-warmup/warmup.py | 631 | 3.734375 | 4 | def read_input(filename: str) -> list:
"""
:param filename:
:return: list
"""
file = open(filename, 'r').read()
lines = file.split('\n')
numbers = []
for line in lines:
numbers.append(int(line))
return numbers
def get_result(numbers: list) -> int:
"""
Open file a... |
8eb33da14db779b74c33bafd542cdff15fe70bbe | anti0xidant/MIT6001 | /intset.py | 1,940 | 4.09375 | 4 | class intSet(object):
"""An intSet is a set of integers
The value is represented by a list of ints, self.vals.
Each int in the set occurs in self.vals exactly once."""
def __init__(self):
"""Create an empty set of integers"""
self.vals = []
def insert(self, e):
"""Assumes e... |
7c8410ebbd2f5dd94175d0737a739e46a394494e | ggaapp/Python | /old_lecture/day5_1112_try_except.py | 1,354 | 3.71875 | 4 | SEPARATOR = '\n' + '__'*20 + '\n\n\n'
def test1_try_except():
while True:
_a_str = input('input a string = ')
_b_str = input('input b string = ')
try:
_c = int(_a_str) * int(_b_str)
except:
print('Not Number', SEPARATOR)
continue
print... |
f013a7659359da1ea77cb89e070baa229199a202 | JasoSalgado/algorithms | /sorting-by-selection/ordering_by_selection.py | 1,317 | 4.125 | 4 | """
Ordering by selection
This algorithm orders elements from ascending to descending
Functioning:
It looks for the smallest element
Interchange it by the current one
It folows looking for the smallest element in the list
Interchange it by the current one
This is a repetitive operation
index = 0... |
143197ecba57fa77f3893e1a3662e7b1d8bc1363 | kozak758/funtik | /chislo_ego_delitely.py | 223 | 3.90625 | 4 | ####Ввести число, вывести все его делители.
print ("Input number, please:", end=" ")
n=int(input())
i=1
while i<=n:
if n%i==0:
print("Number divisors:",i)
i+=1
|
76aed7c5ea6b20daaabe57159cfb6e9e483fa5b0 | devangchopra/BestEnlist-Python-Internship | /Day 9/t9.py | 1,191 | 4.46875 | 4 | #Create a lambda function that multiplies argument x with argument y
a = lambda b, c : b * c
print(a(20, 30))
#-------------------------------------
#Write a Python program to create Fibonacci series to n using Lambda
def fibonacci(limit):
listA = [0, 1]
any(map(lambda _:listA.append(sum(listA[-2... |
74ac9f9bb5f865e6a37f514728ab28db490122b1 | BeniyamL/alx-higher_level_programming | /0x05-python-exceptions/101-safe_function.py | 372 | 3.53125 | 4 | #!/usr/bin/python3
import sys
def safe_function(fct, *args):
""" executes the function safely
Arguments:
args: an array of arguments
Returns:
the result of the funciton
"""
try:
result = fct(*args)
except:
result = None
print("Exception: {}".format(sys... |
1e7caf2759f1d041d9db578fde5b042379f409b2 | Tetsuya3850/DSA-Primitives | /SearchingSorting/merge_sort.py | 912 | 3.84375 | 4 | def merge_sort(A):
# Time O(NlogN), Space O(N), where N is the length of array.
def merge(A, l, m, r):
n1 = m - l + 1
n2 = r - m
L = A[l: m+1]
R = A[m+1: r+1]
i = 0
j = 0
k = l
while i < n1 and j < n2:
if L[i] <= R[j]:
A... |
25b8baaafb486e6018eb9290bbddfa67740cb882 | aravind9643/Python_Programs | /Aravind/Practice_3_14112018.py | 77 | 3.875 | 4 | #String Operations (Slicing)
str = "Aravind"
print str[1:5]
print str[-6:-2] |
fb1379cc6f3e6bfbc9e9651183ed1d638aa62d25 | eldadpuzach/MyPythonProjects | /Tuples/methodes-count-index.py | 129 | 3.6875 | 4 | my_tuple = ('a','p','p','l','e',)
# Count
# Output: 2
print(my_tuple.count('p'))
# Index
# Output: 3
print(my_tuple.index('l')) |
a81fe2cd30e8b0cb5fc586a6b048bf49738cf98f | rinsonpeter/Python | /OLD/test.py | 288 | 3.890625 | 4 | import random
number = random.randint(0,10) # or you could assaign a static nmber
guess=int(input("guess the number i have in mind(0to 10)"))
while True:
if (guess==number):
break
else:
guess=(int(input('nope try again ')))
print("you guessed it right",number)
|
f598e1ba8653d720aebba40524f089d131f53052 | preethamsridhar/CTCI | /Arrays_and_Strings/is_unique/is_Unique.py | 391 | 4 | 4 | def is_unique_character_check(String1):
is_unique_all = [None] * 128
if len(String1) > 128:
return "strings are not unique"
else:
for i in range(len(String1)):
if is_unique_all[ord(String1[i])] == 1:
return "strings are not unique"
else:
is_unique_all[ord(String1[i])] = 1
return "strings are uniq... |
b8bf60c8c950240f6438d4305d96b54bfc0867b0 | ionescueduard/Algorithmic-Problems | /12/12.py | 555 | 3.65625 | 4 | def solveMemo(steps, n, i, memo):
if i > n:
return 0
if i in memo:
return memo[i]
sum = 0
for step in steps:
sum += solveMemo(steps, n, i + step, memo)
memo[i] = sum
return sum
def solve(steps, n, i):
if i > n:
return 0
if i == n:
return 1
sum... |
8f0791d4919fe17868bbdd95747a73e6ec212ee2 | MichaelLenghel/python-concepts-and-problems | /levenshtein/levenshteinAlgo.py | 1,297 | 3.984375 | 4 | import numpy as np
class lev:
distance = 0
@staticmethod
def min(num1, num2, num3):
if num1 < num2:
if num1 < num3:
return num1
elif num2 < num3:
return num2
else:
return num3
def edit_distance(self, needle, haystack):
rows, cols = len(needle) + 1, len(haystack) + 1;
# Sets order for 2D mat... |
bf138c23b41a144199a9c59553f4684a8dfe1274 | PankaG/leetcode-solutions | /arrays/three-sum-smaller.py | 1,102 | 3.640625 | 4 | # https://leetcode.com/problems/3sum-smaller/submissions/
'''
Given an array of n integers nums and a target, find the number of index triplets i, j, k with 0 <= i < j < k < n that satisfy the condition nums[i] + nums[j] + nums[k] < target.
Example:
Input: nums = [-2,0,1,3], and target = 2
Output: 2
Explanation: Bec... |
8c00de887e7ca15419275fcdaeca67f524f66de4 | teddyondieki/mastering_python | /abstract_method/main.py | 650 | 3.5 | 4 | from .frog_world import FrogWorld
from .wizard_world import WizardWorld
from .game_environment import GameEnvironment
def validate_age(name):
try:
age = input(f'Welcome {name}. How old are you?')
age = int(age)
except ValueError as err:
print(f'Age {age} is invalid, please try again...... |
9e5f85a991dc8ad4648caf259eb0647f9e04939e | himaeda1332/W21_HW5 | /hw5_test_ec1.py | 1,760 | 3.75 | 4 | """
############################## Homework #5 ##############################
% Student Name: Hisamitsu Maeda
% Student Unique Name: himaeda
% Lab Section 00X: 103 (non-SI student)
% I worked with the following classmates: Nobody
"""
import unittest
import hw5_cards_ec1
class TestHand(unittest.Te... |
bd21bf056c52a97d2c28467937d1407a6a5d12b0 | parmod25feb/python-skills | /Factor.py | 378 | 4.28125 | 4 | # Write a program to find the factors of agiven number and check whether the factor is even or odd.
num = 20
for i in range(1,num+1):
if(num % i == 0):
if(i%2 == 0):
print("Even : ", i)
else:
print("Odd : ", i)
else:
continue
# Output for 20 is
# Odd : 1
# ... |
58e27a41d91762d5a8d4388acb16480814c44fd6 | sudangurung/GUI-Learning | /frame.py | 418 | 3.515625 | 4 | from tkinter import *
from PIL import ImageTk,Image
root = Tk()
root.title("My favourite legends.")
root.iconbitmap("C:/Users/grgsu/PycharmProjects/GUI/Wattson.ico")
#creates a frame
frame = LabelFrame(root, text="This is my Frame...", padx=5, pady=5)
frame.pack(padx=10, pady=10)
#puts the button in the f... |
04ae3175e06768237a9d2f0cd95a75a06f7bf6c1 | razaali11110/PythonPrograms | /A for Asking/Prime Number.py | 146 | 3.984375 | 4 | n=int(input("Enter : "))
for i in range(2,n):
if n%i==0:
print("Not a prime number.")
break
else:
print("prime")
|
80f68a4ca7f4a5e01926321eec9ea6516e9fba55 | liamwoodman/python-learning | /countdown/countdown.py | 3,144 | 4.4375 | 4 | # Countdown Clock
# Create a program that allows the user to choose a time and date, and then prints out a message at given intervals
# (such as every second) that tells the user how much longer there is until the selected time.
#
# Subgoals:
# If the selected time has already passed, have the program tell the user to ... |
024359c01da5a96b8c9e30dda6f36f4f87241e57 | vaibhavkollipara/StateStreet | /test.py | 606 | 4.0625 | 4 | def palindrome(input):
return input == "".join(input[::-1])
def palindrome_new(input):
reverse = [e for e in input]
start, end = 0, len(input) - 1
while start < end:
reverse[start], reverse[end] = reverse[end], reverse[start]
start += 1
end -= 1
return input == "".join(reve... |
c03bfdfabcb0164df2848cbd2d9bf09896113012 | Subhash3/CodeChef | /others/quadratic_roots.py | 314 | 3.515625 | 4 | #!/usr/bin/env python3
import math
A = int(input())
B = int(input())
C = int(input())
discriminant = (B*B) - (4*A*C)
if discriminant == 0 :
x1 = (-B)/(2*A)
x2 = (-B)/(2*A)
else :
x1 = -B + math.sqrt(discriminant)
x2 = -B - math.sqrt(discriminant)
x1 /= 2*A
x2 /= 2*A
print(x1)
print(x2)
|
7d0b86a7bb75e200698fac5d9f969edcc17a407d | piequi/my-hackerrank-challenges | /arrays/minimum_swaps.py | 1,009 | 3.875 | 4 | #!/bin/python
import math
import os
import random
import re
import sys
# Complete the minimumSwaps function below.
def minimumSwaps(arr):
swaps = 0
cur = 0
for i in range(len(arr)):
# if the value is not correct
if arr[cur] != cur + 1:
# find the index of the wrong value
... |
e5289f7df5a07824abe02463cce1cfe92bd41274 | kon-shou/study_python_algorithm | /maze_breadth_saiki.py | 1,658 | 3.71875 | 4 | maze = [
[9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9],
[9, 0, 0, 0, 9, 0, 0, 0, 0, 0, 0, 9],
[9, 0, 9, 0, 0, 0, 9, 9, 0, 9, 9, 9],
[9, 0, 9, 9, 0, 9, 0, 0, 0, 9, 0, 9],
[9, 0, 0, 0, 9, 0, 0, 9, 9, 0, 9, 9],
[9, 9, 9, 0, 0, 9, 0, 9, 0, 0, 0, 9],
[9, 0, 0, 0, 9, 0, 9, 0, 0, 9, 1, 9],
[9, 0, 9, 0, ... |
45fb7fcb14ff9abfeff014da23b78ede11b0bcb0 | ozifirebrand/Packt_and_study_for_python | /Exercises/main.py | 1,230 | 3.734375 | 4 | # This is a sample Python script.
# Press Shift+F10 to execute it or replace it with your code.
# Press Double Shift to search everywhere for classes, files, tool windows, actions, and settings.
def print_hi(name):
# Use a breakpoint in the code line below to debug your script.
print(f'Hi, {name}') # Press ... |
9783a6b1ce49745f39e91f2790a321637376badb | pmn-coding/Nils | /Funktionen_1_schrittweiten_versuch.py | 672 | 3.59375 | 4 | x = -1
range2 = 1
step = 0.1
Achse = ""
for i in range(125): #Zahl ändern um x-Achsenlänge zu ändern
Achse += "-"
ac = 0.1 #auflösung
while not x >= range2:
c = 0
if x == 0:
print(Achse)
else:
y = 1/x**2
#print("Vor",y)
if not y % ac ... |
45cd69ed1a1b9dcd3b45bc0a86e50e46813389a0 | HannaKulba/AdaptiveTraining_English | /tasks/part_4/nth_power.py | 119 | 3.640625 | 4 | a = float(input())
n = int(input())
if a % 2 == 0:
a = (a ** 2) ** (n / 2)
else:
a = a * a ** (n - 1)
print(a) |
c49944e543f6b03e21ad5c54f7356744e367134b | twood1/LeetCode | /Medium/NumSubseq.py | 2,751 | 3.5 | 4 | # 1498. Number of Subsequences That Satisfy the Given Sum Condition
# Medium
# Given an array of integers nums and an integer target.
#
# Return the number of non-empty subsequences of nums such that the sum of the minimum and maximum element on it is less or equal than target.
#
# Since the answer may be too large, r... |
844a86081fbb2a705f14d02dac8ee35a5878293e | michlee1337/practice | /CTCI/c10_sortAndSearch/groupAnagram.py | 604 | 3.890625 | 4 | import collections
def _sort(word):
return("".join(sorted(word)))
def groupAnagram(words):
anagram_dict = collections.defaultdict(list)
for word in words:
anagram_dict[_sort(word)].append(word)
return([v for sublist in anagram_dict.values() for v in sublist])
if __name__=="__main__":
te... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.