blob_id stringlengths 40 40 | repo_name stringlengths 5 119 | path stringlengths 2 424 | length_bytes int64 36 888k | score float64 3.5 5.22 | int_score int64 4 5 | text stringlengths 27 888k |
|---|---|---|---|---|---|---|
4e08f866c6b750c0523aaa96833ed67c4e606e3d | jordan78906/CSCI-161_projects | /HernandezAlmache_Jordan_9.py | 6,417 | 3.875 | 4 |
#Jordan Hernandez-Alamche
#CSci 161 L03
#Assignment 9
'''
Extend the shopping cart class
'''
class ShoppingCart:
count = 0
def __init__(self,customer_name,current_date):
self.customer_name = customer_name
self.current_date = current_date
self.cart_items = []
def add_item(self,It... |
5063a1d8744b0bec91ed57b4af7c6ee5b91bb82f | Chaitalykundu/100daysofCoding | /filter_func.py | 354 | 3.625 | 4 | #filter function
def even(a):
return a%2==0
number=list(range(1,11))
print(number) #o/p:[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
n=filter(even,number)
print(n) #o/p:<filter object at 0x030EB8D0>
evens=tuple(filter(even,number))
print(evens) #o/p:(2, 4, 6, 8, 10)
even_no=list(filter(lambda i:i%2==0,number))
prin... |
c020627c3ebd8a0dfe54bb2b179137dfade2e80a | wayne-pham/pci-xpress | /databaseCreation.py | 9,141 | 3.65625 | 4 | import sqlite3
database = sqlite3.connect("pythonsqlite.db")
cursor = database.cursor()
############ TABLES #############
# Store
cursor.execute("DROP TABLE IF EXISTS STORE")
store = """
CREATE TABLE STORE
(
Store_Name VARCHAR(100) NOT NULL,
Address_line_1 VARCHAR(100) NOT NULL,
City VARCHAR(100) NOT NULL,
S... |
deb27cc24b0de5884ec92c38f479ef3f1df3a766 | soom1017/ITE1014 | /2020_ITE1014/5-1/2.py | 308 | 3.984375 | 4 | import random
numbers = []
for i in range(0,100):
a= random.randint(1, 1000)
numbers.append(a)
for j in numbers:
print(j, end = ' ')
print('\n')
max_number = 1
for k in numbers:
if k > max_number:
max_number = k
print("max value: " + str(max_number))
|
36e14e604f52315bc26630b23b757d4fd6b4fee0 | 41xu/SwordToProblem | /04重建二叉树.py | 952 | 3.53125 | 4 | # -*- coding:utf-8 -*-
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
# 返回构造的TreeNode根节点
def reConstructBinaryTree(self, pre, tin):
# write code here
root=pre[0]
rootindex=tin.index(root)
... |
bbf42b09e9fa78bca48430d9269e90c9cb9cf549 | markgreene74/bitesofpy | /bytes/40/exercise_40.py | 812 | 4.03125 | 4 | # https://codechalleng.es/bites/40/
def binary_search(sequence, target):
# define the uppper/lower limits
low = 0
high = len(sequence) - 1
# start the search
while low <= high:
# pick the middle
middle = (low + high) // 2
# now start the search
if sequence[middle] == ... |
4ad9dddfb4d22162ba91be7ee16df6b535069079 | NiuNiu-jupiter/Leetcode | /Premuim/1102. Path With Maximum Minimum Value.py | 1,492 | 3.828125 | 4 | """
Given a matrix of integers A with R rows and C columns, find the maximum score of a path starting at [0,0] and ending at [R-1,C-1].
The score of a path is the minimum value in that path. For example, the value of the path 8 → 4 → 5 → 9 is 4.
A path moves some number of times from one visited cell to any ne... |
d496e3554c6145e451a5b61a70df2d53e3454fca | WillPowerCraft/my-first-repository | /str_lines_slices.py | 1,548 | 4.1875 | 4 | # Python поддерживает emoji
# Индексация символов в строке - указать конкретный символ внутри []
# s = 'Hello'
# print(s[0])
# # Python индексирует символы в строке по возрастающей и по убывающей '-1' - последний символ строки
# print(s[-1])
# # Пример сканирования каждого символа в строке
# # Такой способ удобен, если... |
593b395ec358252d6ef7a4afb6839d0131e887f0 | GiovanniScattolin/stock_market | /stock_package/scripts/csv_reader.py | 1,141 | 3.953125 | 4 | import pandas as pd
def read_currency_data(path):
"""Read the file containing data about currencies, store it in a DataFrame
:param path: The path to the .csv file containing currencies info
:type path: string
:return: the Dataframe containing infos about the currencies
:rtype: Pandas.Dataframe
... |
d95d9688d393bc9df6ad00d41e544cfcaa044a2f | projjal1/PCAP_Programming_Series | /classes_part1.py | 484 | 4.34375 | 4 | #Program to demonstrate the simple implementation of OOP concept
#using classes in Python
class A:
'''This class is for simple demo of constructors and methods'''
def __init__(self):
'''Default-constructor'''
print("Inside the constructor")
def hello(self):
'''Prints hello'''
... |
abb561c2081b9a56dc4e1f156de92a9678a916d0 | sunilkum84/golang-practice-2 | /revisiting_ctci/chapter1/ZeroMatrix_1_8.py | 1,098 | 3.65625 | 4 | """
take an m x n matrix and if there is a zero in the matrix then change the entire
row and column it is in to 0s
"""
import unittest
def ZeroMatrix(mat):
""" take a list of lists where cells are integers,
if there is a zero cell then change all values in the row and
column to zero """
z_rows = []
z_cols = [... |
70fd0ed87f2cc53e9b3c5aaa6d860d372a2070e7 | donggyuu/algorithm | /algorithm-python/chp2_check_palindrome_string.py | 1,342 | 3.734375 | 4 | '''
N개의 문자열을 입력받아 회문이면 YES, 아니면 NO를 출력하는 프로그램을 작성한다.
(대소문자 구분은 안함, 각 단어 길이는 100을 넘지 않는다)
**input
5
level
moon
abcba
soon
gooG
**output
# 1 YES
# 2 NO
# 3 YES
# 4 NO
# 5 YES
'''
# ---------------------------------
# 여러 방법
# 1. for문으로 역순 구하기
# 2. [::-1] // 이거 문자열에서만 쓰임. list는 해보니까 안되더라...
# 3. method활용 -> reverse, reve... |
a14538fbc19b998f44d3ed1634b5faef4091e76e | nosoccus/Applied-Programming | /LAB3/lab1-4.py | 231 | 3.8125 | 4 | arr = ['a', ['c', 1, 3], ['f', 7, [4, '4']], [{'lalala': 111}]]
lst = []
def func(arr):
for i in arr:
if type(i) == list:
func(i)
else:
lst.append(i)
return lst
print(func(arr))
|
194e478fd23c2078973bd2aa8d3f76fcf2fc7735 | ljia2/leetcode.py | /solutions/hashtable/750.Number.Of.Corner.Rectangles.py | 2,341 | 3.796875 | 4 | import collections
import math
class Solution(object):
def countCornerRectangles(self, grid):
"""
Given a grid where each entry is only 0 or 1, find the number of corner rectangles.
A corner rectangle is 4 distinct 1s on the grid that form an axis-aligned rectangle.
Note that only t... |
08d320cdb159c3c38a1e08fe533a26d8348a74a5 | omergundogdu75/python-egitim | /OOP/specials.py | 669 | 3.796875 | 4 | mylist = [1,2,3]
# myString = "My String"
#
# print(len(mylist))
# print(len(myString))
#
# print(type(mylist))
# print(type(myString)print(type(myString)
class Movie:
def __init__(self,title,director,duration):
self.title = title
self.director = director
self.duration = duration
pri... |
ed70b2da7484a8a9e94170113f446c39140569f5 | iamchiranjeeb/Python-Task | /task/passwords.py | 1,123 | 3.703125 | 4 | import re
class Capital(object):
def __init__(self,str):
self.string = str
def capitalCheck(self):
if re.search("[A-Z]",self.string):
return True
else:
return False
class Small(Capital):
def __init__(self,str):
super().__init__(str)
def smallChe... |
48400e8bb1e0f42c0cdca5a10187d4587875021d | zyxdSTU/Ner_Method | /util.py | 379 | 3.734375 | 4 | #获取词典
def acquireWordDict(inputPathArr, wordDict):
for inputPath in inputPathArr:
input = open(inputPath, 'r', encoding='utf-8', errors='ignore')
for line in input.readlines():
if len(line) == 0: continue
word = line.split(' ')[0]
if word not in wordDict:
... |
1e0f3685bea6d6b428404b65e69b73cc530ec915 | jadewu/Practices | /Python/Reverse_String_II.py | 526 | 3.71875 | 4 | # 把string分成多个片段放进list里,每个片段长度为k
# 把每两个片段中的第一个reverse,第二个不动
# 把所有片段join一下
class Solution:
def reverseStr(self, s: str, k: int) -> str:
# Divide s into an array of substrings length k
s = [s[i:i+k] for i in range(0,len(s),k)]
# Reverse every other substring, beginning with s[0]
for i in range(0,le... |
e82ffd1539d515872bbf777cf424d28e0e075181 | satusuuronen/pythai | /gp/command.py | 3,683 | 3.78125 | 4 | """
@project: Pythai - Artificial Intellegence Project with Python
@package: Genetic Programming
@author: Timo Ruokonen (timoruokonen)
"""
import random
from literal import literal
from global_variable import global_variable
class command:
'''
Represents a command (function call) in the generated code. Command... |
1d7a6d523975ef4245a1ea0a348f52b262d67f7e | buyi823/learn_python | /Python_100/python_79_string_order.py | 825 | 4.28125 | 4 | #!/usr/bin/python3
# -*- coding: UTF-8 -*-
# By Blaine 2021-08-04 16:43
# string order
if __name__ == '__main__':
str1 = input('input string:\n')
str2 = input('input string:\n')
str3 = input('input string:\n')
print(str1, str2, str3)
if str1 > str2:
str1, str2 = str2, str1
if str1 > st... |
5055a423d4f7ac3e4df64d06ba63f704bb2d3103 | gistable/gistable | /all-gists/32d1a0d97e391392dec10a83070336f8/snippet.py | 5,816 | 3.671875 | 4 | def move_to_dir(old, new):
"""Converts using e.g. old position (1,1) and new position (2, 1) to a direction (RIGHT)"""
if old[0] < new[0]:
return "RIGHT"
if old[1] < new[1]:
return "DOWN"
if old[0] > new[0]:
return "LEFT"
return "UP"
def get_score(starts):
"""
Funct... |
06668bb6ab52aeb5b5eb2468576b4c7e6cc8502a | Bram-Hub/Proof-Generator | /src/main.py | 2,319 | 3.546875 | 4 | import os
import sys
import argument_parser as arg_p
from lxml import etree
def main():
print("Prove or disprove an argument defined in a .bram file. All premises should be defined in assumption tags "
"and all goals should be defined in goal tags within the proof with an id of 0.\n")
location = os... |
f195b163b4ac2aec77a6e17e8e1cfada43691f1f | ADebut/Leetcode | /844. Backspace String Compare.py | 485 | 3.625 | 4 | class Solution:
def backspaceCompare(self, S: str, T: str) -> bool:
s = []
for i in range(len(S)):
if S[i] == '#' and s:
s.pop()
elif S[i] != '#':
s.append(S[i])
t = []
for i in range(len(T)):
if T[i] == '#' and t:
... |
4f8cc15d24a17974a31a54e773f958ae58f939dc | kunalkhadalia04/python_sample | /Documents/Python_Projects/numbers1.py | 123 | 3.640625 | 4 | var1 = 10
var2 = 5
var3 = 2
var4 = 3
print(var4**var3)
var5 = var3*(var1+var2)
print(var5)
var6 = 0.5
print(var1*var6)
|
27ca4d76856476cb7276131aa0e70840a15f37fb | vishalpmittal/practice-fun | /funNLearn/src/main/java/dsAlgo/leetcode/P9xx/P925_LongPressedName.py | 1,898 | 3.8125 | 4 | """
Tag: string
Your friend is typing his name into a keyboard.
Sometimes, when typing a character c, the key might get
long pressed, and the character will be typed 1 or more times.
You examine the typed characters of the keyboard.
Return True if it is possible that it was your friends n... |
b34dabc1bc8cf7474cf000a2ad0578c23ce4d540 | ryzvonusef/ryzvonusef.github.io | /PYTHON/empy.py | 1,270 | 3.703125 | 4 | import csv
import pandas as pd
eFileName = './employee_file.csv'
class Employee:
def __init__(self,eFirstName,eLastName,eID,eCNIC,ePhoneNumber):
self.empFName = eFirstName
self.empLName = eLastName
self.empID = eID
self.empCNIC = eCNIC
self.empPhone = ePh... |
db4540ee7d0adc40bc3692bd45d9b0fc4c4bc5eb | pybokeh/python | /code_snippets/SortedDictionary.py | 144 | 3.53125 | 4 | myhash = {1:'John', 4:'Dick', 3:'Bill', 2:'Alex'}
for score in sorted(myhash.keys(), reverse=True):
print myhash[score] + ' ' + str(score)
|
91f1601d2f69ff64d93ad5c0b912d73eb7da801a | Derek-Y-Wang/Octagon-Health-Data-Science-Competition | /question_2.py | 4,164 | 3.609375 | 4 | # Name: Question 2
# Date: 07/11/2020
# Authors: Robert Ciborowski, Derek Wang
# Description: Answers question 2 of the competition: What might predict
# successful therapy? We use a patient recovering before 9 months
# as a success.
# The code starts running in main() (at the bo... |
d492da35c2d2191dbbf72b0e7ec7457c50f4da29 | rohitbhatghare/python | /Dec-21-2020/DuckTyping.py | 292 | 3.65625 | 4 | class Duck:
def talk(self):
print('quack..quack..')
class dog:
def talk(self):
print('bow bow')
class goat:
def talk(self):
print('Myah myah')
def f1(self):
obj.talk()
l = [Duck(), dog(), goat()]
for obj in l:
f1(obj)
|
0cd98a4d0d40e0f7b730e8ef07b18a374a52baa0 | LBouck/ProjectEulerSolutions | /PythonSolutions/ProjectEuler001.py | 265 | 3.609375 | 4 | #project euler 001
import numpy as np
import time
t0 = time.time()
# create array of values up to 1000
arr = np.arange(1,1000)
sum = np.sum(arr[np.logical_or(arr%3==0, arr%5==0)])
t1 = time.time()
print("Sum is: "+str(sum))
print("Time elapsed is: "+str(t1-t0))
|
5f52970b26c5443bb53114b7551cc804157140e6 | junweinehc/Python | /Practice/jusPractice.py | 558 | 3.9375 | 4 |
#just practice
#don’t waste time reading pls
name = "Loha hahaha"
print(name.title())
print("python \nC \nJava")
print(name.rstrip())
print(name.lstrip())
print(name.strip())
fName="eric"
lname="dak"
fullName=f"{fName} {lName}"
print("Hello " + fullName + ", " + "would you like to learn some Python today?")
import... |
e260558548e8b6c1c7114f1405c9659deda05295 | Blade6/PythonDiary | /文件读写/IO编程/picking.py | 1,865 | 3.796875 | 4 | # -*- coding:utf-8 -*-
# 我们把变量从内存中变成可存储或传输的过程称之为序列化,在Python中叫pickling,在其他语言中也被称之为serialization,marshalling,flattening等等,都是一个意思。
# 序列化之后,就可以把序列化后的内容写入磁盘,或者通过网络传输到别的机器上。
# 反过来,把变量内容从序列化的对象重新读到内存里称之为反序列化,即unpickling
# Python提供两个模块来实现序列化:cPickle和pickle。这两个模块功能是一样的,
# 区别在于cPickle是C语言写的,速度快,pickle是纯Python写的,速度慢,跟cStringIO... |
c533aa17ae6829bfdd347a4402334c43cb7342f1 | acvanw79/pyglet-starter | /game.py | 609 | 3.765625 | 4 | import pyglet # import the library
window = pyglet.window.Window() # create the window
# Create some text
label = pyglet.text.Label('Hello erabody', x = 200, y = 200)
# inside the loop:
def on_draw():
text.draw()
# label = pyglet.text.Label('Hello, world', x = 200, y = 200)
# Create a sprite
ball_image = ... |
2e02aaddff53488797e06d00e6d2b1e6e2c7ae4f | FlimothyCrow/Python | /battleship.py | 2,654 | 3.84375 | 4 | import copy
def updateGame(game, move, player):
[row, col] = move
newGame = game
newGame[row][col] = player
return newGame
# updateGame(beginBoard, [0,0], 1)
def printGame(game):
for row in game:
print(row)
def moveValid(game, move):
x, y = move
if game[x][y] == 9 :
re... |
b0325df7b58ec4e68cc80bf2feedd0572a4bf8f7 | aadityadabli97/Python-Practice | /17.py | 795 | 3.890625 | 4 | # concept of radiobutton
from tkinter import *
import tkinter.messagebox as tmsg
main=Tk()
def order():
tmsg.showinfo("order received",f"we have received your order for {var.get()} thanks for ordering")
main.geometry("500x500")
main.title("concept of radiobutton")
#var=IntVar()
var=StringVar()
var.set("no... |
b69ec24f0d3678e76099963aabb690cd41b704f4 | Degelzhao/python | /advanced_features/slice.py | 220 | 3.984375 | 4 | #使用切片来完成trim操作
def trim(s):
if s[:1] != ' ' and s[-1:] != ' ': #判断首尾是否为空
return s
elif s[:1] == ' ':
return trim(s[1:])
elif s[-1:] == ' ':
return trim(s[:-1])
|
23f8276a07d57898876f15a6dd6544d63b3fcb9e | ammartawil/AdventOfCode2017 | /day3/spiral_memory.py | 1,673 | 4.03125 | 4 | # -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function, unicode_literals
import math
# import pdb; pdb.set_trace()
x = 361527
# Start by finding which square x is in.
sq_root_x = math.sqrt(x)
int_sq_root_x = int(sq_root_x)
# Squares sizes are 1, 3, 5, 7, etc.
# If sqrt of x is even,... |
c4c4c6f14a6edf8bfbefd3fd1b578a8e6c3cf4e5 | emiliacg/Python-Class | /Estructuras de datos 1.py | 736 | 3.921875 | 4 | print("esto es un texto")
Emilia=13
print(Emilia+6)
Miguel=Emilia+6+8
print(Miguel)
# se compara Emilia con el numero 14
if Emilia==14:
print("hola")
# Estructuras de datos 1
Compras=["carne","leche","arroz","huevos","carne","leche","arroz","huevos","carne","leche","arroz","huevos","carne","leche","arroz","huevo... |
17cbd0b5b66bc985ce87a72c15f90358c034c731 | tomaszbobrucki/numeric_matrix | /Problems/Markdown heading/task.py | 225 | 3.734375 | 4 | def heading(phrase, quant=1):
if quant <= 1:
return "#" + " " + phrase
elif 6 > quant > 1:
return "#" * quant + " " + phrase
else:
return "#" * 6 + " " + phrase
# print(heading("A", 10))
|
db55950185325b7ddcff85bb27f01a7246521ee6 | alfitec/ProjectEulerChallenge | /project7/project7_10001stPrime.py | 571 | 3.90625 | 4 | """
10001st prime
Problem 7
By listing the first six prime numbers: 2, 3, 5, 7, 11, and 13,
we can see that the 6th prime is 13.
What is the 10 001st prime number?
"""
import math
def prime(number):
primes=[]
for i in range (2,number+1):
i_is_prime=True
sqroot=math.sqrt(i)
for j i... |
18d2f39bb5116554528ee1cc769d9342ac88eb32 | yiming1012/MyLeetCode | /LeetCode/字符串/20. Valid Parentheses.py | 1,122 | 3.765625 | 4 | class Solution:
def isValid(self, s: str) -> bool:
'''
执行用时 :36 ms, 在所有 Python3 提交中击败了62.46%的用户
内存消耗 :13.5 MB, 在所有 Python3 提交中击败了23.89%的用户
:param s:
:return:
'''
left = ['(', '{', '[']
total = ['()', '{}', '[]']
res = []
for i in s:
... |
8abef3688739666c0b04c18ca0c336798094d992 | sochic2/kis | /머신러닝 이론 및 실습/Day_01_02_numpy.py | 2,167 | 3.65625 | 4 | # Day_01_02_numpy.py
import numpy as np
# 문제
# 0~9까지의 리스트를 만들어서 거꾸로 출력하세요.
a = list(range(10))
print(a)
print([i for i in reversed(a)])
print(a[3:4])
print(a[3:3])
print(a[-1])
print(a[:])
print(a[::])
print(a[::2])
print(a[9:0:-1])
print(a[9:-1:-1])
print(a[-1:-1:-1])
print(a[::-1])
print('-------------------... |
82670b27e8b382cb33c2a15af6be4ecd70ea2606 | ender8848/the_fluent_python | /chapter_14/demo_14_17.py | 1,465 | 3.96875 | 4 | import itertools
'''
示例 14-17 演示用于合并的生成器函数
'''
# 调用 chain 函数时通常传入两个或更多个可迭代对象
print(list(itertools.chain('ABC', range(2))))
'''['A', 'B', 'C', 0, 1]'''
# 如果只传入一个可迭代的对象,那么 chain 函数没什么用
print(list(itertools.chain(enumerate('ABC'))))
'''[(0, 'A'), (1, 'B'), (2, 'C')]'''
# 但是 chain.from_iterable 函数从可迭代的对象中获取每个元素,然后按顺序把元素连接... |
60728a6b6812ffc9c46430ae805e3dfea6e0c20d | anupjungkarki/IWAcademy-Assignment | /Assignment 1/DataTypes/answer42.py | 164 | 3.953125 | 4 | # Write a Python program to convert a list to a tuple.
list_data = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
print(list_data)
tuple_data = tuple(list_data)
print(tuple_data)
|
7eef6098a977199f80456d28eb39a6116a62044a | spenserca/aoc-python | /src/_2020/day_nine/utils.py | 1,368 | 3.953125 | 4 | def is_sum_of_two_preamble_values(preamble: [int], number: int):
for i in range(len(preamble)):
first_number = preamble[i]
other_numbers = preamble[i + 1:]
sums = [first_number + on for on in other_numbers]
if number in sums:
return True
return False
def... |
45b80cff8d0098026bfb1c50ee123bfb5bdbe729 | bitores/python-life | /demo_re2.py | 364 | 3.953125 | 4 | import re
pattern = re.compile(r'hello')
match = pattern.match('hello world!')
if match:
print match.group()
p=re.match(r'hello','hello world!')
print p.group()
# a <==> b
a = re.compile(r"""\d + # the integral part
\. # the decimal point
\d * # some fractional di... |
4d3fc5380a824cceb962c3116540d1bd914d92b0 | ee491f/python-demo-2021 | /branching.py | 127 | 4.03125 | 4 | number = 3.3
if number > 3:
print("greater than 3")
print("greater than 3 again")
else:
print("less than or equal to 3") |
7eaa2eb20ae9e569a9d7719a519de9faee25c9a1 | Ramlanka7/PythonSample | /ListExamples.py | 303 | 3.703125 | 4 | q = [1, "Plum", 3.14, 2, "One", 3]
print(q[1])
print(q[0:2])
print(q[1:])
print(q[-1])
print(q[:3])
a = [1, 2, 3]
b = [4, 5, 6]
print(a * 2)
c = a + b
print(c)
del c[1:3]
print(c)
d = [1, 2, 3, 4, 5, 6]
d[1] = 'a'
print(d)
d[2:4] = ['b', 'c']
print(d)
d[2:4] = ["A", "B", "C", "D"]
print(d)
|
30628ff1849cc1fa494b709add2b218e8ddc86d4 | cosmos512/PyDevoir | /StartingOutWithPy/Chapter 07/ProgrammingExercises/08_random_number_file_reader.py | 308 | 3.671875 | 4 | # This exercise assumes you have completed Programming Exercise 7, Random
# Number File Writer. Write another program that reads the random numbers from
# the file, display the numbers, and then display the following data:
# • The total of the numbers
# • The number of random numbers read from the file
|
ee44d53d1d2a643710b5dbf8a44e55200765346b | UnsableMin/guess-number | /main.py | 719 | 3.96875 | 4 | import random
print ("welcome to number Guesser")
comp_num = random.randint (0, 10)
tries = 3
won = False
play = True
while play == True:
while tries > 0:
print()
player_num = input ("enter a number between 0-10:")
player_num = float(player_num)
if player_num < 0 or player_num > 10:
print ("Ba... |
143b49c369565b2f1c15323f141ab471510e9cde | atuanpham/HMM | /hmm/forward_algorithm.py | 2,564 | 3.6875 | 4 | import numpy as np
def compute_alpha(t, x_t, A, B, alpha_matrix):
"""
Compute the joint probability of each state and observation x_t at time t.
x_t is a index of 'observations' list.
Arguments:
t -- Time t.
x_t -- The observation at time t.
A -- State Trans... |
17c55236c9038564112321bfd96301d1f2bcb551 | dhtcwd/learnpython | /EX18.py | 793 | 4.28125 | 4 | # -*- coding:utf-8 -*-
# this one is like your scripts with argv
def print_two(*args):
arg1, arg2 = args
print "arg1: %r, arg2: %r" % (arg1, arg2)
# ok, that *args is actually pointless, we can just do this
def print_two_again(arg1, arg2):
print "arg1: %r, arg2: %r" % (arg1, arg2)
# this just takes one ar... |
62cd2d31f76f87fbf6c581b5109da8a2c3247079 | ImranAvenger/uri-python | /1180.py | 214 | 3.6875 | 4 | x = input()
y = (raw_input()).split(' ')
m = 0
p = 0
for i in range(x):
y[i] = int(y[i])
if y[i] < m:
m = y[i]
p = i
print "Menor valor: " + str(m)
print "Posicao: " + str(p)
|
9a0539fab47ef4162437bc2d31969b24b090bebf | BenTsai7/Machine-Learning-Practical-Codes | /Logistic_Regression/two-classification.py | 2,162 | 3.890625 | 4 | # 多特征梯度下降算法
# 用于二分类的逻辑回归
import numpy as np
import matplotlib.pyplot as plt
# 学习率 非常关键的参数,调得不好容易导致无法收敛,甚至不断震荡至溢出
learning_rate = 0.001
# 迭代次数
iterations = 1000
def sigmoid(z):
return 1 / (1 + np.exp(-z))
def gradient_descent(x_data,y_data):
weightslen = x_data.shape[1]
weights = np.ones(weightslen)
... |
576d73bad9e36fef2506a9689f63eb608c18df2f | gulamd/python | /fromkeys_get_copy.py | 383 | 3.734375 | 4 | #fromkeys-use to create dictionary
#d = {'name' : 'unknown', 'age': 'unknown'}
#d = dict.fromkeys(['name','age','height'],'unkown')
#print(d)
# get method
d = {'name' : 'gulam', 'age': 'unknown'}
#print(d.get('name'))
#if d.get('name'):
# print('present')
#else:
# print('not present')
# if none --->false ,... |
4cca03034fca913727ba8f97c449141a2b85f5c1 | assassint2017/leetcode-algorithm | /House Robber III/House_Robber_III.py | 1,422 | 3.609375 | 4 | # Runtime: 72 ms, faster than 39.39% of Python3 online submissions for House Robber III.
# Memory Usage: 15.8 MB, less than 5.09% of Python3 online submissions for House Robber III.
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = N... |
a266386c7a9c68a16ccacd87bbd8db11dd411322 | fatmazgucc/python-neuralNetworkStart | /mainSetListTuple.py | 1,624 | 3.9375 | 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}') ... |
cce699583232f74950feafc91d64e9cd0d48f940 | dagongji10/LeCode | /scripts/9.py | 525 | 3.6875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Thu Aug 15 14:17:42 2019
@author: Administrator
"""
def isPalindrome(x: int) -> bool:
if x<0:
return False # 不能用'false'代替
else:
s = '#' + '#'.join(str(x)) + '#' # 也可以直接用字符串倒序然后判断是否相等
center = int(len(s)/2)
p = 1
... |
cbb88d6182d96b1a4f095ebc274320ffd086aba2 | Mariamapa/Formulario- | /formulario.py | 2,418 | 3.515625 | 4 | from tkinter import *
def send_data():
#Definición de las variables
usuario_info = usuario.get()
contraseña_info = contraseña.get()
nombre_info = nombre.get()
edad_info = str(edad.get())
#Abriremos la sección de llenado
print(usuario_info,"\t", contraseña_info,"\t", nombre_info,"\t", edad_info)
... |
6fb555e4774deb8ea038269ce1b4a9fd04f75c01 | varshinireddyt/Python | /GoldManSachs/StringCompression.py | 2,036 | 3.703125 | 4 | """
Leetcode 443: StringCompression
Given an array of characters chars, compress it using the following algorithm:
Begin with an empty string s. For each group of consecutive repeating characters in chars:
If the group's length is 1, append the character to s.
Otherwise, append the character followed by the group's ... |
ad168ea3cc67035dcb1bee60c7ff2b4b20f88f7e | hnzhang/python | /SierphinskiTriangle.py | 1,577 | 4.09375 | 4 |
import turtle #draw graphics
def draw_triangle(points, color, turtle_instance):
'''
draw triangle
'''
#print("Color", color)
turtle_instance.fillcolor(color)
turtle_instance.up()
turtle_instance.goto(points[0][0], points[0][1])
turtle_instance.down()
turtle_instance.begin_fill()
... |
8f4bc53e79d249a93e780eb71841fa183423bd7e | MilenaTupiza/programacion | /funmultiply.py | 302 | 4 | 4 | # -*- coding: utf-8 -*-
"""
Created on Tue Jun 30 11:59:27 2020
@author: User
"""
def multiply(a,b):
print("El resultado en print de la multiplicacion es: ",a,"y ",b,"es ", a*b)
print("\n")
return (a*b)
print("\n")
multiply(4,5)
print("El resultado es: ",multiply(5,4))
|
a9f5b4e37f3b3abd184d0637dec914a38cc32ceb | gratsgravelsins/DMI | /PYTHON/sinmape/bezj1.py | 701 | 3.515625 | 4 | # -*- coding: utf-8 -*-
#from math import j1
#import numpy as np
#import matplotlib.pyplot as plt
#Jasarēķina savs kods tieši šajā veidā
#viena argumenta funk
#def mans_sinuss(x):
#def j1(x,n):
k = 0
a = (-1)**0*x**1/(1)
s = a
# while k<0:
while k<n:
k = k + 1
R = (-1) * x**2/(k*(4*k+4))
a = a * R
s... |
ea93b55582e94eb8efb731e235207f1b5f725f97 | Navdeep656/python_file_handling | /main.py | 1,271 | 3.609375 | 4 | import requests
def fetch_rest_api():
print("Rest API call")
response = requests.get("https://reqres.in/api/users?page=1")
user_data = response.json()
print(user_data)
total = user_data["total"]
print(total)
data = user_data['data']
for record in data:
print(record["id"], recor... |
02cbbeafe4d2d86effbb855a2267023920e89fd2 | gopularam/developer | /Python/Generator_Fibonacci.py | 271 | 3.65625 | 4 |
def fibinocci():
a,b = 1,1
while 1:
yield a
a,b = b, a+b
def main():
counter =0
for i in fibinocci():
print(i)
counter+=1
if counter == 5:
break
print('Done')
if __name__ == '__main__':
main() |
3cdd09b92243b04a334e16cecc648eca82770419 | masilvasql/curso_python3_basico_avancado | /fundamentos_projetos/area_circunferencia_v4.py | 213 | 3.96875 | 4 | # import math
from math import pi
raio = input("Informe o raio : ")
areaCircunferencia = pi * float(raio) ** 2
print(f'A área da circunferência é {areaCircunferencia}')
print('Nomde do módulo', __name__)
|
7fafc497a71882ca12696ceadd6a204baa363484 | JESmith804/python-challenge | /PyPoll/main.py | 2,746 | 3.65625 | 4 | import os
import csv
# input file path
csvpath = os.path.join ('..', 'PyPoll', 'election_data.csv')
# Lists to store data
voterIDs = []
candidates = []
voteCounts = []
# set initial values
i = 0
j = 0
k = 0
win = 0
# opens input file, removes header row and loops through the remaining rows
with open(csvpath, newli... |
05c126ebf480bd19ad7fea07aa3f674f875566f2 | quento/encrypting-with-python | /ca-server.py | 5,179 | 3.609375 | 4 | import socket
import helper
from helper import simpleCipher
class CertServer:
"""
This class creates a simple certificate server that verifies a server belongs to a certain certificate
"""
def __init__( self, host = '127.0.2.1', port = 9000 ):
self._host = host
self._port = ... |
eaa9255d75cb57217d5bfc13e4444108fd2690aa | ARUNDHATHI1234/Python | /co1/program11.py | 226 | 4.03125 | 4 | a=int(input("enter first number"))
b=int(input("enter second number"))
c=int(input("enter third number"))
if a>b:
if a>c:
print(a,"is big")
else:
print(c," is big")
elif b>c:
print(b,"is big")
else:
print(c," is big")
|
2d5d59705197ca008c0354752f088b3920706155 | xuziyan001/lc_daily | /25-reverse-kgroup.py | 1,540 | 3.5625 | 4 | from tool import ListNode,concat_node
class Solution:
def reverseKGroup(self, head: ListNode, k: int) -> ListNode:
if k < 2:
return head
if not head:
return head
start = head
end = head
for i in range(k-1):
end = end.next
if n... |
52147d6f868ae549874a7092ae35bc92c931ebb9 | gonzeD/CS1-Python | /LoadSaveGame/src/CorrLoadSave.py | 622 | 3.515625 | 4 | #!/usr/bin/python3
# -*- coding: utf-8 -*-
def save_data(filename, life, mana, position_x, position_y):
with open(filename, 'w') as f:
f.write(str(life)+'\n')
f.write(str(mana)+'\n')
f.write(str(position_x)+'\n')
f.write(str(position_y)+'\n')
def load_data(filename):
try:
... |
27f668cca9053c7ea130091c03df8a36eee6771a | aaron0215/Projects | /Python/HW11/temps_ex.py | 1,899 | 3.515625 | 4 | import tkinter
class TempCoverterGUI:
def __init__(self):
self.main_window = tkinter.Tk()
self.top_frame = tkinter.Frame(self.main_window)
self.bottom_frame = tkinter.Frame(self.main_window)
self.prompt1_label = tkinter.Label(self.top_frame,\
... |
9f17c7e06b7755bf62fc710e6fd51519b73d26e4 | udaykodeboina/Test | /import_decimal.py | 351 | 3.75 | 4 |
from decimal import Decimal
a = 22 #total number of days
"""
This is a mothly payable calculation
"""
b = 600 # daily allowance
c = a * b
d =Decimal(c * 0.27)
e = c - d
print ("No of days in a month are:", a)
print ("Daily allowance per day is:", b)
print("Monthly Expected: ", c)
print("tax Payable", round(d,2))
pri... |
0ce7036e6b737dd291b6e1054ec5c090a76d3cfd | bmiraski/tlacs | /ch9.py | 2,475 | 4.09375 | 4 | import turtle
import sys
import string
def test(did_pass):
""" Print the result of a test. """
linenum = sys._getframe(1).f_lineno # Get the caller's line number.
if did_pass:
msg = "Test at line {0} ok.".format(linenum)
else:
msg = ("Test at line {0} FAILED.".format(linen... |
cd01ffa2ae8c08a0d7e22ede49a0008f3bd9d228 | sandipan898/agent-selection-program | /agent_selector.py | 2,930 | 3.671875 | 4 | import random
def create_agent_list():
""" Used to make a agent data list if needed """
while True:
agent_list = []
agent_id = input("Enter an unique agent id: ")
is_available = input("Is the agent available?(0/1) ")
available_since = input("Available Since: ")
roles =... |
3388970ba4d218a06e06e6444c6c5511c54ea002 | ghaed/Fun-With-Algorithms | /Heap-Median/median.py | 1,247 | 3.765625 | 4 | """ Calculates the median using heap"""
import heapq
f = open('test_case_large.txt')
lines = f.readlines()
x_list = [int(numeric_string) for numeric_string in lines]
# x_list = [1, 2, 3, 4, 5]
heap_high = [] # Min- heap
heap_low = [] # Also min-heap, stored as negative numbers
medians_sum = 0
x0 = x_l... |
28b211f3e937b75aa4f05e8d2d4f2ac373e2ba72 | maciejdomagala/thegreatUpsolving | /various/FindComplement.py | 389 | 3.875 | 4 | """
Given a positive integer num, output its complement number. The complement strategy is to flip the bits of its binary representation.
"""
class Solution(object):
def findComplement(self, num):
"""
:type num: int
:rtype: int
"""
num_b = bin(num)[2:]
ans = ''.join(... |
19e516773399fd7f591936c172389b4bd9115c34 | KidSpace/GretaPy | /Question3.py | 984 | 4.03125 | 4 | # Greta's Quiz Game
from matplotlib.pyplot import imshow
import numpy as np
from PIL import Image
number = 3
#--Cool Image to show if they answer the question Right
pil_im = Image.open('door3.png', 'r')
imshow(np.asarray(pil_im))
imshow(pil_im)
#--The Question and Answer Pairs
print('Congenital hearing loss is...?\n... |
78d4436cd3059da058ef2f5f059502aba9aac4c0 | WUJIAWIN/Data-Structure-Algo-P3 | /P7.py | 5,061 | 3.515625 | 4 | # Problem 7
# Request Routing in a Web Server with a Trie
# A RouteTrie will store our routes and their associated handlers
class RouteTrie:
def __init__(self, handler = None, description = None):
# Initialize the trie with an root node and a handler, this is the root path or home page node
self.ro... |
eea24fad422d5317c2f9e7884a62548b03bd7837 | Yashika1305/PythonPrograms | /prog10.py | 258 | 3.90625 | 4 | m=int(input("Enter marks in maths"))
p=int(input("Enter marks in physics"))
c=int(input("Enter marks in chemistry"))
if (m>=65 and p>=55 and c>=50 and m+p+c>=180 and m+p>=140 and m+c>=140):
print("Eligible for course")
else:
print("not eligible")
|
39ed4ebd96d241d32a998df12507205b27b431fd | ewatso11/ew_bootcamp | /seq_features_and_tests.py | 935 | 3.921875 | 4 | def number_negatives(seq):
"""Number of negative residues a protein sequence"""
# Convert sequence to upper case
seq = seq.upper()
# Count E's and D's, since these are the negative residues
return seq.count('E') + seq.count('D')
def test_number_negatives_for_single_AA():
"""Perform unit tests... |
9e783df208e273dfd1689fdc4497685016351507 | ijoshi90/Python | /Python/sum_of_odd_evens_in_list.py | 1,128 | 3.875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Wed Sep 4 19:40:50 2019
@author: akjoshi
"""
# Count sum of off and even numbers in list
from random import *
odd = 0
even = 0
odd_total=0
even_total=0
odd_list=[]
even_list=[]
def odd_even(numbers):
for i in numbers:
if i % 2 == 0:
even_list.append(... |
4629d65f5a4b6a15091aede2e8813d100d3f89d1 | JonnyCheong/machineLearning | /learning2.py | 1,749 | 3.625 | 4 | #The code do the machine learning. Finally export .pkl file.
import numpy as np
from sklearn.model_selection import train_test_split
import matplotlib.pyplot as plt
from sklearn.decomposition import PCA
from sklearn.svm import SVC
from sklearn.neighbors import KNeighborsClassifier
from sklearn.externals import j... |
75df4bd86deab4163f51103dec6648c60ccdc838 | cristianA06/ProgCompEAFIT.github.io | /20171/presentaciones/Ordenamiento/sol2.py | 503 | 3.59375 | 4 | import random
def insertionSort():
tam = 10000
lista = random.sample(range(0,tam+1),tam)
#print lista
for index in range(1,len(lista)):
actual = lista[index]
pos = index
while pos>0 and lista[pos-1]>actual:
lista[pos]=lista[pos-1]
pos = pos-1
... |
dd74a8a74e4781c733dd3afbe3ba8abbfbec39d1 | joaquinloustau/cmsi386 | /homework1/lines.py | 241 | 3.78125 | 4 | import sys
num_lines = 0
for line in open(sys.argv[1]):
line = line.strip()
if line and not line.startswith("#"):
num_lines += 1
print num_lines
#http://stackoverflow.com/questions/7896495/python-how-to-check-if-a-line-is-an-empty-line
|
aae475e1e3e8056f060a3e13614788d8a15ba507 | yeshixuan/Python | /02-高级语法系列/07-多线程/04.py | 944 | 4.03125 | 4 | #利用time延时函数,生成两个函数
# 利用多线程调用
# 计算总运行时间
# 练习带参数的多线程启动方法
import time
# 导入多线程处理包
import threading
def loop1(in1):
# ctime得到当前时间
print("Start loop 1 at:", time.ctime())
# 睡眠多长时间,单位是秒
print("我是参数:", in1)
time.sleep(4)
print("End loop 1 at:", time.ctime())
def loop2(in1, in2):
print("Start loop ... |
77e53b10be0fd480bc40a6fbac933196086c7838 | Kandiotti/Setiembre2021 | /PensamientoComputacional/scope.py | 294 | 3.546875 | 4 | def funcion1 (arg, func):
def funcion2(arg):
return arg * 2
valor = funcion2(arg)
return func(valor)
def funcion_random(arg):
return arg * 5
def main():
argumento = 2
print(funcion1 (argumento, funcion_random))
if __name__ == '__main__':
main() |
3b0fa50159622197f8e4617fbdcfd5339701b737 | NuAyeSan/python-class1 | /variable.py | 805 | 3.671875 | 4 | + - * /
%
**
>>>2 + 2
4
>>>50 - 5 * 6
20
>>>(50 - 5 * 6 ) / 4
5.0
>>>round(5.0)
5
>>>5.123456
5.123456
round(5.12345,2)
5.12
>>>17 / 3
5.666666667
>>>17 // 3
5
>>>18 // 4
4
>>>20 // 5
4
>>>17 % 3
2
>>>17 * 4 % 3
2
a = 1
a (variable) = (assign) 1 (value)
weight = 50
height = 5 * 9
vol = weight * height
vol
sale = 30... |
0fd8e4df976c34732be82e16ef76b829188f7473 | kiminh/offer_code | /06_PrintListFromTailToHead.py | 982 | 3.96875 | 4 | # -*- coding:utf-8 -*-
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
# 返回从尾部到头部的列表值序列,例如[1,2,3]
# 循环
def printListFromTailToHead(self, listNode):
# write code here
value = []
while listNode:
value.insert(0, listN... |
da3969e6ad90a6a77a395965f8ff7ae7e8ba16da | tchirktema-zz/python-cme | /bianne.py | 407 | 3.953125 | 4 | #ce programme permet de voir si une annee est bisexitile
annee = input("Entrer l'annee : ")
#conversion de l'annee en entier
annee = int(annee)
if annee%400 == 0:
print(str(annee)+ " est bisexitile")
elif annee%4 == 0:
if annee%100 != 0:
print( str(annee)+ " est bisexitile")
else :
print... |
7af826fd1a14c3901c37b55a8167f6cec345b681 | SoliDeoGloria31/study | /AID12 day01-16/day02/code/if.py | 246 | 3.796875 | 4 | # if.py
# 写一个程序,输入一个整数,判断这个整数是奇数还是偶数
# 分析: 奇数对2求余一定等于1
x = int(input('请输入一个整数: '))
if x % 2 == 1:
print(x, '是奇数')
else:
print(x, '是偶数')
|
7047bb9d45bafcefb774e03ca14c4a45c166387b | mspspeak/problems | /python/euler_seven.py | 588 | 3.90625 | 4 |
# By listing the first six prime numbers: 2, 3, 5, 7, 11, and 13, we can see that the 6th prime is 13.
# What is the 10 001st prime number?
def divisible_by(a,b):
if (a != 0) and (b != 0):
return (a % b) == 0
else:
return False
def is_prime(n):
i = 2
upperbound = n
return_value = True
while i < upperb... |
ce7ed7fe2cdb8557440e85f57a1e6c8ff62cbca9 | DanielMevs/Babylonian-Algorithm | /hw7.py | 547 | 4.15625 | 4 | import math
def bab(x):
x0 = 0.1
x1 = x/2
if(x<0):
raise Exception("x should not be less than 0. The value of x was: ", x)
while .01 <= abs(x1-x0)/x0:
x0 = x1
r = x/x0
x1 = (x0+r)/2
print(x1)
return x1
x = 0
x = float(input("Please input the value of x: "))
... |
822d51bcb839bad0bbe3a2fb51323f6b83ed33f1 | Ramsey0179/Ramboilk-CWEU | /Assig8_Leapyear.py | 271 | 3.765625 | 4 | year = int(input("Sene kaç, girin lütfen :"))
leap_year = year % 4 == 0 and (year % 100 != 0 or year % 400 == 0)
result = (leap_year == True)*'artık yıldır.' + (leap_year == False)*'artık yıl değildir.'
print(f"Girdiğiniz *{year:^10}* senesi {result:^20}!")
|
0c0eb1a6f46c3d8f9521e4b622bd8c3f3b081349 | RaviTejaKomma/learn-python | /unit5_assignment_05.py | 2,844 | 4.21875 | 4 | __author__ = 'Kalyan'
notes = '''
1. Read instructions for the function carefully and constraints carefully.
2. Try to generate all possible combinations of tests which exhaustively test the given constraints.
3. If behavior in certain cases is unclear, you can ask on the forums
'''
from placeholders import *
... |
473a9d56a78bde3f3573a74a2b33ddd7dce50275 | weilin-zhang/MyProject_siat | /Python/data_structure/LeetCode/FlippingAnImage.py | 1,162 | 3.59375 | 4 | '''
给定一个二进制矩阵 A,我们想先水平翻转图像,然后反转图像并返回结果。
水平翻转图片就是将图片的每一行都进行翻转,即逆序。例如,水平翻转 [1, 1, 0] 的结果是 [0, 1, 1]。
反转图片的意思是图片中的 0 全部被 1 替换, 1 全部被 0 替换。例如,反转 [0, 1, 1] 的结果是 [1, 0, 0]
输入: [[1,1,0],[1,0,1],[0,0,0]]
输出: [[1,0,0],[0,1,0],[1,1,1]]
解释: 首先翻转每一行: [[0,1,1],[1,0,1],[0,0,0]];
然后反转图片: [[1,0,0],[0,1,0],[1,1,1]]
输入: [[1,1,0,0],[1,... |
79b584580f750c160d49e781d4dab6bf6435dcf8 | jankeromnes/Python-Calc | /phys/main.py | 1,126 | 4.0625 | 4 | #! /usr/bin/python3.7
import os
print("Welcome to the physics calculator available calculators include: distance speed time calculator (dstc), gravity formula(gf), lorentz factor(lf), mass energy(mee),line displacement(ld), velocity (velocity) acceleration(acceleration), range(range)")
while True:
keywords1 = ["dst... |
4e86c437cd9843fad1e21820a7088cc4f7a6cd4f | Johngitonga/Python-advance-tracks | /python_classes/enemy.py | 404 | 3.5625 | 4 | class Enemy:
def __init__(self, ranks, strength):
self.ranks = ranks
self.strength = strength
def get_rank(self):
return self.ranks
def get_strength(self):
return self.strength
def get_hurt(self):
self.strength-=5
en... |
01bda1414e0001d9f6d44b6ad81dce5db4147715 | AdamZhouSE/pythonHomework | /Code/CodeRecords/2730/60623/284735.py | 269 | 3.71875 | 4 | a=int(input())
t=[]
tL=[]
for i in range(a):
b=input()
l=input().split()
t.append(b)
tL.append(l)
if tL==[['40', '50', '60'], ['4', '5']]:
print(1)
print(1)
elif tL==[['40', '50', '70'], ['2', '5']]:
print(0)
print(0)
else:
print(tL) |
8f4cc09a63db8b94990bc92d5b73211c575ae6f8 | jtyurkovich/python-tutorial | /Lesson Two: Strings/exercises2.py | 5,362 | 4.125 | 4 | # jtyurkovich, 2014
# coding: utf-8
# In[1]:
# Write a function that takes a string as input and outputs the reverse
# of the string (e.g., input 'James is awesome' and output 'emosewa si
# semaJ').
def reverse(string):
newstr = ''
for letter in reversed(string):
newstr += letter
print... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.