blob_id large_string | repo_name large_string | path large_string | src_encoding large_string | length_bytes int64 | score float64 | int_score int64 | detected_licenses large list | license_type large_string | text string | download_success bool |
|---|---|---|---|---|---|---|---|---|---|---|
d87a67d800dcaab55b67e61c28dad7d4b80bd37a | blackantywj/Leetcode_coding_everyday | /Roman_to_Integer.py | UTF-8 | 1,472 | 3.78125 | 4 | [] | no_license | class Solution:
def romanToInt(self, s: str) -> int:
dic = {'I':1, 'V':5, 'X':10, 'L':50, 'C':100, 'D':500, 'M':1000, 'IV':4, 'IX':9, 'XL':40, 'XC':90, 'CD':400, 'CM':900}
if len(s) == 0:
return 0
sum = 0
i=0
while i < len(s):
if s[i] in {... | true |
92bf807ce245025619ad7d21213f25e50d087e6d | Manuelpv17/holbertonschool-higher_level_programming | /0x10-python-network_0/6-main.py | UTF-8 | 526 | 2.859375 | 3 | [] | no_license | #!/usr/bin/python3
""" Test function find_peak """
find_peak = __import__('6-peak').find_peak
a = [1, 2, 4, 6, 3]
print(find_peak(a), a)
a = [4, 2, 1, 2, 3, 1]
print(find_peak(a), a)
a = [2, 2, 2]
print(find_peak(a), a)
a = []
print(find_peak(a), a)
a = [-2, -4, 2, 1]
print(find_peak(a), a)
a = [4, 2, 1, 2, 2, 2, 3, 1... | true |
4caef209010e432aaf8ee01050205b486929bed6 | tae100k/Python-Algorithm | /Sec4/Greedy/8. Titanic/AA.py | UTF-8 | 577 | 2.90625 | 3 | [] | no_license | import sys
sys.stdin = open("input.txt", "r")
#input받기
n, m = map(int, input().split())
weights = list(map(int, input().split()))
weights.sort(reverse = True)
cnt = 0
i = 0
while i < len(weights):
#print("weights[i]:{}, weights[-1]:{}".format(weights[i], weights[-1]))
if weights[i] + weights[-1] <= m:
... | true |
98ee0476a5adea42ea9f702c1765072f9343f4df | RyanIsBored/unit1 | /km2miles.py | UTF-8 | 116 | 3.484375 | 3 | [] | no_license | #Ryan Jones
#1/17/18
kilometers = int(input('Input number of Kilometers: '))
miles = (kilometers*0.621371)
print(miles) | true |
ce6d7887cef9b1f56c1fdc9e66a9d3cd684d831f | Sk00g/codebits | /archive/elements/button.py | UTF-8 | 5,053 | 2.671875 | 3 | [] | no_license | import pyglet
from pyglet.window import key
from archive.const import *
from archive.enums import *
from archive.primitives import Rectangle, Line
class Button(object):
def __init__(self, batch, icon, location, size, background, border_color, border_thickness=1):
self.batch = batch
self.location =... | true |
4c171b5f16ce217c035d15dd4d1c300878f30ce1 | jkfer/LeetCode | /Minimum_path_sum.py | UTF-8 | 912 | 3.03125 | 3 | [] | no_license | # https://leetcode.com/problems/minimum-path-sum/
# Medium
import sys
L = [
[1, 4, 8, 6, 2, 2, 1, 7],
[4, 7, 3, 1, 4, 5, 5, 1],
[8, 8, 2, 1, 1, 8, 0, 1],
[8, 9, 2, 9, 8, 0, 8, 9],
[5, 7, 5, 7, 1, 8, 5, 5],
[7, 0, 9, 4, 5, 6, 5, 6],
[4, 9, 9, 7, 9, 1, 9, 0]
]
K = [
[1, 3, 1],
[1, 5, ... | true |
319d309a06954cd06e3ea38b97c0e84d8143971f | psu4/mmPBSA_enery_time_series | /mmPBSA_energy_plot.py | UTF-8 | 4,345 | 2.609375 | 3 | [] | no_license | """
# AMBER MMP(G)BSA Energy Terms Post Processing: MM-PBSA Energy Plot
# Written by Pin-Chih Su and Cheng-Chieh Tsai. Last modified on Nov 13,2015
# Tested in python 2.7.6, scipy-0.13.3, matplotlib.pyplot-1.3.1, and Linux Redhat 5.0/Windows 7
"""
import matplotlib.pyplot as plt
import pylab
import os
import sys,... | true |
5f58bc677d7646459f36d46bd0b1a9fab3b66a87 | raysmith619/Introduction-To-Programming | /exercises/my_menu.py | UTF-8 | 857 | 3.4375 | 3 | [] | no_license | #my_menu.py 22Oct2022 crs, very simple menu
#
# From: https://www.pythontutorial.net/tkinter/tkinter-menu/
# With a few modifications
import tkinter as tk
# root window
root = tk.Tk()
root.title('Menu Demo')
def file_open_cmd():
""" File Open - called via File-->Open
To be done
"""
... | true |
9a0ea0b63bfd123aeb00612f9eaa1db3906fc66b | JnyJny/bitvector | /bitvector/bitfield.py | UTF-8 | 1,212 | 3.671875 | 4 | [
"Apache-2.0"
] | permissive | """Access Bits in a BitVector
"""
class ReadOnlyBitField:
"""Read-only data descriptor for accessing named fields in a BitVector.
"""
def __init__(self, offset: int, width: int = 1):
"""
:param offset: int
:param width: int
"""
self.field = slice(offset, offset + w... | true |
25687cb89cb7503d1a090824fd016ada154edfb4 | Dharmik79/Auto-Search-Error | /main.py | UTF-8 | 1,183 | 2.78125 | 3 | [] | no_license | import shlex
import requests
import webbrowser as wb
from subprocess import Popen,PIPE
def execute_and_return(cmd):
args=shlex.split(cmd)
proc=Popen(args,stdout=PIPE,stderr=PIPE)
out,err=proc.communicate()
return out,err
def make_requests(error):
resp=requests.get("https://api.stackexchange.com/"+"... | true |
0376a7bbd60c40fc54560468811062ede537ece8 | Svennevs/Quadtree-for-RRT-in-python | /RRTqtree.py | UTF-8 | 5,723 | 3.046875 | 3 | [] | no_license | # -*- coding: utf-8 -*-
"""
Created on Mon Sep 30 17:50:12 2019
@author: Sven van Koutrik
"""
import random, math, csv
from qtree import QTree, Point
class Edge:
def __init__(self, n1=None, n2=None, cost=0):
self.ID1 = n1.ID;
self.ID2 = n2.ID;
self.cost = math.sqrt( n1.dist_points(n2) ... | true |
c90f4147817fc51a65b044d629ce11754ac061d2 | erictroebs/wikigraph | /wikigraph/cli/SlotArgumentError.py | UTF-8 | 128 | 2.609375 | 3 | [] | no_license | class SlotArgumentError(Exception):
def __init__(self, index, value):
self.index = index
self.value = value
| true |
2e6bf1c8f1456ff061032bdfaf7a56b923420c9e | Abhishek-R-Soni/Python-Practice | /inventory.py | UTF-8 | 556 | 3.96875 | 4 | [] | no_license | # copy dict to other dict
inventory = {"croissant":19,
"bagel":4,
"muffin":8,
"cake":1
}
#for k,v in inventory.items():
# print(f"Key is : {k}\nValues is : {v}")
stock_list = inventory.copy()
print("After copy")
for k,v in stock_list.items():
... | true |
399e8c4532e1c839172a57a0d09a65771bc7bb10 | seonukim/Study | /keras/keras49_classify2.py | UTF-8 | 1,586 | 3.125 | 3 | [] | no_license | # 1. 모듈 임포트
from keras.models import Sequential, Model
from keras.layers import Dense, LSTM, Input
from keras.callbacks import EarlyStopping
from keras.utils import to_categorical
from sklearn.preprocessing import OneHotEncoder
from keras.utils import to_categorical
import numpy as np
# 1-1. 객체 생성
es = EarlyStopping(m... | true |
0e1b3e07148acd532f6ba8ed61660817e5d47b12 | ikoryakovskiy/grlwrappers | /grlgym/envs/grl.py | UTF-8 | 3,839 | 2.59375 | 3 | [] | no_license | import gym
from py_env import PyEnv
from gym.spaces import Box
import numpy as np
import collections
import random
class GRLEnv(gym.Env):
def __init__(self, config_file):
self.env = PyEnv()
o_dims, o_min, o_max, a_dims, a_min, a_max = self.env.init(config_file)
self.o_dims = o_dims
... | true |
eac6e2d19cf01057f03a0ba588f626c917142d7f | Yoriyari/MUSA02 | /common/game.py | UTF-8 | 13,332 | 2.765625 | 3 | [] | no_license | #===============================================================================
# Game v1.3
# - Last Updated: 18 Sep 2021
#===============================================================================
# Update History
# ..............................................................................
# 18 Sep 202... | true |
4425c86ec28ce325c10626da176a334fc61c94ae | kubakin/kubakin | /kursov/duglas2.py | UTF-8 | 2,047 | 2.609375 | 3 | [] | no_license | import matplotlib.pyplot as plt
import matplotlib.dates as dates
import time
from datetime import datetime,date
import math
file = open('data.txt')
str1 = eval(file.read())
data = str1[1335]['data']
print(len(data))
ostatok = data
maxIndex=0
e=8
start = data[0]
last = data[len(data)-1]
mass=[]
mass.append(start)
pivot=... | true |
bc042aac01a9787f4ca13f577fef44d88900ed5a | DrLex0/MightyVariableFan | /pwm_postprocessor.py | UTF-8 | 46,792 | 2.875 | 3 | [
"LicenseRef-scancode-unknown-license-reference",
"CC-BY-4.0"
] | permissive | #!/usr/bin/env python3
"""
Post-processing script that converts M106 commands into sequences of M300 beep commands that can
be detected by the beepdetect.py running on a Raspberry Pi.
It can also handle scaling of the PWM values depending on Z coordinate, to compensate for the
effect of exhaust air 'bouncing' again... | true |
e797618fd27bd694c5c5bdba4e000cc3a55c2605 | salihbout/ML_Scikit_learn | /LogisticRegression.py | UTF-8 | 1,354 | 3.015625 | 3 | [] | no_license | from sklearn import datasets
from sklearn.cross_validation import train_test_split
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import accuracy_score
import matplotlib.pyplot as plt
import numpy as np
from UsefulFunctions import plot_decision_... | true |
87df28ee50bea427d6af794a4e5bad7af5a170fc | howarder3/codility_practice | /4-2-MaxCounters-try-1.py | UTF-8 | 506 | 3.265625 | 3 | [] | no_license | # 4-2-MaxCounters-try-1.py
# you can write to stdout for debugging purposes, e.g.
# print("this is a debug message")
def solution(N, A):
# write your code in Python 3.6
num_list = [0] * N
for i in range(len(A)):
if A[i]>=1 and A[i] <= N:
num_list[A[i]-1] += 1
elif A[i... | true |
b8ede9d4afcf8c4e735d4848735462c5917776ba | ajwalkiewicz/LearningProjects | /InventoryMenager/modules/item.py | UTF-8 | 1,584 | 3.265625 | 3 | [
"MIT"
] | permissive | #!/usr/bin/python3
from dataclasses import dataclass
# @dataclass
# class Item:
# """Example:
# >>> item = Item("The Godfather", "book", "living_room", 1)
# >>> item
# Item(name='The Godfather', category='book', localization='living_room', quantity=1)
# """
# name: str
# category: str
# ... | true |
0ea556b013096fd24870fb9edecb54adcbdcab4c | Orca9412/Python-Basic-Grammar | /Python_Basic/15_문자열 자료형의 기본 함수.py | UTF-8 | 1,929 | 4.28125 | 4 | [] | no_license | a = "Hello World"
# a[2] = 'A'
# TypeError: 'str' object does not support item assignment
"""
파이썬에서 문자열은, 특정한 인덱스에 접근해서 값을 바꿀 수 없다.
"""
# 1. replace() 함수: 문자를 대체해서 반환
a.replace("Hello", "Hi")
print(a) # Hello World
"""
replace() 함수는 또 다른 값을 생성하는 것이므로, 별도의 변수에 담고
그 변수를 출력하는 방식으로 해야 한다.
"""
b = a.r... | true |
b2311a03d1f2a36e9f3d47db10dc468fef0bb494 | pasindupiumal/ROS_RIS | /scripts/SetPose.py | UTF-8 | 2,063 | 2.921875 | 3 | [] | no_license | #!/usr/bin/env python
import rospy
from geometry_msgs.msg import Twist
from sensor_msgs.msg import LaserScan
regions_ = {
'right': 0,
'fright': 0,
'front': 0,
'fleft': 0,
'left': 0,
}
def callback(msg):
global regions_
regions_ = {
'right': min(min(msg.ranges[0:143]), 10),
... | true |
b4084fa599fe66f9c57ccf374934f665c192c673 | Jeevan-Gharate/instastra | /InstAstra.py | UTF-8 | 2,331 | 3.21875 | 3 | [] | no_license | import sys
from time import sleep
import os
from colorama import Fore as F
import pyfiglet
import platform
import subprocess
clear = lambda: os.system('clear')
cls = lambda: os.system('cls')
def Clear():
if platform.system() == 'Windows':
_ = cls()
else:
_ = clear()
def sta... | true |
cf703769d5dd82b01fdbc473b0a91966c527d3b5 | raunit-x/Interpreter-From-Scratch | /basic_interpreter/constants.py | UTF-8 | 262 | 2.703125 | 3 | [] | no_license | import string
DIGITS = '0123456789'
LETTERS = string.ascii_letters
LETTERS_DIGITS = LETTERS + DIGITS
KEYWORDS = {
'VAR',
'AND',
'OR',
'NOT',
'IF',
'ELIF',
'ELSE',
'THEN',
'FOR',
'TO',
'STEP',
'WHILE',
'FUN'
} | true |
619779773ccae53aa828bea2c4f3a48f8a9d44b2 | oririnat/kidO | /kid/diffrencing.py | UTF-8 | 728 | 2.640625 | 3 | [] | no_license | import cv2
import numpy as np
kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (7, 7))
binarizationThreshold = 127
changedPrecentThreshold=0.05
def diffrencing(previousImg,newImg):
greyPreviousImg= cv2.cvtColor(previousImg, cv2.COLOR_BGR2GRAY)
greyNewImg= cv2.cvtColor(newImg, cv2.COLOR_BGR2GRAY)
diff=greyNewImg-gr... | true |
6ada39b20023b1a71df3f31487bbdb9d8eb105ec | michdol/data_structures | /linked_list/linked_list.py | UTF-8 | 5,671 | 3.46875 | 3 | [] | no_license | from operator import add, sub
class Node(object):
def __init__(self, data):
self.data = data
self.next = None
self.previous = None
class LinkedList(object):
def __init__(self):
self.head = None
self.tail = None
@property
def size(self):
current = self.... | true |
0d8085a06067f2e930251a0fd95d2cc19cc0ddde | serkancam/byfp2-2020-2021 | /hi-A4/metin1.py | UTF-8 | 449 | 3.328125 | 3 | [] | no_license | import turtle as t
t.shape("turtle")
t.Screen().setup(600,600)
t.Screen().bgcolor("light green")
metin=input("yaz:")
t.penup()
t.goto(0,250)
metin=metin.upper()
metin=metin.lower()
metin=metin.strip()
# metin=metin.replace("u","i")
metin=metin.replace("h","")
isimler=metin.split(",")
t.write(metin,font=("Arial",20,... | true |
50183e9a56068c5320992108cc39b20c0cda2b43 | elboraki/Data_structures_algo | /python/selectionSort.py | UTF-8 | 396 | 3.8125 | 4 | [] | no_license | # -*- coding: utf-8 -*-
arrayNumbers=[4,5,8,7,9,1,2,32,25,48,44]
def selectionSort(arr):
for i in range(len(arr)-1):
minIndex=i
for j in range(i+1,len(arr)):
if(arr[minIndex]>arr[j]):
minIndex=j
temp=arr[minIndex]
arr[minIndex]... | true |
a70b8bca8c4fb49cc61e3acf22f559e70bac289e | kristen-foong/spja | /labs/08/server_solution.py | UTF-8 | 4,208 | 3 | 3 | [] | no_license | import collections
import json
import socket
import sys
import threading
import traceback
MAX_NUMBER_OF_USERS = 100
def send(socket, str):
return socket.sendall("{}\n".format(str).encode())
class User:
def __init__(self, chat, addr, socket):
self.chat = chat
self.addr = addr
self.so... | true |
007bd281840af49267384c97153154e2aef301fd | Aasthaengg/IBMdataset | /Python_codes/p03448/s428397190.py | UTF-8 | 259 | 3.328125 | 3 | [] | no_license | A = int(input())
B = int(input())
C = int(input())
X = int(input())
ans = 0
for i in range(A + 1):
if 500 * i > X:
break
for j in range(B + 1):
if 500 * i + 100 * j > X:
break
if X - 500 * i - 100 * j <= 50 * C:
ans += 1
print(ans) | true |
260b97ed399dba105ae12d20f03833f1c575f13e | phiysng/leetcode | /leetcode/python/235.lowest-common-ancestor-of-a-binary-search-tree.py | UTF-8 | 1,850 | 3.90625 | 4 | [
"BSD-3-Clause"
] | permissive | # Definition for a binary tree node.
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
'''
BST的性质:
- 树上不存在重复的结点
- left < root < right
在此题中,我们从根节点开始遍历
如果两个结点都在一边,我们对将左节点作为新的root,右节点同理.
同时 如果说两个结点分别在两棵子树上,或者一个就是当前的根节点,则返回当前的根节点
伪代码:
从根节点开始遍历树
如果节点 ppp 和节... | true |
a1599b2aa453330b04dad21c6a335c6ba9a5b970 | lordseoman/cluster | /jet-mysql/skel/root/bin/serviceStatus.py | UTF-8 | 800 | 2.515625 | 3 | [] | no_license | #!/usr/bin/env python
"""
Register a new service.
"""
import requests
import os
import sys
from dotenv import load_dotenv
load_dotenv('/etc/.env')
status = sys.argv[1]
if len(sys.argv) > 2:
message = sys.argv[2]
else:
message = 'No message supplied.'
TaskId = os.environ.get("TASK_ID")
OverseerIP = os.environ... | true |
0fb06799c7963ad6a1f2095b5b009e8d65eda9cc | SamirMarin/Sparkify_cassandraETL | /queries.py | UTF-8 | 3,817 | 2.90625 | 3 | [] | no_license | #DROP TABLES
songs_in_session_drop = """DROP TABLE IF EXISTS songs_in_session"""
songs_per_user_drop = """DROP TABLE IF EXISTS songs_per_user"""
users_per_song_drop = """DROP TABLE IF EXISTS users_per_song"""
#CREATE TABLES
songs_in_session_create = """CREATE TABLE IF NOT EXISTS songs_in_session \
... | true |
9c07bf218672e91c781e9cb56c6e69bcb1495e53 | szheng31/aoc | /answers/day9/day9pt1.py | UTF-8 | 548 | 3.203125 | 3 | [] | no_license | from itertools import combinations
f = open('input.txt','r')
thelist = f.read().split('\n')
firstindex = 0
lastindex = 24
while lastindex <= len(thelist):
validnums = []
preamble = list(combinations(thelist[firstindex:lastindex + 1],2))
for i in preamble:
validnums.append(int(i[0])+int(i... | true |
de76093eacd5c3cfa50b919ae6a775ec74bbe0df | guicos/Jogos-em-Python- | /dica.py | UTF-8 | 475 | 3.828125 | 4 | [] | no_license | import random
import adivinhacao
def dica(num):
number = random.randrange(1,5)
stop = (num % 2) == 0
if( stop == True and number == 1):
print("Numero é par")
if( stop == False and number == 2 ):
print("O numero é impar")
if( number == 3):
print(f"O numero esta abaixo de ... | true |
82539cc7ddc62c55540f956285a29f86e123822d | likohank/mianshiti_2018 | /02.fibonnaci_matrix.py | UTF-8 | 900 | 3.6875 | 4 | [] | no_license | import numpy as np
import time
matrix = np.matrix('1 1;1 0')
#该矩阵list 是从 matrix 一次方开始, 斐波那切数列第二个元素 对应 本列表第一个矩阵; 第三个元素对应本列表第二个矩阵
def Fibonacci_Matrix_Tool(n):
matrix = np.matrix('1 1;1 0')
if n == 1:
return pow(matrix,1)
elif n%2 == 1:
return Fibonacci_Matrix_Tool( (n-1)/2 ) ** 2 * matrix
else:
return Fi... | true |
855d7ad5959f37cbbda04b75627dcdd21307e9ff | edwardhorsey/exercism | /python/palindrome-products/palindrome_products.py | UTF-8 | 1,242 | 3.5 | 4 | [] | no_license | from itertools import combinations_with_replacement
def get_combinations(min_num, max_num, rev=False):
if min_num > max_num:
raise ValueError('Min num cannot be larger than Max num')
num_range = sorted(range(min_num, max_num+1), reverse=True) if rev else range(min_num, max_num+1)
return combination... | true |
8502cd32679b2a250a3cdee581b56ca2a6ab90d8 | umadevic/20uma.py | /23play.py | UTF-8 | 74 | 2.859375 | 3 | [] | no_license | u=int(input())
i=str(u)
d=0
for j in i:
i=i+(int(j)**2)
print(i)
| true |
f51ea10ed38837e90d2532a3677eec8623a84874 | karansingla06/ICE-NER-NLP | /ice_commons/test/er/engines/test_corenlp_ner.py | UTF-8 | 1,969 | 2.625 | 3 | [] | no_license | from ice_commons.er.engines.corenlp_ner import CorenlpCustomNER, CorenlpDefaultNER
def test_predict_null_custom_english_null(mocker):
text = original_text = pos = ""
obj = CorenlpCustomNER()
mocker.patch('ice_commons.er.engines.corenlp_ner.stanfordcorenlp_customner', return_value=[])
assert obj.predic... | true |
23956c447a8f251893296bb78e1ea1be48263165 | lidenscheng/DataStructuresAlgorithms | /AlgorithmsToolbox/Week2/fibonacci_partial_sum/fibonacci_partial_sum.py | UTF-8 | 1,062 | 3.625 | 4 | [] | no_license | # Uses python3
#import sys
'''
def fibonacci_partial_sum_naive(from_, to):
sum = 0
current = 0
next = 1
for i in range(to + 1):
if i >= from_:
sum += current
current, next = next, current + next
return sum % 10
'''
def get_period(m):
a = 0
b = 1
c = a+b
for i ... | true |
6eaff8646942addade7f31ec9b378ff5f65cf09f | andreanero/pyfilter | /pyfilter/utils.py | UTF-8 | 3,885 | 2.96875 | 3 | [
"MIT"
] | permissive | import torch
from typing import Union, Iterable
from torch.nn import Module
from .constants import INFTY
from .typing import ShapeLike
def size_getter(shape: ShapeLike) -> torch.Size:
if shape is None:
return torch.Size([])
elif isinstance(shape, torch.Size):
return shape
elif isinstance(s... | true |
5dc5c5e9bcbabf1802826169b6ff413f0091aa45 | jasonZhang892/DNN-based_source_separation | /src/criterion/dpcl.py | UTF-8 | 1,647 | 2.671875 | 3 | [] | no_license | class AffinityLoss(nn.Module):
def __init__(self, ):
super(AffinityLoss, self).__init__()
self.maximize = False
def forward(self, input_transposed, target_transposed, batch_mean=True):
"""
Args:
input_transposed (batch_size, D, F_bin, T_bin)
... | true |
2a069d89a13d7efed28a2deb328d4c92a6ed1aea | ionu87/LearningAutomation | /wait_types/explicit_wait_1.py | UTF-8 | 2,390 | 2.671875 | 3 | [] | no_license | from selenium import webdriver
from selenium.webdriver.common.by import By
import time
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.common.exceptions import *
class ExplicitWait():
def test(self):
URL = 'https://www.e... | true |
bbe85ef83e9e124475dbebd0161c55446bfcc8fd | Aasthaengg/IBMdataset | /Python_codes/p03108/s614068288.py | UTF-8 | 1,051 | 3.03125 | 3 | [] | no_license | N,M = map(int,input().split())
AB = [tuple(map(int,input().split())) for i in range(M)]
class UnionFind:
def __init__(self,N):
self.parent = [i for i in range(N)]
self._size = [1] * N
self.count = 0
def root(self,a):
if self.parent[a] == a:
return a
else:
... | true |
06aa77f8a1414bd177cf49fa0625b2cd14968e7e | iamsusiep/natural_language_processing | /sentiment_analysis.py | UTF-8 | 1,202 | 3.234375 | 3 | [] | no_license | import nltk
nltk.download('punkt')
def format_sentence(sent):
return({word: True for word in nltk.word_tokenize(sent)})
{'!': True, 'animals': True, 'are': True, 'the': True, 'ever': True, 'Dogs': True, 'best': True}
pos = []
with open("C:/Users/iamsu/nlp/pos_tweets.txt", encoding="utf8") as f:
for i in f:
... | true |
28edb27aad21fe748f8d55bb9894fc8cbbc232f9 | jacobthewest/cs180 | /PythonLabs/Lab4/Lab4Main.py | UTF-8 | 652 | 3.75 | 4 | [] | no_license | import argparse
print("USAGE EXAMPLE: python Lab4Main.py --array 1 2 3 4")
parser = argparse.ArgumentParser()
parser.add_argument('--array', '--arg', nargs='+', type=float)
args = parser.parse_args()
input = args.array
lowestNumber = 1000000000000000000000000000
highestNumber = -1000000000000000000000000000
runningS... | true |
027b02e6b9b93359199c8417dbe45c490883d990 | RamaKrishna-Suresh/week-3-Review | /subnetcalc.py | UTF-8 | 2,371 | 2.75 | 3 | [] | no_license | class IP4Address:
ip_address=[0,0,0,0]
mask = 0
def __init__(self,ip_address,mask):
self.ip_address = ip_address
self.mask = mask
def getMask(self):
list_octat = [128,64,32,16,8,4,2,1]
list_result = [0,0,0,0]
sum_octat = 0
index = 0
sum_max ... | true |
4b1c6776c4f0713548bb7f1cc0a178b5f05e9dbb | ZhengWenSEC2023/Image-Steganalysis | /previous_trial/LLSR_yifan.py | UTF-8 | 4,962 | 2.59375 | 3 | [] | no_license | # v2020.03.19v2
# created by yifan
import numpy as np
from sklearn.metrics import accuracy_score
from numpy import inf
from sklearn.metrics import mean_squared_error
import matplotlib.pyplot as plt
from sklearn.cluster import KMeans
class LLSR():
def __init__(self, onehot=True, normalize=False):
self.one... | true |
93f7a753b9aec74f27fd48feb27b7cabc16c2bca | gokceneraslan/disentangling-vae | /disvae/models/decoders.py | UTF-8 | 8,404 | 2.984375 | 3 | [
"MIT",
"Python-2.0"
] | permissive | """
Module containing the decoders.
"""
import numpy as np
import torch
from torch import nn
class DecoderConv2D(nn.Module):
def __init__(self, img_size, latent_dim=10, kernel_size=4, num_layers=6, stride=2, padding=1, hidden_dim=256, hidden_channels=32):
r"""Decoder of the model proposed in [1].
... | true |
d716e47445339d01931cd5dd0a0cae34fd078b99 | syurskyi/Python_Topics | /125_algorithms/_examples/_algorithms_challenges/pybites/advanced/126/emoji.py | UTF-8 | 1,080 | 3.71875 | 4 | [] | no_license | import sys
import unicodedata
START_EMOJI_RANGE = 100000 # estimate
def what_means_emoji(emoji):
"""Receives emoji and returns its meaning,
in case of a TypeError return 'Not found'"""
try:
return unicodedata.name(emoji)
except TypeError:
return 'Not found'
def _make_emoji_mapp... | true |
95e2b0e7d12aebb36da5f800cadca0e520bae2bc | TomSmithson/DocsToCalendar | /GoogleDocsReader.py | UTF-8 | 2,377 | 2.71875 | 3 | [] | no_license | import pickle
import os.path
from googleapiclient.discovery import build
from google_auth_oauthlib.flow import InstalledAppFlow
from google.auth.transport.requests import Request
SCOPES = ['https://www.googleapis.com/auth/documents']
class GoogleDocsReader:
def __init__(self):
self._service = None
... | true |
55d7eb4e3491b0970db2f0ded13475f85a1618f0 | Aasthaengg/IBMdataset | /Python_codes/p02615/s682739699.py | UTF-8 | 239 | 2.984375 | 3 | [] | no_license | import math
def resolve():
n = int(input())
values = list(map(int, input().split(' ')))
values.sort(reverse=True)
ans = 0
for i in range(1, n):
ans += values[math.floor(i / 2)]
print(ans)
resolve()
| true |
4c18f4a6bfefdb2c2de251e5a11cc4c215abb468 | alvas-education-foundation/ISE_3rd_Year_Coding_challenge | /4AL17IS001_Ahimsa_Jain/SK-Challenge-1/s2.py | UTF-8 | 1,182 | 3.9375 | 4 | [] | no_license | 2) Given an array,A, of N integers and an array, W, representing the respective weights of A's elements, calculate and print the weighted mean of A's elements. Your answer should be rounded to a scale of decimal place
Input format:
1. The first line contains an integer, N, denoting the number of elements in arrays ... | true |
e3a0d403e73da68d8ab8c351e2713c1250dcca24 | ghulamghousdev/Python-Tasks | /Assignment 1/Part 3/Task-3.2.py | UTF-8 | 666 | 4.09375 | 4 | [] | no_license | import random
upperRange1 = int(input("Enter Upper range for list1: "))
noOfElements1 = int(input("Enter number of elements for list1: "))
upperRange2 = int(input("Enter Upper range for list2: "))
noOfElements2 = int(input("Enter number of elements for list2: "))
list1 = [random.randrange(1, upperRange1, 1) for i in ra... | true |
36613899808e418e9406ee30cdfe686d2cf94178 | Sin93/dobro_mail | /Bot_4.5/BotLogic/DatabaseMethods/bot_methods.py | UTF-8 | 7,436 | 2.546875 | 3 | [] | no_license | import json
from BotLogic.BotResponse.XML.XML import XML, HTML
import config
from BotLogic.DatabaseMethods.models import Categories, Projects, History, ImageInfo, User
from BotLogic.BotResponse.Validation.DataSets.DataSet import DataSet
class Database:
"""
Основной класс для работы с БД
"""
... | true |
83adae19dfa80f244dcc6dd4872c7963b45ee5ae | sobolevn/cosmic-ray | /cosmic_ray/operators/break_continue.py | UTF-8 | 960 | 3.03125 | 3 | [
"MIT"
] | permissive | """Implementation of the replace-break-with-continue and
replace-continue-with-break operators.
"""
import ast
from .operator import Operator
class ReplaceBreakWithContinue(Operator):
"Operator which replaces 'break' with 'continue'."
def visit_Break(self, node): # pylint: disable=invalid-name
"Vi... | true |
2691d7e9759e2ca17e8c670dd5ebf76c9a32b5d3 | BaranAkcakaya/ProgramlamaLab. | /DERS_1-BUBBLE SORT.py | UTF-8 | 783 | 3.75 | 4 | [] | no_license | #BİR LİSTEYE RANDOM DEGERLER ATAMA.
import random
def generate_an_array(n):
my_array=[]
for i in range(n):
s=random.randint(0,100)
my_array.append(s)
return my_array
my_arr_1=generate_an_array(10)
print(my_arr_1)
#LİSTE İCİNDE ARAMA YAPMA.
def my_search_c(array_2,item):
found=... | true |
8bbeb76a60fb5eba802a74051db940795b826418 | EmilioLrp/CIS667_2048_game | /src/game/game.py | UTF-8 | 4,656 | 3.28125 | 3 | [] | no_license | import numpy as np
import math
from src.game.board import Board
from src.game.actions import Action
class Game:
def __init__(self):
self._game_board = None
self._board_indexes = None
self._goal = None
self._move_count = 0
self._weighted_score = 0
self.init_board(si... | true |
c1e16f4646906a0766acd7fe9adb7aeb6b4fc7eb | obonyojimmy/biobb_structure_utils | /biobb_structure_utils/utils/remove_ligand.py | UTF-8 | 6,553 | 2.59375 | 3 | [
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | #!/usr/bin/env python3
"""Module containing the RemoveLigand class and the command line interface."""
import argparse
import Bio.PDB
from biobb_common.configuration import settings
from biobb_common.tools import file_utils as fu
from biobb_common.tools.file_utils import launchlogger
from biobb_common.command_wrapper i... | true |
a9d8d68f8747f023848dda66298299fc8881ce64 | EskerOn/GeneticAlgorithm | /geneticFun.py | UTF-8 | 9,986 | 3.0625 | 3 | [] | no_license | import random
###Temporal para hacer pruebas
class Individual:
def __init__(self, LearningR : float, Momentum : float, Period : int, HiddenLayers : list):
self.LearningR = LearningR
self.Momentum = Momentum
self.Period = Period
self.HiddenLayers = HiddenLayers
self.FitnessVa... | true |
33b2dbb4fcdc312f94ba7b414d56bea07407b6e9 | amaralcs/advent_of_code | /day7/solution.py | UTF-8 | 1,248 | 3.3125 | 3 | [] | no_license | import re
import networkx as nx
import matplotlib.pyplot as plt
from utils import read_file
def create_edge(source, destination):
if destination == 'no other':
return None
qty = re.search(r"^(\d+)", destination).group()
name = re.search(r"(\w+\s?\w+$)", destination).group()
return (source, name... | true |
b0b46d1fbe59e1aa5c23b41d874d50d8d04ef126 | SanHime/bfassist | /bfassist/webgen/framework/html/node.py | UTF-8 | 15,179 | 3.125 | 3 | [
"Apache-2.0"
] | permissive | #############################################################################
#
#
# HTML Node webGenFramework module to BFA c7
#
#
#############################################################################
""" This is a HTML node module for a simple HTML/JS/CSS generator/framework with the purpose of maintaining t... | true |
5ade2aeeab1cbbf1984a5d7256520d80f6af1f8f | AdamZhouSE/pythonHomework | /Code/CodeRecords/2496/60706/264222.py | UTF-8 | 412 | 3.3125 | 3 | [] | no_license | def reorganizeString(S):
lst = sorted(sorted(S), key=lambda x: S.count(x), reverse=True)
n = int(len(S) / 2 + 0.5) # 奇数位数时取中间右边一位
if lst[0] == lst[n]: # 最多的字符超过半数
return ''
else:
return ''.join(j for i in zip(lst, lst[n:]) for j in i) + ['', lst[n - 1]][len(S) ... | true |
a0770dbef7a1f15f2ca9e30074c21dcc78e6bcd5 | lightning-pro/dhash | /asdhash.py | UTF-8 | 1,453 | 2.984375 | 3 | [
"MIT"
] | permissive | import asyncio
import time
import random
import string
class ASyncDHash(object):
def __init__(self):
self.nodes = [ASyncNodes('#1'), ASyncNodes('#2')]
async def read(self, key):
if key % 2 == 0:
await self.nodes[0].read(key)
else:
await self.nodes[1].read(key)
async def write(self, key, value):
if ... | true |
24e0683b3f1b2bcdf8bf5c800a9e5811fec38cdc | fmerg/zkay | /src/zkay_ast/analysis/partition_state.py | UTF-8 | 2,454 | 3.40625 | 3 | [
"MIT"
] | permissive | from typing import Set, Dict
class PartitionState:
"""
Supports operations on partitions
- insert: create a new partition with a single element
- merge: merge partitions
- ...
"""
def __init__(self):
self._partitions: Dict[int, Set[object]] = {}
def insert(self, x):
p = {x}
self._insert_partition(p)
... | true |
77c2679b7af288b54fe93fabcbe364a450c99bec | ninopira/kaggle_m5 | /0601_28model/feature/trend_week/week_trend.py | UTF-8 | 1,201 | 2.546875 | 3 | [] | no_license | # val 週間前との割合
import pandas as pd
import sys
sys.path.append('../../')
print('read_transformed...')
df_all = pd.read_pickle('../../scaled_35093990_33386550_melt_over0sellprice.pkl')
print(df_all.shape)
for base in range(1, 29):
print(base)
df_feat = df_all[['id', 'demand', 'date']]
useless_cols = ['deman... | true |
5f478176c0e57750af34d968ef1ff72812815afc | bibiksh/Python_trainging | /2.Python_basic/Chapter05/Problem49_2.py | UTF-8 | 140 | 3.09375 | 3 | [] | no_license | def dono(m,n):
bordd=m*n
donoo=2
return bordd//donoo
alist=list(map(int,input().split()))
m=alist[0]
n=alist[1]
print(dono(m,n)) | true |
9902ca43011eabe82b86b95c3869ec73fcbb274b | Oxel40/TTTBot | /Board.py | UTF-8 | 3,598 | 3.203125 | 3 | [] | no_license | from tkinter import *
from tkinter.ttk import Frame, Label, Style
import numpy as np
from copy import copy
from random import random
class Board(Frame):
def __init__(self, master, BotAI):
self._Bot_AI = BotAI
self.Player_decisions = []
Frame.__init__(self, master)
self.master = ma... | true |
58b769f16419e21decaab97f4630a69080626068 | mikeshultz/scatter-contracts | /tests/test_env.py | UTF-8 | 3,066 | 2.8125 | 3 | [] | no_license | """ Tests for the Env contract """
from .utils import (
get_accounts,
std_tx,
has_event,
get_event,
)
from .consts import (
ENV_CONTRACT_NAME,
UINT_HASH_1,
UINT_VAL_1,
STR_HASH_1,
STR_VAL_1,
)
def test_env_owner(web3, contracts):
""" Make sure owner is set """
admin, _, _, ... | true |
a1e53caea8c889529c240619fb9afd9980920df9 | daniel-reich/ubiquitous-fiesta | /st8HBr2HMup6mD6z5_11.py | UTF-8 | 116 | 3.34375 | 3 | [] | no_license |
def profit_margin(cost_price, sales_price):
return '{:.1f}%'.format(100*(sales_price-cost_price) / sales_price)
| true |
ccf685f5b84f7d27f3ba6546b1108f1a620a7d15 | pelarejo/KooC | /KoocGrammar/Class.py | UTF-8 | 5,180 | 2.53125 | 3 | [] | no_license | #!/usr/bin/env python3
from pyrser.grammar import Grammar
from pyrser import meta
from cnorm import nodes
from cnorm.parsing.declaration import Declaration
from KoocGrammar.KC_Statement import KC_Statement
from cnorm.parsing.expression import Idset
from cnorm.nodes import *
from mangler.simple_mangling import VARS
imp... | true |
7345141ed2711d1b307b50aed34da2799545f30f | tayyabmalik4/Python-With-Tayyab | /55-oops-self-constructer.py | UTF-8 | 2,118 | 3.265625 | 3 | [] | no_license | # in this tutorial we learn about self and __init__ function constructor
# ///////////////////////////////////self concept//////////////////
# sab sa pahla ek function bnaty han os ma ek argument data han
# pher os ka through variables ko integrate kr data han
# pher jab function ko run krta waqat function ma argume... | true |
b85e69978c984c8ec8cf6e63b5b211d35e43c3df | davidlamyc/bto-resale-etl | /merge-resale-with-cpi.py | UTF-8 | 350 | 2.515625 | 3 | [] | no_license | import pandas as pd
import os, errno
import math
resale_df = pd.read_csv("./resaleflatprices-distance.csv")
cpi_df = pd.read_csv("./housing-cpi.csv")
df = pd.merge(resale_df, cpi_df, how='left', left_on=['year'], right_on = ['year'])
df['adjusted_price'] = df['resale_price'] / df['cpi'] * 100
df.to_csv('./resalefla... | true |
59fda716f7834900d33ed22afa822f5810a87b3b | AnonymouX47/ucode-2.0 | /challenges/rgb-to-hex/gen.py | UTF-8 | 716 | 3.046875 | 3 | [] | no_license | #! /usr/bin/env python3
from random import randint
from solution import solve
ranges = ((0, 225), (-1000, -1), (256, 1000))
i = -1
for r in ranges:
for g in ranges:
for b in ranges:
rgb_ranges = (r, g, b)
t = randint(1, 10)
i += 1
with open(f"testcases/inpu... | true |
969678227369cec07eab15709dceb743e0291d1d | emaestre/leet-code | /jump-game/jump-game.py | UTF-8 | 266 | 2.65625 | 3 | [] | no_license | class Solution:
def canJump(self, nums) -> bool:
nums_len = len(nums)
last_pos = nums_len - 1
for i in range(nums_len - 1, -1, -1):
if i + nums[i] >= last_pos:
last_pos = i
return last_pos == 0
| true |
c064ab3277fa19680a5ceda32eb02c1c2659097a | JonasSatkauskas/magic8ball | /magic8ball.py | UTF-8 | 1,525 | 3.3125 | 3 | [] | no_license | import random
import time
time.sleep(0.2)
# Pasisveikinimas su paaiškinimu
print('Labas, aš be rūpesčių atsakysiu į klausimą su pradžia "ar"')
print("\nJeigu nori išeiti, įvesk raidę 'q'")
# Galimi programos atsakymai
atsakymai = ['Taip',
'Ne',
'Aš dabar užsiėmęs... Paklausk manęs vėliau...',
'Tikrai taip!... | true |
fee26872f8f568a79785e41d349ad21254fd703d | 7up4/amcl | /package/model/metadata.py | UTF-8 | 2,798 | 2.84375 | 3 | [] | no_license | import pandas as pd
class Metadata:
def __init__(self, columns: list):
self._significance = 'significance'
self._statistic = 'statistic'
self._resulting = 'resulting'
self._sensitivity = 'sensitivity'
self._pvalue = 'pvalue'
self._table = pd.DataFrame(columns=column... | true |
6ea61cf01e3babc8b9f78b335dc7e37accaff408 | dean-ayalon/DS-Workshop | /features/event_time.py | UTF-8 | 2,696 | 3.390625 | 3 | [] | no_license | import numpy as np
import pandas as pd
# This feature corrects click timestamps for timezone differences
# in the 4 most common countries in the data: US, Canada, Great Britain and Australia.
# After this correction is applied, the resulting times are "binned" into
# 5 different periods using boolean vectors:
# Morni... | true |
de2ea4b314cd8ced5fa03ee168846d2fb383d231 | lzy2099/FastAPI_TEST | /two_form_data/JSON_Econder.py | UTF-8 | 660 | 2.734375 | 3 | [] | no_license | # -*- coding:utf-8 -*-
from fastapi import FastAPI
from pydantic import BaseModel
from datetime import datetime
from fastapi.encoders import jsonable_encoder
fake_db = {}
class Item(BaseModel):
title: str
timestamp: datetime
description: str = None
app = FastAPI()
@app.put("/items/{id}")
def update_i... | true |
7747cbe1e403b088aa9f5d8fc14526dfcb93395e | amaradatta93/matrixfun | /Amara_Datta_Sachidananda_solve.py | UTF-8 | 8,423 | 3.890625 | 4 | [] | no_license | """
Instructions:
- Implement the function `path_exists` below.
- Save this file as `{first_name}_{last_name}_solve.py`.
Constraints:
- Your solution will be run in a Python2.7 environment.
- Only python standard library imports can be used and they must be imported within `path_exists`.
- The func... | true |
83fb9a62a5b64940dc919b7c383118afde450b39 | nicolageorge/play | /system-design/hashmap.py | UTF-8 | 1,493 | 3.3125 | 3 | [] | no_license | import unittest
def print_data(func):
def wrapper(*args, **kwargs):
print args[0]._data
rv = func(*args, **kwargs)
print args[0]._data
print "---------------end execution------------------"
return rv
return wrapper
class Item:
def __init__(self, key, value):
self.key = key
self.value = value
def _... | true |
2c0499d4e9b9a35f6b5157932fa2d58bcdf5f7d3 | bnsreenu/python_for_microscopists | /052-GMM_image_segmentation.py | UTF-8 | 2,975 | 3.875 | 4 | [] | no_license | #!/usr/bin/env python
__author__ = "Sreenivas Bhattiprolu"
__license__ = "Feel free to copy, I appreciate if you acknowledge Python for Microscopists"
# https://www.youtube.com/watch?v=kkAirywakmk
"""
@author: Sreenivas Bhattiprolu
NOTE: I was alerted by one of the viewers that m.bic part needs more explana... | true |
491bc1b10a0f6e6c9abbef94c870e1a26ec4e544 | ralvarezum/lab | /ejercicios/Ejercicios 25-03/ej6.py | UTF-8 | 328 | 3.53125 | 4 | [] | no_license | cadena = input("Ingrese la cadena de numeros separados por comas:")
cadena2 = ''
lista = []
for i in range(0, len(cadena)):
if (cadena[i] != ','):
cadena2 = cadena2+cadena[i]
else:
lista.append(int(cadena2))
cadena2 = ''
lista.append(int(cadena2))
lista.sort(reverse=True)
print... | true |
7b0469da0ec3c60b1c38e07a0e0d4f44998ccef0 | jadenpadua/ICPC | /core/Matrix/square-in-matrix.py | UTF-8 | 335 | 3.4375 | 3 | [] | no_license | class Solution:
def squareInMatrix(self, matrix: List[List[str]]) -> int:
squares = []
for i in range(len(matrix)-1):
for j in range(len(matrix[i]) - 1):
square = [matrix[i][j],matrix[i][j+1],matrix[i+1][j],matrix[i+1][j+1]]
squares.append(square)
... | true |
9bb9c82cab4c143ebe26946395787203db3b96b6 | vincentwang1517/Machine-Learning-Practice | /hw6/MF.py | UTF-8 | 3,435 | 2.65625 | 3 | [] | no_license | # python3 this.py model
# no.86
import sys, io, os
import numpy as np
import pandas as pd
from keras import regularizers
from keras.models import Model
from keras.layers import Input, Embedding, Dense, merge, Flatten, Add
from keras.optimizers import Adam
from keras.callbacks import ModelCheckpoint
from mltools impo... | true |
95f528ffaeee1633959ca0f7fc689033bbca3bc9 | wangchi87/Server | /Server2.py | UTF-8 | 3,967 | 2.796875 | 3 | [] | no_license | import select
import sys
from socket_wrapper import *
class ServerEnd:
serverSock = None
port = 12354
host = None
RECV_BUFFER = 1
sockCollections = []
def __init__(self):
self.host = socket.gethostname()
self.__mainLoop()
def assignHostAddr(self, host):
self.... | true |
5763caa114ef7e5ac52e976fc6eb3e1420f84139 | hjm0702/MPCS-51042-Python | /spring-2018-hw8-hjm0702-master/spring-2018-hw8-hjm0702-master/problem1.py | UTF-8 | 2,789 | 3.1875 | 3 | [] | no_license | import matplotlib.pyplot
import multiprocessing
import time
def mandelbrot(c, max_iterations=100):
'''evaluate iterations'''
counter = 0
def determine(x,c,max_counter):
nonlocal counter
counter += 1
z = x**2+c
if abs(z)>2:
return counter
elif... | true |
72eb7b603b01ccb86ad2cde16c74cec4fc0a1a64 | JasoSalgado/algorithms | /sorting-by-selection/exercises/exercise-04.py | UTF-8 | 320 | 4.09375 | 4 | [] | no_license | """
Sorting by selection
"""
list = [9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
print(f"List: {list}")
for i in range(len(list) - 1):
minimum = i
for x in range(i, len(list)):
if list[x] < list[minimum]:
minimum = x
aux = list[i]
list[i] = list[minimum]
list[minimum] = aux
print(list)
| true |
95258fc20eb04f8474a19bb69a18171bfbd67c17 | LetsHaveFun/aio_anticaptcha | /tests/helpers.py | UTF-8 | 940 | 2.921875 | 3 | [
"Apache-2.0"
] | permissive | import asyncio
from unittest import mock
def fake_coroutine(return_value, iter_v=False):
def coro(*args, **kwargs):
if iter_v:
value = next(return_value)
else:
value = return_value
if isinstance(value, Exception):
raise value
return value
r... | true |
d469e7e7cffd932f18f06c3ee3d13df52d7a8675 | group4BCS1/BCS-2021 | /src/midterm/mid_term.py | UTF-8 | 3,249 | 4.09375 | 4 | [
"MIT"
] | permissive | def output():
print('\n'"Customer Code: ", a)
print("Beginning Meter Reading: ", b)
print("Ending Meter Reading: ", c)
print("Gallons of Water Used: ", gallons_used)
print("Amount Billed: $", bill,'\n')
while True:
a = input("Enter code:\n ")
a = a.lower() #Changing the customer code t... | true |
bc8a70d59ea057f56b5d401bc1990c75bb725d21 | AdamZhouSE/pythonHomework | /Code/CodeRecords/2949/60651/239045.py | UTF-8 | 107 | 3.203125 | 3 | [] | no_license | inlist=input().split()
inlist.remove("0")
inlist.reverse()
outlist=" ".join(inlist)
print(outlist,end=" ")
| true |
d4a1c0c02648abb388dba921cd2c96fc0cad761f | NAMEs/Python_Note | /爬虫/爬虫学习01/17.py | UTF-8 | 466 | 2.78125 | 3 | [] | no_license | '''
案例存在问题,可以顺利爬取
'''
from urllib import request
import ssl
# 利用非认证上下文环境替换认证的上下文环境
# default 默认值
# unverified adj. 未经核对的,未经证实的
ssl.create_default_context = ssl._create_unverified_context
try:
url = 'https://www.12306.cn'
rsp = request.urlopen(url)
html = rsp.read().decode()
... | true |
364db46aa35a2d0d02aa248660f3523ef5659cb8 | eric-zhu94/leetcode | /242. Valid Anagram.py | UTF-8 | 676 | 3.25 | 3 | [] | no_license | class Solution:
def isAnagram(self, s: str, t: str) -> bool:
s_seen = {}
t_seen = {}
for i in range(len(s)):
if s[i] not in s_seen:
s_seen[s[i]] = 1
else:
s_seen[s[i]] +=1
for j in range(len(t)):
if t[j] not in t_see... | true |
c2d9f39be898a75f286efeb26786254fa32fd52f | JunchuangYang/Machine-Learning | /K-均值(k-means)算法/k-均值算法实现/kmeans_test.py | UTF-8 | 640 | 2.8125 | 3 | [] | no_license | # -*- encoding:utf-8 -*-
from kmeans import *
import matplotlib.pyplot as plt
# 从文件构建的数据集
dataMat = file2matrix('training_4k2_far.txt',"\t")
# 提取数据集中的特征列
dataSet = dataMat[:,0:]
# 指定有k个聚类中心
k=4
Clustercents,ClustDist = kMeans(dataSet,k)
# 返回计算完成的聚类中心
print('Clustercents:\n',Clustercents)
# 输出生成的ClustDist:对应的聚类中心(... | true |
1c20b8d29abaaa268c751e456bea486d05059c13 | nadrarar/HuffmanCoding | /project/speech.py | UTF-8 | 1,216 | 3.21875 | 3 | [] | no_license | import sys
import re
import operator
import itertools
class Speech(object):
def __init__(self, filename,wordUsage0=None):
if(wordUsage0==None):
wordUsage0 = {}
self.wordUsage = wordUsage0.copy()
self.wordCount = 0
self.parseFileAndCountWordUsage(filename)
def parseFil... | true |
e4c091f334a52a33c5732ab1e6ef08d4aa104f7f | corutopi/AtCorder_python | /other/2019/diverta2019ProgrammingContest/D.py | UTF-8 | 657 | 3.6875 | 4 | [] | no_license |
def get_divisors(num):
"""
指定した整数のすべての約数を配列にして返す.
:param num:
:return:
"""
import math
max_num = math.floor(math.sqrt(num))
re = set()
for i in range(1, max_num + 1):
if num % i == 0:
re.add(i)
re.add(num // i)
return sorted(re)
def solve():
... | true |
2c6575cfb9e25af993c071aedd05741b5ba839f9 | mocmeo/algorithms | /find-good-days-to-rob-banks.py | UTF-8 | 566 | 3.296875 | 3 | [] | no_license | from tkinter import N
def goodDaysToRobBank(security, time):
n = len(security)
left = [0]*n
right = [0]*n
res = []
for i in range(1, n):
if security[i-1] >= security[i]:
left[i] = left[i-1] + 1
else:
left[i] = 0
for i in range(n-2,-1,-1):
if security[i+1] >= security[i]:
right[i] = right[i+1] ... | true |
a9cd46975186fe5de99c1694ca3bb99d80fec10b | Mehedi-Bin-Hafiz/Data-Mining-Class | /DecisionTree/DTAlgorithm.py | UTF-8 | 4,552 | 2.921875 | 3 | [] | no_license | import pandas as pd
import math
dataSet = pd.read_excel('examdata.xlsx')
print('\n#################Entropy Part#####################\n')
############ look me #############
dtClass = dataSet.buymobile ##must assign decision class
############# look me ############
dtClassCountedValue = dtClass.value_counts(sort=... | true |
d425a2fdd8e090835cba1806c4bd0b85b5296776 | bungamaku/foundation-programming-1 | /Lab/Lab DDP (1)/lab01_D_NN_Bunga Amalia Kurniawati_1706022104_pertarungan1.py | UTF-8 | 532 | 3.234375 | 3 | [] | no_license | #Lab DDP kelas D, 8 September 2017
#Bunga Amalia Kurniawati - Ilmu Komputer 1706022104
#Pertarungan 1
import turtle
t = turtle.Turtle()
panjang = int(input('Masukkan panjang dari sisi anak tangga: '))
t.pendown()
t.color('yellow')
t.left(90)
t.forward(panjang)
t.right(90)
t.forward(panjang)
t.color('... | true |