blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
59206867d7a35e131a214486f7b12621876b1ad5 | microsoft/pybryt | /pybryt/annotations/complexity/complexities.py | 8,817 | 4.09375 | 4 | """Complexity classes for complexity annotations"""
import numpy as np
from abc import ABC, abstractmethod
from dataclasses import dataclass
from typing import Any, Dict, List, Union
@dataclass
class ComplexityClassResult:
"""
A container class for the results of complexity checks.
"""
complexity_c... |
e004fbf44a1c54030e467abb7825724e9d1ba249 | vesran/GraphIT | /graphit/induced_bipartite_subgraph.py | 4,714 | 3.875 | 4 | from graphit.graphcore import Graph
def _count_bipartite_edges(G, X, Y):
""" Counts the number of edges in G which starts has an endpoints in X and Y.
:param G: Graph
:param X: Vertex set from G
:param Y: Vertex set from G
:return: Integer
"""
cpt = 0
for edge in G.edges:
v1 = ... |
47fdae9fb8f95a64a34518088a443a3e8cf3f25e | francosbenitez/unsam | /07-plt-especificacion-y-documentacion/05-especificacion/documentacion.py | 2,305 | 4.09375 | 4 | """
Ejercicio 7.8: Funciones y documentación
Para cada una de las siguientes funciones:
Pensá cuál es el contrato de la función.
Agregale la documentación adecuada.
Comentá el código si te parece que aporta.
Detectá si hay invariantes de ciclo y comentalo al final de la función
Guardá estos códigos con tus modificacio... |
ce6e06a0bd0994743e886b39c801b469753083eb | dk-yoon/Algorithm | /Software Expert Academy/Difficulty (1)/SWEA2056.py | 867 | 3.96875 | 4 | '''
연월일 순으로 구성된 8자리의 날짜가 입력으로 주어진다.
해당 날짜의 유효성을 판단한 후, 날짜가 유효하다면
”YYYY/MM/DD”형식으로 출력하고,
날짜가 유효하지 않을 경우, -1 을 출력하는 프로그램을 작성하라.
'''
t = int(input())
thirtyone = ['01','03','05','07','08','10','12']
thirty = ['04','06','09','11']
twentyeight = ['02']
for t in range (1,t+1):
date = str(input())
year = (date[0:... |
f74dde0261038d46e3ada75c994c31d62ee9dba1 | rugbyprof/2143-ObjectOrientedProgramming | /ClassLectures/day01.py | 2,090 | 4.59375 | 5 | import random
# simple print!
print("hello world")
# create a list
a = []
# prints the entire list
print(a)
# adds to the end of the list
a.append(3)
print(a)
# adds to the end of the list
a.append(5)
print(a)
# adds to the end of the list, and python doesn't care
# what a list holds. It can a mixture of all ty... |
680824ae02e990a20dda4600a0c150299fe6d5d1 | BalaTheAtom/Begginer_solo | /pract1.py | 788 | 3.671875 | 4 |
st="APPLE"
def findOccurences(s, ch):
return [i for i, letter in enumerate(s) if letter == ch]
d=len(st)
times=0
l=[]
b=[0 for x in range(d)]
while(True):
letter_entered=input("Please enter a char : ").upper()
times=times+1
a=list(findOccurences(st,letter_entered))
for i in range(d):
if(i i... |
2c2e0cc6c45e8436e570cff352546e4b9c533ecd | nkuryad/KodeNoteBook | /src/list-sum.py | 502 | 3.75 | 4 |
""" @docStart
### List Sum
@docEnd """
# @codeStart
from functools import reduce
# sum of all parameters
def sumAll(*x):
res = 0
for a in x:
res += a
return res
print(sumAll(2, 3, 4, 5))
# 14
# sum of no. of given list
def listSum(x):
res = 0
for i in x:
res += i
return ... |
85d336a4cb86757906dfdbab4eddc3f0833d00d6 | yoursc/adventofcode | /2015/07/2015-07-part_2.py | 2,274 | 3.5 | 4 | #!/usr/bin/python
# -*- coding: utf-8 -*-
"""
@Author : Ven
@Date : 2020/1/19
"""
cmd_dic = {}
num_dic = {}
def write_cmd_dic(command: str):
command_split = command.split(" -> ")
if command_split.__len__() != 2:
return
inter: str = command_split[0]
outer: str = command_split[1]
cmd_dic[... |
4ed85238537222b17177ac114b7b79ae6730c79b | franzigrkn/WISB256 | /Euler Challenge/Multiples_3_5.py | 311 | 3.953125 | 4 |
multiples=[]
number=int(input())
getallen=list(range(0, number+1))
print(getallen)
for i in range(3,number, 3):
multiples.append(getallen[i])
for i in range(5, number, 5):
if getallen[i] not in multiples:
multiples.append(getallen[i])
print(multiples)
answer=sum(multiples)
print(answer)
|
3e782341426e65808ed55d9ed62bc1ddaa977f3c | nadeem1306/Q3_NADEEMCHAUDHARY- | /Q3_Nadeem.py | 690 | 3.90625 | 4 | def minChar(n,s):
special=0
digit=0
up=0
lp=0
print("Password contains:")
for i in s:
if i.islower():
lp+=1
elif i.isdigit():
digit+=1
elif i.isupper():
up+=1
else:
special+=1
print("Digits="... |
041c28c1af90e7097d58e328139e85cf7e3d0687 | linadatascience/MSCS | /Practice_of_Computer_Program/Project_Poker_Game/Deck.py | 686 | 3.59375 | 4 | from Card import *
from random import shuffle
class Deck:
def __init__(self):
self.deck = []
suit = "spades"
for x in range (1,14):
self.deck.append(Card(suit,x))
suit = "clubs"
for x in range (1,14):
... |
5522c757bfa1df5d3b4469da0a1f586af5647123 | solavrov/imaginedNums | /funs.py | 760 | 3.53125 | 4 | from IndexSet import IndexSet
def create_unique_index_set(size, dim):
s = []
x = IndexSet(size, dim)
s.append(x.get_sorted_tuple())
while True:
if x.next():
s.append(x.get_sorted_tuple())
else:
break
return list(set(s))
def sum_given_size(x, size):
r =... |
bc959cf3fd78611a404cd333297742d775541671 | bhrigu123/interview_prep_python | /longest_valid_brackets.py | 984 | 3.5625 | 4 | def get_longest_length(arr):
stack = []
start_index = 0
end_index = 0
max_length = 0
while end_index < len(arr):
if is_opening(arr[end_index]):
stack.append(arr[end_index])
end_index+=1
else:
if len(stack) > 0:
popped_bracket = stac... |
40437c8b41eeb844522e59a6841566ddfa67e1bf | dominicprice/pyeliza | /eliza/syn.py | 1,219 | 3.71875 | 4 | import eliza.EString as EString
from eliza.word import WordList
from typing import List
class SynList(list):
"Collection of synonyms"
def add(self, words):
"Add a WordList of synonyms to the list"
self.append(words)
def pprint(self, indent):
for elem in self:
print(' ' * indent, end='')
elem.pprint(i... |
ae0ed592ffd47e1092f3e27185f77013f1405ee5 | wsh123456/arithmetic | /leetcode/211_add-and-search-word-data-structure-design.py | 1,508 | 3.875 | 4 | # 添加与搜索单词-数据结构设计
# 设计一个支持以下两种操作的数据结构:
# void addWord(word)
# bool search(word)
# search(word) 可以搜索文字或正则表达式字符串,字符串只包含字母 . 或 a-z 。 . 可以表示任何一个字母。
# 示例:
# addWord("bad")
# addWord("dad")
# addWord("mad")
# search("pad") -> false
# search("bad") -> true
# search(".ad") -> true
# search("b..") -> true
# 说明:
# 你可以假设所有单词都是由... |
390b0408991d84b88a271de629b20408b9d98eb9 | hughian/OJ | /LeetCode/Python/M98. Validate Binary Search Tree.py | 1,488 | 3.546875 | 4 | class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
def isValidBST(root) -> bool:
if not root: return True
def pre(root):
if not root: return True, float('inf'), -float('inf')
if root:
t = True
minl, ... |
0fa4a8af2f87b8156221536e06e21726b7c9524d | harounixo/GOMYCODE | /project-2.py | 389 | 3.59375 | 4 | def remove_match_char(list1, list2):
for i in range(len(list1)) :
for j in range(len(list2)) :
if list1[i] == list2[j] :
c = list1[i]
list1.remove(c)
list2.remove(c)
list3 = list1 + [""] + list2
return [list3... |
5ac57123e6615e33946e07d28dda4f91b7ac92bd | adit-sinha/Solutions-to-Practice-Python | /(7) List Comprehensions.py | 137 | 3.875 | 4 | a = [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
for even in a:
if even%2==0:
print(even, "is an even number in the given list.")
|
63cb3807d9d675e89126629bd4b69a673995a4d2 | amisha1garg/Arrays_In_Python | /SearchAnElement.py | 1,046 | 4.15625 | 4 | # Given an integer array and another integer element. The task is to find if the given element is present in array or not.
#
# Example 1:
#
# Input:
# n = 4
# arr[] = {1,2,3,4}
# x = 3
# Output: 2
# Explanation: There is one test case
# with array as {1, 2, 3 4} and element
# to be searched as 3. Since 3 is... |
1b254db1f4c2ffe870cc48724c88c18d031fd186 | tachang/OAuthTool | /ConnectHTTPHandler.py | 4,665 | 3.546875 | 4 | import urllib2
import urllib
import httplib
import socket
import ssl
import sys
import base64
class ConnectBasedProxyHTTPConnection(httplib.HTTPConnection):
# Variable to store the protocol being requested
protocol = None
# Initialization
def __init__(self, host, port=None, strict=None, timeout=socket._GL... |
a1f302c36a5df438238163b38e2469a1046e5c1a | TylerAlsop/Graphs | /lecture-notes/day-2-word-ladder1.py | 4,058 | 3.859375 | 4 | # Given two words (begin_word and end_word), and a dictionary's word list,
# return the shortest transformation sequence from begin_word to end_word, such that:
# Only one letter can be changed at a time.
# Each transformed word must exist in the word list. Note that begin_word is not a transformed word.
# Note:
# Ret... |
e1aa51e544d816a3b2ff44cc7bee030c96a2d5ec | q2806060/python-note | /a-T-biji/day19/student_project/student_info.py | 3,587 | 3.625 | 4 |
from student import Student
def input_student():
L = [] # 先创建一个空列表.准备放学生信息的字典
while True:
n = input("请输入学生姓名: ")
if not n: # 如果姓名为空,结束输入
break
try:
a = int(input("请输入学生年龄: "))
s = int(input("请输入学生成绩: "))
except ValueError:
print... |
f3ac9194450d7ee69a8fc4e8c20e84c38e11c3cd | sarkondelo/pyladies | /8ho/7.py | 706 | 3.75 | 4 | birth_number = input('Zadej svoje rodné číslo, prosím. ')
#fce analytující formát rč
def format(birth_number):
intak = int(birth_number[:6])
intak2 = int(birth_number[-4:])
if len(str(intak)) == 6 and birth_number[6] == '/' and len(str(intak2)) == 4:
return True
else:
return False
print(format(birth_number))
... |
e24bd9cad4b75ebf7953ce4be3ce8c9950beee13 | Parth731/Python-Tutorial | /pythontut/8_String_Datatype.py | 784 | 3.984375 | 4 |
mystr = "Harry is a good boy"
print(mystr)
#index is start 0
print(mystr[4])
# 4 is excluding
print(mystr[0:4])
# length count start from 0
print(len(mystr))
# positive index
# print(mystr[0:19])
# print(mystr[0:5:2])
# print(mystr[0::2])
# print(mystr[:5])
# print(mystr[0:])
# print(mystr[:])
# print(mystr[::])
... |
d7dee45350afc55ad323584fb513c0c7c31bfa88 | AravindVasudev/datastructures-and-algorithms | /problems/leetcode/valid_sudoku.py | 1,213 | 3.59375 | 4 | # https://leetcode.com/problems/valid-sudoku/
class Solution:
def isValidSudoku(self, board: List[List[str]]) -> bool:
for i in range(9):
rowSet, colSet = set(), set()
for j in range(9):
if board[i][j] != '.':
if board[i][j] in rowSet:... |
ecd5c2714193628b34cd985b9f6933ac985cda4c | ra-hul/Baby-Names | /math.py | 260 | 4.125 | 4 | import math;
x1= int(input("Enter x1--->"))
y1= int(input("Enter y1-->"))
x2= int(input("Enter x2--->"))
y2=int(input("Enter y2--->"))
d1 = (x2 - x1) * (x2 - x1);
d2 = (y2 - y1) * (y2 - y1);
res = math.sqrt(d1+d2)
print("Distance between two points:",res); |
e409d609dee5910eb6d6231e20bbf0d2cdb90262 | gongjunhuang/Spider | /DMProject/train_test/test.py | 740 | 3.796875 | 4 | def mcnuggets(n):
""" Determine if it's possible to buy exactly n McNuggets with packages
of 6, 9 and 20 McNuggets.
The solution is a Diophantine equation with 3 variables (ax+by+cz=n).
Calculate z=(n-ax-by)/c for all x,y. The time complexity is O(n^2).
"""
packs = {'6': 0, '9': 0, ... |
6ada036e4fbb9f47a03ac723bc5b879405355131 | AntonUden/ProjectEuler | /Python/Project Euler 1 (Python)/Project Euler 1.py | 86 | 3.71875 | 4 | sum = 0
for i in range(1, 1000):
if (i%3 == 0) or (i%5 == 0):
sum += i
print(sum) |
e7708c87d8b01fd86be7f2857044a5b54cb4e868 | David1874/algorithm | /HW6/Dijkstra_05131011.py | 2,886 | 3.609375 | 4 | class Graph():
def __init__(self, vertices):
self.V = vertices
self.graph = []
self.graph_matrix = [[0 for column in range(vertices)]
for row in range(vertices)]
def addEdge(self,u,v,w):
pass
def get_min(self,X,a) -> int:
b=[]
... |
bf0806faa67dfa7553469fef01aaffc3d5e16245 | RinaticState/python-work | /Chapter 9/privileges.py | 2,241 | 3.984375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Fri Jan 05 15:54:19 2018
@author: Ayami
"""
class User(object):
"""Gives summary of user information."""
def __init__(self, first_name, last_name, username, email, location):
"""Initialises the first name and last name attributes."""
self.first_name = fir... |
1c41cafb2511ea5c50fcf0a5d051766c1ab8ad77 | ratchanon-dev/solution_py | /max.py | 2,500 | 4.125 | 4 | """PlanCDEFGHIJKLMNOPQRSTUVWXYZ"""
def main():
"""io function"""
text = input()
num1 = float(input())
num2 = float(input())
num3 = float(input())
if text == "Descend":
print("%.2f, %.2f, %.2f"% (checkhigh(num1, num2, num3), \
checkmid(num1, num2, num3), checklow(num1, num2,... |
7d361940ad31a7c266f639361c9b401acb732b4a | itenabler-python/PythonDay2 | /chart/chart_02.py | 668 | 3.5625 | 4 | import matplotlib.pyplot as plt
from matplotlib.ticker import FuncFormatter
def value_format(value, position):
return '$ {}M'.format(int(value))
# set up values
VALUES = [100,150,125,170]
POS = [0,1,2,3]
LABELS = ['Q1 2018','Q2 2018','Q3 2018','Q4 2018']
# set up the chart
# Colors can be specified in multiple form... |
4d56e41a4ea60e0ab3a0fe596beb1cbaa7f46ae3 | jorge-alvarado-revata/code_educa | /python/week3/ejercicios10a.py | 240 | 3.828125 | 4 | # Verifica si un año es bisiesto
es_bisiesto = False
year = int(input('ingrese el año: '))
es_bisiesto = (year % 4 == 0)
es_bisiesto = es_bisiesto and (year % 100 != 0)
es_bisiesto = es_bisiesto or (year % 400 == 0)
print(es_bisiesto)
|
d36f797e4df40b9398793818ac4fbebe4bd6c11f | meloun/ew_aplikace | /Aplikace_1_0/Source/libs/test/hex.py | 280 | 3.796875 | 4 | '''
Created on 11.11.2013
@author: Meloun
'''
s = "abcd"
print "{:}".format((12,13))
s2 = s.encode('hex')
print s2, type(s2)
for c in s:
print c
print c.encode('hex')
print (",".join(c.encode('hex') for c in s))
print ":".join(c.encode('hex') for c in s) |
46b0e8d098b974ae897fa28cdc374b1590be5951 | PaulMDavid/ml_qs | /Day21/old/RNN_BitCoin.py | 2,616 | 3.625 | 4 | # Importing the Libraries
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
# Reading CSV file from train set
training_set = pd.read_csv('BitCoin_Data.csv')
training_set.head()
#Selecting the second column [for prediction]
training_set = training_set.iloc[:,2:3]
training_set.head()
... |
064b74e4ebb8bc64c71e47a97367d6898a22bbb2 | AdamZhouSE/pythonHomework | /Code/CodeRecords/2976/39021/312998.py | 201 | 3.625 | 4 | import re
str = input()
re.compile
res = []
while True:
s=input()
res.append(s.repalce(str,''))
else:
res.append(s)
if not s:
break
for i in res:
print(i) |
dddb15eeede80a2ba43849566f350048445dd549 | olgarozhdestvina/pands-problems-2020 | /Problem Set/weekday.py | 249 | 4.34375 | 4 | # Olga Rozhdestvina
# The program that outputs whether or not today is a weekday.
from datetime import datetime
today = datetime.today()
if today.weekday() <= 4:
print("Yes, unfortunately today is a weekday.")
else:
print("It is the weekend, yay!") |
fd02d127ec7eeb2dd6f2cd53bb35a49387f53925 | ctaboy/SpringProjects21 | /Language_Modeling/Part 2 Anagram decoder/decode.py | 2,790 | 3.59375 | 4 | #!/usr/bin/env python
"""Anagram decoder."""
import collections
from typing import DefaultDict, List
import pynini
import argparse
KeyTable = DefaultDict[str, List[int]]
def get_key(s: str) -> str:
"""Computes the "key" for a given token."""
return "".join(sorted(s))
def make_key_table(sym: pynini.Sym... |
ef67d287757457892bcb55c57c4d861c2d962d4a | uhrzel/ph-guide-to-prog | /arrays/python/no-lists.py | 476 | 4.03125 | 4 | # Get collection of items:
item1 = input()
item2 = input()
item3 = input()
item4 = input()
item5 = input()
# Our position, or "index":
position = int( input() )
# Get our item at position:
if (position == 1):
our_item = item1
elif (position == 2):
our_item = item2
elif (position == 3):
our_item = item3
el... |
5bf0ef5baac7616c5c2cbc1cda0a94c959246e3a | HaileeKim/Data-Structure | /DoublyLinkedList.py | 2,316 | 3.953125 | 4 | class DList:
class Node:
def __init__(self, item, prev, link):
self.item = item
self.prev = prev
self.next = link
def __init__(self):
self.head = self.Node(None,None,None)
self.tail = self.Node(None,self.head,None)
self.head.next = self.tail
... |
f6e30d6af7d7c7d180ae0f810f9dc95545ff1b06 | rwylie/python-exercises | /Turtle_Exercises/shapes.py | 775 | 3.609375 | 4 | from turtle import *
def circle():
circle(50)
def star(size):
for i in range(5):
forward(size)
right(144)
def square():
for i in range(4):
forward(50)
right(90)
def pentagon():
for i in range(5):
forward(200)
right(72)
def octagon():
for i in ... |
dbb500c610ecaa8d2aacd32e0016169a6032104c | daniel-reich/ubiquitous-fiesta | /yXekCk3qRWYR5AHif_24.py | 151 | 3.796875 | 4 |
def vow_replace(word, vowel):
lst=["a","e","i","o","u"]
for char in word:
if char in lst:
word=word.replace(char, vowel)
return word
|
8ceff93c8bda0482caa2f730e0e142385843ede8 | MartrixG/CODES | /NAS/任务/data_process/test.py | 210 | 3.546875 | 4 | import Dataset as data
import numpy as np
#data.view_detail('cifar100', show_image=True)
a = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 1, 2, 3, 4, 5, 6, 7, 8, 9, 1, 2, 3, 4, 5, 6, 7, 8, 9])
print(a.reshape(3, 3, 3)) |
495fdb44d87aaa50df4c8ef7e5c5872ac4f58c82 | Astrosysman/lessons_of_python | /lesson3_dz_5_fibonacci_number.py | 396 | 4.25 | 4 | #!/usr/bin/env python3
# Возвращает число Фибоначчи на ведёному пользователю номеру
# Автор Вазинский Виталий
def fibonacci_number(number):
if number == 1 or number == 2:
return 1
return fibonacci_number(number - 2) + fibonacci_number(number - 1)
def main():
number = int(input('Введите число: '))
print(fibon... |
1c324c7964c9918ca783608c94359e2e400dc3d2 | kharithomas/LeetCode-Solutions | /two_pointers/two-sum-ii-input-array-is-sorted.py | 539 | 3.515625 | 4 | from typing import List
# TC : O(N)
# SC : O(1)
class Solution:
def twoSum(self, numbers: List[int], target: int) -> List[int]:
start, end = 0, len(numbers) - 1
while start < end:
sum = numbers[start] + numbers[end]
if sum == target:
return [start + 1, en... |
9f364aa3baf62debfa9a80ccbcad298a2a0a61f7 | moontree/leetcode | /version1/81_Search_In_Rotated_Sorted_Array_II.py | 2,166 | 4.1875 | 4 | """
Follow up for "Search in Rotated Sorted Array":
What if duplicates are allowed?
Would this affect the run-time complexity? How and why?
the relation between mid, left, and right
Suppose an array sorted in ascending order is rotated at some pivot unknown to you beforehand.
(i.e., 0 1 2 4 5 6 7 might become 4 5 6... |
b47489c921441c6c77012aff1a0580770be1368d | Grommash9/python_24_skillbox | /24_zadacha_8/card.py | 824 | 3.640625 | 4 | cards_list = []
def new_cards_list():
suit_list = [' ♣️', ' ♦️', ' ♥️', ' ♠️']
cards = {
'Двойка': 2,
'Тройка': 3,
'Четверка': 4,
'Пять': 5,
'Шестерка': 6,
'Семерка': 7,
'Восьмерка': 8,
'Девятка': 9,
'Десятка': 10,
'Валет': 10... |
18984e579823fed4235b31bf94232379291918f2 | ajeet214/Web-Scrapping | /youtube_channel_30_videos.py | 2,798 | 3.640625 | 4 | """
Project : YouTube Channel videos
Author : Ajeet
Date : July 27, 2023
"""
import re
from bs4 import BeautifulSoup as bs
from urllib.request import urlopen
import json
youtube_search = "https://www.youtube.com/@PW-Foundation/videos"
# Open the URL and read the content of the page
url_search = urlopen... |
10a021b4293873be8ae55dc1365c56da94c9bb9e | jbell69/python-challenge | /PyBank/main.py | 2,312 | 3.8125 | 4 | # install modules
import csv
import os
#declare variables
total_months = 0
net_amount = 0
previous_revenue = 0
monthly_change = 0
m_change_list = []
total_change = []
months = []
# Set path for file
csvpath = os.path.join("..", "Data", "budget_data.csv")
with open(csvpath, newline='') as bank_csv_file:
bank_csv... |
287361df635003364ab44c8ca9cf099390e36ab2 | kellybreedlove/proj6 | /Graph.py | 3,538 | 4.03125 | 4 | import sys
import Queue
"""
A class to model a vertex in a graph.
"""
class Vertex(object):
"""
idVal The id or value stored at this vertex
adjs The vertices that are adjacent to this vertex
"""
def __init__(self, idVal, adjs):
self._id = idVal
self._adjacents = adjs
"... |
6f54531db1a486b7549b04fc10dbf5cbc7b6c9fb | mnincao/4linux-520-7938 | /aula1/aula1.py | 283 | 3.59375 | 4 | nome = input("Digite o seu nome completo:")
cpf = input("Digite seu CPF:")
idade = input("Digite sua idade:")
print('-------------------------')
print('Confirmação de cadastro: ')
print(f'Nome:{nome}')
print(f'CPF:{cpf}')
print(f'Idade:{idade}')
print('-------------------------') |
0128aa02bef82c5ee9e31d5ee9e736d27f36ba90 | Patricksxj/p_scripts | /计算95%置信区间.py | 689 | 3.5625 | 4 | # 使用该方法,计算的是95%CI
# 计算95%CI时,网上有人设置 alpha=0.05, 不正确
# 注意:scale不是标注差,是标准误差
# 在查 Z 表的時候,首先要先看檢定是單尾檢定還是雙尾檢定 。如果是求信賴區間的話就是雙尾檢定 。
import numpy as np
from scipy.stats import *
data=np.random.normal(0,1,10000)
confidence=0.95
result=t.interval(confidence,df=len(data) - 1,loc=data.mean(),scale=sem(data))
mean=data.mean()
std=d... |
8caa03ee484c43ba411299a7614db721a0b1bd91 | hornsbym/WarGame | /Connector.py | 3,553 | 3.59375 | 4 | """
Author: Mitchell Hornsby
File: Connector.py
Purpose: Creates a socket that constantly runs. It waits for players to connect
and then pairs them up in a new GameServer.
"""
from GameServer import GameServer
import socket
import pickle
class Connector (object):
def __init__(self):
"""
... |
e3bcd374e1d0c14019f507c3c67e1883aee024e2 | brulogatti/ApprendeCoderAvecPython | /Exercicios_module3.py | 7,361 | 4 | 4 | '''
a=int(input())
b=int(input())
c=int(input())
if a==b:
print(a)
elif a==c:
print(a)
elif b==c:
print(b)
temperature=int(input())
if temperature>0:
if temperature<=10:
print("Il va faire frais.")
else:
print("Il va faire froid.")
a=int(input())
b=int(input())
c=int(input())
if c==1:
... |
2794b2cf9308ca912d482f9bb4dbdbcb651631fb | aadilkhhan/Advance-Python-1 | /13_pr_03.py | 98 | 3.8125 | 4 | num = int(input("Enter your number : "))
table = [num*i for i in range(1 , 11)]
print(table) |
2f05f6af584a8ce65670549e60dc5885920ce550 | shashankvmaiya/Algorithms-Data-Structures | /LeetCode_python/src/heap/median_dataStream_H.py | 2,088 | 3.65625 | 4 | '''
295. Find Median from Data Stream
Question: Design a data structure that supports the following two operations:
void addNum(int num) - Add a integer number from the data stream to the data structure.
double findMedian() - Return the median of all elements so far.
E.g.,
addNum(1)
addNum(2)
findMedian() -> 1.5
addN... |
6f60f063e044540992a2212cdfa772afe987469e | tots0tater/scheduler | /tkcalendar.py | 3,999 | 4.625 | 5 | from tkinter import Frame, Button, Label
import calendar, datetime
class TkCalendar(Frame):
"""
A tkinter calendar that displays a month. All days on the
calendar are buttons that when pressed return a date
object to the designated callback function.
Required arguments:
master -- the parent which TkCalendar ... |
c9f86f1072e7ed7731b164bb3a8f4d19642fe4a3 | MNJetter/aly_python_study | /ex3.py | 1,165 | 4.40625 | 4 | # Writes a statement.
print "I will now count my chickens:"
# Writes a statement followed by the restuls of a math equation.
print "Hens", 25.00 + 30.00 / 6.00
# Writes a statement followed by the results of a math equation.
print "Roosters", 100.00 - 25.00 * 3.00 % 4.00
# Writes a statement.
print "Now I will count ... |
6725b82267c0589e3e195787bb466d3540e6057c | mwong33/leet-code-practice | /easy/can_place_flowers.py | 1,650 | 3.828125 | 4 | class Solution:
# O(n) time O(1) space
def canPlaceFlowers(self, flowerbed: List[int], n: int) -> bool:
# Greedy Algorithm
# Iterate through the flowerbed
# 1) Check if current plot is 0 if it is not just increment to the next plot
# 2) If it is 0 check plot in front to see if it... |
7fdcf69c2ad116a4e59b0659620693c2f5b42046 | trendsetter37/HackerRank | /Sherlock and the Beast/satb.py | 1,033 | 3.84375 | 4 | #!/usr/bin/python3.4
''' Sherlock and the Beast on HackerRank '''
import sys
from colorama import Back, Style, Fore
def decent(n):
n = int(n)
if n == 1:
return -1
else:
if n % 3 == 0:
return '5' * n
else:
for i in range(n, -1, -5): # This should return the largest
if i % 3 == 0 and (n-i) % 5 == 0... |
a59ec0a71b6fe9319f2f3253b5ce94e5e39d9892 | J0/Kattis | /python/farming/character.py | 106 | 3.8125 | 4 | x = input()
x = int(x)
if x == 1 :
print(0)
elif x == 2:
print(1)
else:
sum = 2**x - x -1
print(sum)
|
2ad52c36492224f9566ad122a6e77fd495f03098 | novicelch/python-study | /python-spider/base/python_base.py | 1,291 | 3.921875 | 4 | # 这是python基础练习
# -*- coding: utf-8 -*-
__author__ = "liuchenhu";
import re, math;
print(__author__);
a = "world";
b = "liuchenhu";
c = 22;
print(a);
print("hello world");
print("hello", "world", "lch");
print("hello %s"%a);
print("hello %s"%(a,));
print("hello %s - %s"%(a, b));
print("%s is %s years ord"%(b, c));
# ... |
6b6601ec96f13f16f338715e32bd5a0487df6462 | kizs3515/shingu_1 | /0922_4.py | 410 | 3.875 | 4 | for looper in["K","O","R","E","A"]:
print "hello",
print " "
print " "
for looper in[1,2,3,4,5]:
print "hello"
print " "
for looper in["AS","AD","AC"]:
print "\nhello"
print " "
for looper in range(0,10):
print "hello"
for i in 'abcdefg':
print i,
print " "
print " "
for i in range(1,10,2):
... |
08e20effcc8c0003c89e4a87116e61b263ada70e | GHs1b1/weatherF | /WeatherF.py | 1,246 | 3.84375 | 4 | # Application that interact with webservice to obtain data.
import requests
location: str = input("Enter the city name: ")
try:
print(location)
except:
print('invalid city, please re-enter')
def main():
# website: "https://api.openweathermap.org/data/2.5/weather?q={city name},{state code},... |
cb0c0e475c40dac8f007242ab580906119606c35 | patni11/Nand2Tetris | /Downloaded/nand2tetris/projects/06/Instructions.py | 7,984 | 3.6875 | 4 |
#Our class to convert each line of assembly language to relevant binary code
class Assembly_Binary:
def __init__(self, input_array):
self.input_array = input_array
self.final_array = [] #To store the final 16bit binary lines of the output
self.binary_array = [] #To store temporary output
... |
36653d214911bc0e98acef8fa542d471814b0029 | nguyenkims/projecteuler-python | /src/p85.py | 1,049 | 3.65625 | 4 |
def f(m,n):
'''return the number of rectangles that a m x n contains'''
s=0
for a in range(1,m+1):
for b in range(1,n+1):
s+= (m-a+1)*(n-b+1)
return s
print f(1,1),f(2,4), f(3,3)
def g(m,n):
''' the same as f(m,n) except g(m,n) is calculated recursively'''
if m==0:
return 0
elif m == 1 :
return n * ... |
10608e1d4bf19495d84af3a84aea9bcec0dbe815 | bkrmalick/uni | /Data Strucutres (Python + Java)/CW2/asdasd.py | 336 | 3.75 | 4 |
def subarray(subarray, array):
for i in range(0,len(subarray))
found=False
for j in range(0, len(array))
if(B[i]==A[j]):
found=True
break
if(!found):
return False
return True
A=[4,2,1,3]
B=[2,3,1]
print(... |
ddeaec9c7a7d0ea2852de9c55ab4ef29fb30453f | gatlinL/csce204 | /Exercises/March8th/functions2.py | 1,048 | 3.90625 | 4 | # Author: Gatlin Lawson
import turtle
import random
turtle.setup(575,575)
pen = turtle.Turtle()
pen.speed(0)
pen.pensize(2)
pen.hideturtle()
def draw_square():
length = 50
x = random.randint(-int(turtle.window_width()/2), int(turtle.window_width()/2 - length))
y = random.randint(-int(turtle... |
fb8f66f7a4c46f15c65115aa6b808ccf90fd8608 | mikeckennedy/python-jumpstart-course-demos | /apps/09_real_estate_analyzer/final/concept_dicts.py | 1,040 | 4.34375 | 4 | lookup = {}
lookup = dict()
lookup = {'age': 42, 'loc': 'Italy'}
lookup = dict(age=42, loc='Italy')
class Wizard:
def __init__(self, name, level):
self.level = level
self.name = name
gandolf = Wizard("Gladolf", 42)
print(gandolf.__dict__)
print(lookup)
print(lookup['loc'])
lookup['cat'] = 'Fun... |
5d96b384841e54f2a3edd88bd35741e6e4915a2b | luciasalar/lyrics-money-project | /merge_datasets.py | 3,000 | 3.578125 | 4 | import pandas as pd
import glob
"""Here we create dataset 1 and dataset 2"""
# Dataset1 contains:
#1. hiphop songs from billboard top 100 hip hop songs (weekly charts from 70s to 2020)
#2. top 500 songs with keywords "rap money", "hip hop money"
# one problem is that youtube song titles are messy, Genuis lyrics won... |
0fac2b104e9dedc3661fdd82f7483d55b8d83eb6 | Shraddh-Arutwar/Python | /2.1. sum_and_largest_no_of_array.py | 322 | 3.8125 | 4 | # use *range() --> for unpacking the range function output
a = [*range(1,11)]
sum = 0
print("list is: ", a)
for x in range(0, len(a)):
sum = sum + int(a[x])
print("sum of array no: ", sum)
# Largest number in arrays
n = 0
for i in range(0, len(a)):
if a[i] > n:
n = a[i]
print ("largest number is:", ... |
97c8405b0753a8618e218760d84ea421ef05a97e | RoanPaulS/Functions_Python | /palindrome_function.py | 214 | 4.3125 | 4 | word = input("Enter any word : ");
def palindrome(word):
return word == word[::-1];
if palindrome(word):
print("Given word is Palindrome");
else:
print("Given word is not a Palindrome");
|
9b02776b64925880c256a548881369336ce74807 | Jamiil92/Machine-Learning-by-Andrew-Ng | /code/ml-ex2/ex2.py | 4,628 | 3.859375 | 4 | from __future__ import division, absolute_import, print_function
import time
import numpy as np
import matplotlib
from matplotlib import pyplot as plt
from matplotlib import *
from numpy import *
import scipy as sc
from scipy.optimize import fmin_ncg
from plotData import plotData
from sigmoid import sigm... |
2718e8b9d95acf72e433d12f384b0dc5460b7f9e | zumaad/pyrver | /event_loop/event_loop.py | 5,663 | 3.546875 | 4 | import selectors
from typing import Callable, Union, Generator
import datetime
import socket
class ResourceTask:
"""
A resource task is a task that is dependent on a file like object (socket or actual file for example) to
be readable or writable. A coroutine will yield this type of task so that it can be... |
5c1b01b00b25bf6bea7cfad2a719994754fd0fd6 | mauricio004/datafiles2 | /python_mit_2/exhaustiveenumeration.py | 510 | 3.96875 | 4 |
def squareroot(x):
epsilon = 0.01
step = epsilon ** 2
numguesses = 0
ans = 0.0
while abs(ans ** 2 - x) >= epsilon and ans * ans <= x:
ans += step
numguesses += 1
print('numguesses = ' + str(numguesses))
print('ans : ' + str(ans))
if abs(ans ** 2 - x) >= epsilon:
... |
b204aec72eaea78a54989f29063a33c859c33e1b | garra0123/dlex | /preview/diff.py | 173 | 3.578125 | 4 | from sympy import *
# 定义函数变量x
x = Symbol('x')
# 函数sin(x**2)*x 对x求导
d = diff(sin(x ** 2) * x, x)
print("函数sin(x**2)*x 对x求导: \n%s" % d)
|
45176319fafdc2a666507a575985705a71739f8f | de-ritchie/dsa | /Data Structures/week1_basic_datastructures/tree_height/tree_height.py | 1,702 | 3.90625 | 4 | # python3
import sys
import threading
class Node:
def __init__(self, val):
self.val = val
self.children = []
def createTree(nodes) :
root = None
for node in nodes :
if node.val == -1:
root = node
else :
nodes[node.val].children.append(node)
retu... |
73793a70c5a22a1eefee0fb1dcf8036f8b839510 | DenisenkoA/2nd-home-task | /str_op.py | 423 | 3.96875 | 4 | s="У лукоморья 123 дуб зеленый 456"
#1
if s:
if s.count("я")!=0:
print(s.index('я'))
else:
print("буква ""я"" не была представлена")
#2
print(s.count("y"))
#3
if s:
if s.isupper ==True:
print(s.isupper())
else:
print(s.upper())
#4
print(len(s))
if s:
if len(s)>4... |
4f756673e56f9e864859fa19e25daac2b3d37de2 | inwk6312winter2019/week4labsubmissions-parth801736 | /Lab5task2.py | 877 | 3.765625 | 4 | from Lab5task1 import point
import copy
class rectangle:
def __init__(self):
self.width = 0
self.height = 0
self.corner = 0
def find_center(r):
c = point()
c.x = r.corner.x + r.width/2.0
c.y = r.corner.y + r.height/2.0
return c
def move_rectangle(r, dx, dy):
r.corner.x += dx
r.corner.y += dy
def new_m... |
eee63537d879c66d4f2d2601dd70500f959838ad | joelcurl/finna | /statements/util.py | 365 | 3.859375 | 4 | def is_current_date(key, past_dates, today):
if key not in past_dates:
past_dates[key] = today
return True
else:
if past_dates[key] < today:
past_dates[key] = today
return True
return False
def is_date_between(date, start, end):
if start <= date and date ... |
460b294d8d4ac2f27a724d8bd65cdb20087829d2 | thegrafico/coding-challenges | /python_challenge/dummy_coding/test.py | 308 | 3.828125 | 4 | ar = [
[1,2,3],
[4,6,8],
[10,20,30]
]
#vertical normalr
for row in range( len(ar) ):
for col in range( len(ar[0]) ):
print(ar[row][col], end=',')
#Vertical reversed
for row in range( len(ar) ):
for col in range( len(ar) - 1, -1, -1 ):
print(ar[row][col], end=',') |
a85e57997203e91abf2effaf83561e9c4ecf9cb6 | oneyuan/CodeforFun | /PythonCode/src/138.copy-list-with-random-pointer.py | 1,289 | 3.59375 | 4 | #
# @lc app=leetcode id=138 lang=python3
#
# [138] Copy List with Random Pointer
#
import collections
"""
# Definition for a Node.
class Node:
def __init__(self, val, next, random):
self.val = val
self.next = next
self.random = random
"""
class Solution:
def copyRandomList(self, head: '... |
d2f675e265034581b1775b8a4ea18a5994a1c0f7 | albertosanfer/MOOC_python_UPV | /Módulo 3/Práctica3_1.py | 462 | 4.09375 | 4 | # A continuación tenemos un input en el que le pediremos un número al usuario y
# lo guardaremos en la variable entrada. Después, deberemos guardar en la
# variable mayorQueTres el valor True si ese número es mayor que tres y False
# en caso contrario.
# Nota, acordaros de realizar la conversión de tipos en el input
e... |
dffb264a1cc4f0aca5acb36b12d67b4ab123e627 | alyzatuchler/project-euler | /eulerP5.py | 678 | 3.75 | 4 | # -*- coding: utf-8 -*-
"""
Created on Mon Sep 18 15:36:03 2017
@author: alexa
2520 is the smallest number that can be divided by each of the numbers from 1 to 10
without any remainder.
What is the smallest positive number that is evenly divisible by all of the numbers
from 1 to 20?
"""
num_int = 40 #starts at 40 ... |
ee70ef92423123e00cecec5d6bd900c0e0942956 | wenjiaaa/Leetcode | /P0001_P0500/0080-remove-duplicates-from-sorted-array-ii.py | 1,299 | 4.03125 | 4 | """
https://leetcode.com/problems/remove-duplicates-from-sorted-array-ii/
\Given a sorted array nums, remove the duplicates in-place such that duplicates appeared at most twice
and return the new length.
Do not allocate extra space for another array, you must do this by modifying the input array in-place
with O(1) ... |
eef9021d9c043720cca8603679746b1b74b48e23 | wayneshun/LPTHW | /spider/函数.py | 213 | 3.609375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Thu Jul 10 22:37:58 2014
@author: shunxu
"""
def sum(i1, i2):
result= 0
for i in range(i1, i2 + 1):
result = result + i
return result
print sum(1, 100) |
db71b3b17f59af1177fcb54d3f3ca0a15bef17ec | kiaev/python | /Lec10/main2.py | 374 | 4.21875 | 4 | """
Сравнение строк. В Python все строки - Unicode.
"""
print("A > a:", "A" > "a")
print("A is:", ord("A"))
print("a is:", ord("a"))
print("66 is:", chr(66))
print("98 is:", chr(98))
print("ABCD" < "ABCE")
"""
'ABCD' VS 'a'
Лексико-графический порядок сравнения (как в словарь)
"""
print("ABCD" < "a") |
543d43951d475f80f1fc46af4d8c56e403d9b411 | Sakura-Yamada/nandemo | /raspberrypi/motor.py | 1,384 | 3.6875 | 4 | # -*- coding: utf-8 -*-
import RPi.GPIO as GPIO
import time
import sys
#参考文献
#https://tool-lab.com/raspberrypi-startup-26/
#https://github.com/CamJam-EduKit/EduKit3/tree/master/CamJam%20Edukit%203%20-%20RPi.GPIO/Code
#set
GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False)
#Pin Assignment
r1 = 9
r2 = 10
l1 = 8
l2 = ... |
04f74fb4ab6a0481c0ef340cf9ead35812fb9825 | gil9red/SimplePyScripts | /html_parsing/www.sports.ru_epl_table.py | 709 | 3.734375 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
__author__ = "ipetrash"
from bs4 import BeautifulSoup
def parse(html):
soup = BeautifulSoup(html, "lxml")
teams = []
for row in soup.select("tbody > tr"):
cols = row.select("td")
teams.append({
"Место": cols[0].text,
... |
e25cf215e64025e7c763c4b42631c408bce86191 | Ra8/CP | /Python/numbertheory/gcd.py | 393 | 3.78125 | 4 | def gcd(a, b):
while a > 1 and b > 1:
a, b = max(a, b), min(a, b)
a, b = b, a % b
if a == 1 or b == 1:
return 1
if a == 0:
return b
if b == 0:
return a
def test():
assert gcd(5, 10) == 5
assert gcd(2, 3) == 1
assert gcd(5, 8) == 1
assert gcd(6, 8)... |
07e79f7094dbbd4a5054031493eecc00ececfd01 | DevepProd/holbertonschool-higher_level_programming-1 | /0x03-python-data_structures/6-print_matrix_integer.py | 265 | 3.921875 | 4 | #!/usr/bin/python3
def print_matrix_integer(matrix=[[]]):
for i, row in enumerate(matrix):
for x, number in enumerate(row):
print("{:d}".format(number), end="")
if x < len(row) - 1:
print(end=" ")
print()
|
e3fcbca9648afb3761ee687bad5dfd16fe98a46b | sourcery-ai-bot/Estudos | /PYTHON/Python-Atividades/modulo_user.py | 1,636 | 4.125 | 4 | """Uma classe que pode usada para representar um usuário."""
class Usuário():
"""Modelar dados base de um usuário."""
def __init__(self,
nome, sobrenome, idade, sexo, escolaridade, origem
):
"""Inicializando os atributos do método."""
self.nome = nome
self.sobre... |
de5ceff4a4c66b9a1571888a41b34608b55a4b55 | ys1106/Baekjoon | /Baek_12820/venv/Lib/site-packages/nester.py | 865 | 4.09375 | 4 | """这是“nester.py"模块,提供了一个名为print_lol()的函数,这个函数的作用是用来打印列表,其中有可能包含(也可能不包含)嵌套列表"""
def print_lol(the_list,indent=False,level=1):
"""这个函数取一个位置参数,名为"the_list",这可以是任何python列表(也可以是包含嵌套列表的列表)。所指定的列表中的每个数据项会(递归的)输到屏幕上,各数据项各占一行。"""
for each_flick in the_list:
if isinstance(each_flick,list):
... |
e944ae9137500d848f3d517e8caf16a9d213d89f | shenlinli3/python_learn | /second_stage/day_04/demo_02_基础数据类型-集合.py | 1,028 | 3.9375 | 4 | # -*- coding: utf-8 -*-
"""
@Time : 2021/5/13 15:14
@Author : zero
"""
# 集合 set
# 集合是无序的
# 集合中的对象具有唯一性
# 集合的初始化
# 1.
set01 = {1, 2, 3, 4}
print(type(set01))
print(set01)
# 2.
# set02 = set("hello") # str\list\tuple
# set02 = set([1, 2, 3, 3, 4, 2]) # str\list\tuple
set02 = set((1, 2, 3, 3, 4... |
3191da3faa0032effb5f78da8c3711e4596fe916 | oppenheimera/euler | /601.py | 737 | 3.828125 | 4 | from itertools import count
def streak(n):
""" Returns the divisibility streak of n
13 is divisible by 1
14 is divisible by 2
15 is divisible by 3
16 is divisible by 4
17 is NOT divisible by 5
So streak(13)=4.
>>> streak(13)
4
"""
for i in count(0):
if (n+i) % (... |
cafc89d0019f391457ac72a2d98acd4cfce049c4 | nashit-mashkoor/Coding-Work-First-Phase- | /practice-pandas/.ipynb_checkpoints/CAPM MODEL-checkpoint.py | 1,192 | 3.515625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sun Dec 9 21:08:49 2018
@author: MMOHTASHIM
"""
import pandas as pd
import matplotlib.pyplot as plt
import quandl
from statistics import mean
import numpy as np
from IPython import get_ipython
api_key="fwwt3dyY_pF8LyZqpNsa"
def get_data_company(company_name):
df=quandl.get("... |
e3fb0787aa4a1f0b14f45ac019d7c5745923062e | here0009/LeetCode | /Python/285_InorderSuccessorinBST.py | 2,111 | 3.75 | 4 | """
Given a binary search tree and a node in it, find the in-order successor of that node in the BST.
The successor of a node p is the node with the smallest key greater than p.val.
Example 1:
Input: root = [2,1,3], p = 1
Output: 2
Explanation: 1's in-order successor node is 2. Note that both p and the return va... |
50df3f25025ee0728140414d68057558fd021369 | Aasthaengg/IBMdataset | /Python_codes/p03777/s578788663.py | 82 | 3.671875 | 4 | a,b = input().split()
if (a == 'H') ^ (b == 'H'):
print('D')
else:
print('H')
|
ab7aa11d4e9a02ee648a45c5709f2b9d02f9f0cc | Reidddddd/leetcode | /src/leetcode/python/TopKFrequentElements_347.py | 512 | 3.671875 | 4 | class TopKFrequentElements(object):
def topKFrequent(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: List[int]
use counter to count the frequency
then sort the counter with value(reverse means descending order)
then return the top k
"""... |
d5b99576034d7f75f4ad966785f0d7598be55755 | ekocibelli/Special-Topics-in-SE | /HW05_Test_Ejona_Kocibelli.py | 2,174 | 3.5 | 4 | """
Author: Ejona Kocibelli
Project Description: Testing functions reverse, rev_enumerate, find_second, get_lines.
"""
import unittest
from HW05_Ejona_Kocibelli import reverse, rev_enumerate, find_second, get_lines
class TestString(unittest.TestCase):
def test_reverse(self):
""" verify that th... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.