blob_id stringlengths 40 40 | repo_name stringlengths 5 127 | path stringlengths 2 523 | length_bytes int64 22 545k | score float64 3.5 5.34 | int_score int64 4 5 | text stringlengths 22 545k |
|---|---|---|---|---|---|---|
cd96d65248913b4b3238fac25f462e53c463ad85 | Byhako/python | /scripts/metodos/interpolacion_newton.py | 1,423 | 4.03125 | 4 | print("------- Interpolacion Polinomica (Newton) -------")
n = int(input("Ingrese el grado del polinomio a evaluar: ")) + 1
matriz = [0.0] * n
for i in range(n):
matriz[i] = [0.0] * n
vector = [0.0] * n
print(matriz)
print(vector)
for i in range(n):
x = input("Ingrese el valor de x: ")
y = input("Ingrese el va... |
9075401f4a353f91e1fe7b65a115e3b82e4e83f0 | Byhako/python | /poo/morral.py | 491 | 3.71875 | 4 | def morral(size, pesos, valores, n):
if n == 0 or size ==0 :
return 0
if pesos[n-1] > size:
return morral(size, pesos, valores, n-1)
return max(valores[n-1]+morral(size-pesos[n-1], pesos, valores, n-1),
morral(size, pesos, valores, n-1))
if __name__ == "__mai... |
42498a2bff950906b9c2cbbd13c4c5cbf89fb327 | Byhako/python | /scripts/estimar_pi.py | 1,417 | 3.625 | 4 | import random
print('ESTIMAR PI EN UN CIRCULO UNIDAD')
print('')
#MUESTREO SIMPLE
n=0
m=10000
c=0
c1=0
while c<m:
c1=c1+1
x=random.random()
y=random.random()
if x**2+y**2<1:
n=n+1
else:
c=c+1
print('Muestreo simple = %3.4f' %(4*n/c1 ))
#MARKOV
n=0... |
37660afa5ef0d3c689e590713f622ba465bfd038 | glc12125/Algo | /lintcode/Time to flower tree.py | 1,827 | 3.796875 | 4 | '''
There is a tree of nn nodes with Num.00 to n-1n−1, where node 00 is the root node and the parent node of node ii is father[i]father[i]. Now to water the tree, sprinkle water on the root node, the water will flow down every edge, from the father of node ii to node ii costs time[i]time[i], how long will it take to fl... |
c8998af521723e52952d0cd1d0916d039a6ce736 | Jerome4914/for_loop_basicI | /for_loop_basicI.py | 550 | 3.65625 | 4 | #1
# for x in range(0, 151, 1):
# print(x)
#2
# for x in range(0, 1001, 5):
# print(x)
#3
# for x in range(0, 101, 1):
# if (x) % 5 == 0:
# print("Coding")
# else:
# print(x)
# if (x) % 10 == 0:
# print("Coding Dojo")
#4
# sum=0
# for x in range(1, 5000, 2):
# if (x) %... |
7d87a377afbf254405c33b1ed03cac858144bca9 | shivarajmishra/jupyter-book-demo | /_build/jupyter_execute/basics1.py | 23,480 | 3.953125 | 4 | # Python Basics I
<img align="left" src="https://ithaka-labs.s3.amazonaws.com/static-files/images/tdm/tdmdocs/CC_BY.png"><br />
Created by [Nathan Kelber](http://nkelber.com) and Ted Lawless for [JSTOR Labs](https://labs.jstor.org/) under [Creative Commons CC BY License](https://creativecommons.org/licenses/by/4.0/)<... |
7de7efb40b5db9a3e34dccd9b3e106e6f159dfff | vamshi99k/python-programs | /stringvalidators.py | 267 | 3.65625 | 4 | s=input()
res=['False','False','False','False','False']
for i in s:
if i.isalnum():
res[0]='True'
if i.isalpha():
res[1]='True'
if i.isdigit():
res[2]='True'
if i.islower():
res[3]='True'
if i.isupper():
res[4]='True'
print(*res, sep='\n') |
5ae6d412a388802c9b4811d8d4a209ce5925b80d | vamshi99k/python-programs | /count_letters_digits - Copy.py | 307 | 3.9375 | 4 | def count_letters_digits(sentence):
letter_count=0
digit_count=0
for letter in sentence:
if letter.isdigit():
digit_count+=1
if letter.isalpha():
letter_count+=1
result=[letter_count,digit_count]
return result
sentence='hi bro how are 9999'
print(count_letters_digits(sentence))
|
a7b8d7ba2901fd0417800f51e4f9f81af05f21ad | SeonMoon-Lee/pythonStudy | /dict_comprehension.py | 597 | 3.828125 | 4 | '''
dictonary comprehension
딕셔너리를 생성과 동시에 값을 할당하는 문법
dict = { 키:값 for 키,값 in 반복돌릴것}
'''
students = ["태연","진우","정현","하늘","성진"]
for number , name in enumerate(students):
print ("{}번의 이름은 {}입니다.".format(number,name))
students_dict = {"{}번".format(number+1): name for number, name in enumerate(students)}
print(stu... |
aaabeeca1e8964ce74aa230c70a085f97bb74c15 | SeonMoon-Lee/pythonStudy | /raise.py | 778 | 3.765625 | 4 | def rsp(mine,yours):
allowed = ["가위","바위","보"]
if mine not in allowed:
raise ValueError
if yours not in allowed:
raise ValueError
#가위바위보 승패를 판단하는 코드
try:
rsp('가위','바')
except ValueError:
print("잘못된 값을 입력한 것 같습니다")
school = {"1반":[172,185,198,177,165,199], "2반":[165,... |
5cd17480ee4a097b2d437e305ffddadab596d7ea | SeonMoon-Lee/pythonStudy | /class_method.py | 1,040 | 3.625 | 4 | '''
메소드 : 클래스 내부 함수
특수 메소드
__init__() : 인스턴스를 만들 때 실행되는 함수 (생성자)
__str__() : 인스턴스 자체를 출력할 때의 문자열 형식을 지정해 주는 함수
'''
class Human():
'''인간'''
def __init__(self,name,weight):
#초기화 함수
print("__init_실행")
print("이름은 {},몸무게는 {}".format(name,weight))
self.name = name
self.weight ... |
97b2a81aaf57fb021ca6b2c49b7bc925d98ba193 | SeonMoon-Lee/pythonStudy | /class.py | 1,049 | 4.25 | 4 | class Human():
'''인간'''
#person = Human()
#person.name = '철수'
#person.weight = 60.5
def create_human(name,weight):
person = Human()
person.name = name
person.weight = weight
return person
Human.create = create_human
person = Human.create("철수",60.5)
def eat(person):
person.weight+=0.1
pri... |
4c3e7cbbf2e78c3734ee56147a9c83ab33ffa5c5 | Gaminhbirol/BEDU_Python | /Reto_01.2.py | 322 | 4.03125 | 4 |
alumnos = ['Diego', 'Paco', 'Ricky', 'Barbara', 'Canelo']
alumnos.sort()
print('En esta clase de Python los alumnos son: ', alumnos)
nuevo_alum = 'Perengano'
print('El nuevo alumno es: ', nuevo_alum)
alumnos.append(nuevo_alum)
print('Total de alumnos: ', alumnos)
alumnos.sort()
print('Alumnos ordenados: ', alumnos... |
6d65f634ae17e8ea902799358a0b1fa4b1436219 | parthdoshi/seniordesign | /src/line-db-maker/scrubber.py | 1,983 | 3.5625 | 4 | #! /usr/bin/env/python3
"""
map.py accesses the SEPTA website and outputs
an xml file containing in an xml file containing a list
of station elements with name and url subelements.
The output file is called "results.xml"
usage: $ python map.py
"""
import xml.etree.ElementTree as ET
import urllib.request
import re
... |
143523ac0974d17f3644fa70676956a5f7ae3c1b | Granteur/50_States | /main.py | 1,675 | 3.875 | 4 | import turtle
import pandas
BACKGROUND = "blank_states_img.gif"
screen = turtle.Screen()
#gives game a title
screen.title("United States Game")
#sets the background
screen.bgpic(BACKGROUND)
#Alternative way of setting the background
"""screen.addshape(BACKGROUND)
turtle.shape(BACKGROUND)"""
data = pandas.read_... |
69a27f23c239060d45714fe27813cbb18a502dbb | kmanc/cryptopals | /cryptopals/attacks/aes.py | 397 | 3.609375 | 4 | def detect_ecb(input_bytes: bytes):
"""Takes in a byte string. Determines whether or not it is likely to be an AEC-ECB-encrypted ciphertext"""
number_original_chunks = len(input_bytes) // 16
dedupe_chunks = {input_bytes[i: i + 16] for i in range(0, len(input_bytes), 16)}
result = False
if len(dedup... |
15450e86511ccb6b4ba180ed0966b35a9a86ce7c | Arpita2327/regresspy | /test/model.py | 584 | 3.5 | 4 | from numpy.lib.npyio import load
import numpy as np
from sklearn.linear_model import SGDRegressor
from sklearn.datasets import load_iris
from regresspy.regression import Regression
from regresspy.loss import rmse
iris = load_iris()
# We will use sepal length to predict sepal width
X = iris.data[:, 0].reshape(-1, 1)
... |
b4b769475ec048c52b79b49130f7c798ed2c5d1f | InertiaElectric-IE/InertiaElectric-IE.github.io | /InertiaElectric/TestRun.py | 140 | 3.578125 | 4 | firstname = input("Print First Name Here: ")
Lastname = input( "Print Last Name Here: ")
print("Your full name is ", firstname, Lastname)
|
34c606463f5d699e2b44b6d27b0c2263f9a8928f | Tydroneous/Rock-Paper-Scissors | /Problems/Letter-spacing/task.py | 68 | 3.578125 | 4 | word = list(input())
num = int(input())
print(*word, sep=' ' * num)
|
0c324fda23710ad69fa3f42bb6096d681a238b13 | 1160287301/python_study | /坑/test2.py | 890 | 3.859375 | 4 | # -*- coding:utf-8 -*-
import operator
#-----------------------------------------------------------------------------------
# print(operator.sub(1, 2))
#-----------------------------------------------------------------------------------
# from collections import namedtuple
# Employee = namedtuple('Employee', 'name,... |
8c1a7803c34d24734ea3bb858fa60796ed378b34 | 1160287301/python_study | /高级编程/多线程/python_thread.py | 1,123 | 3.65625 | 4 | # -*- coding:utf-8 -*-
# 对于io操作来说, 多进程和多线程性能差别不大
# 1.通过thread类实例化
import time
import threading
def get_detail_html(url):
print("get detail html started")
time.sleep(2)
print("get detail html end")
def get_detail_url(url):
print("get detail url started")
time.sleep(2)
print("get detail url e... |
b790ee0d7bd99110f1f9bd16abf428a85529e7b1 | 1160287301/python_study | /高级编程/自定义序列类/bisect_test.py | 545 | 3.671875 | 4 | # -*- coding:utf-8 -*-
import bisect
# 用来处理已排序的序列,用来维持已排序的序列,升序
# 二分查找
inter_list = []
bisect.insort(inter_list, 3)
bisect.insort(inter_list, 1)
bisect.insort(inter_list, 2)
bisect.insort(inter_list, 4)
bisect.insort(inter_list, 6)
bisect.insort(inter_list, 7)
bisect.insort(inter_list, 5)
print(inter_list) # [1, 2, ... |
0ed7f1501241934e31b9c17722c6c24d842edeb9 | anirudhkm/data-mining-course | /hw3/3/frequent.py | 1,302 | 3.875 | 4 | from collections import OrderedDict
def maximal_freq_itemsets(freq_item_dict):
"""
This function helps to find the maximal
frequent items in the dataset and returns
them as a sequence.
"""
maximal_freq_count = 0
# initial value
for i in freq_item_dict:
# iterate thr... |
a69b12f8e90567c48a6803fbe531bed77f413dbb | anirudhkm/data-mining-course | /hw3/3/sets.py | 471 | 3.640625 | 4 | import numpy as np
def intersection(*args):
"""
This function performs the
intersection operation for the input data
given and returns them as a numpy array
"""
return tuple(sorted(set(args[0]).intersection(*args[1:])))
def union(*args):
"""
This function performs the uni... |
32ec075565ae8d7304f540db2a9fc5bfda0d6ef6 | anirudhkm/data-mining-course | /hw1/5/5_b/recommender_system.py | 3,783 | 3.578125 | 4 | """
Name: Anirudh Kamalapuram Muralidhar
Indiana University
Date: 31th January, 2016
Objective: To build a recommender system
"""
from distance import *
from data_process import *
import numpy as np
def find_top_k_sim_users(similarity_list, k):
"""
This function returns the top "k" most
similar use... |
1841100ecfd18b421ab148333f47575c33f5e02c | s19009/python | /kansuu/fail3.py | 91 | 3.5 | 4 | def f(a, b, c=3, d=2, e=4):
return a + b + c * d - e
result = f(5, 3)
print(result)
|
fdf4ed2891138253932f361aa9e18a820b53f4d2 | DjavidHesenov/Bank-ATM-CRUD-system | /admin/admin.py | 334 | 3.546875 | 4 | def control():
username = input("Username: ").lower()
password = input("Password: ").lower()
if username == "admin":
if password == "admin":
print("Success")
else:
print("Password Sehvdir")
control()
else:
print("Username Sehvdir")
con... |
894323730ff8fa9a603ad4d284178d9011af7790 | mariafoo/COMP1730_assignment2 | /assign2_u5021276.py | 9,463 | 4.03125 | 4 | ## u5021276
## Implementing this function is task 1:
def read_graph_from_file(filename):
'''This function reads a graph from a file and returns a tuple of
two lists: (neighbours, positions): neighbours is the neighbour
list representation of the graph; positions is the list of node
positions (this is u... |
38037db7be034fbf05d6392ee36b1dd9c33f795d | Mamithi/open-katis-challenges | /carrots.py | 83 | 3.5625 | 4 | x, y = input().split()
x = int(x)
for i in range(x):
desc = input()
print(y)
|
c3efa20414a7e147b9ad5c50cd56ab9cbecb2496 | Mamithi/open-katis-challenges | /kemija.py | 237 | 3.75 | 4 | encoded = input()
decoded = ''
vowels = ['a', 'e', 'i', 'o', 'u']
count = 0
while count < len(encoded):
decoded += encoded[count]
if encoded[count] in vowels:
count += 3
else:
count += 1
print(decoded)
|
8c06cb688c09a2c340f34586b54b1b39c682e008 | Mamithi/open-katis-challenges | /nodup.py | 156 | 3.671875 | 4 | words = input().split()
duplicates = [x for i, x in enumerate(words) if x in words[:i]]
if len(duplicates) > 0:
print('no')
else:
print('yes')
|
89c01a8e28117e7b921e01a672f3ce45e39baf27 | Mamithi/open-katis-challenges | /avion.py | 210 | 3.59375 | 4 | found_at = []
for i in range(5):
blimp = input()
if 'FBI' in blimp:
found_at.append(i+1)
if len(found_at) < 1:
print('HE GOT AWAY!')
else:
print(' '.join([str(x) for x in found_at]) ) |
a7390a0db2829dce65dd83ed11733f7dddc8aa22 | MaxDiMassimo/final401 | /smoking classifier.py | 4,179 | 3.515625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Thu May 13 21:57:52 2021
@author: 19145
"""
#drinking classifier
# Importing the libraries
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
# Importing the dataset
dataset = pd.read_csv('final project - smoking ready.csv')
X = dataset.iloc[:... |
5a5bb8dcac7f140f2c84efd8c5419da858cf54d0 | bazzscript/SputnikLab | /VulnPortScanner/vulnportscanner.py | 1,512 | 3.546875 | 4 | import portscanner
targets_ip = input('[~] Enter Target(s) To Scan (Split Multiple Targets with comma(,)): ')
while True:
try:
port_number = int(Input('[~] Enter Amount of Ports you want to Scan(500 means first 500 ports) : '))
break
except ValueError:
print(' We dont understand what y... |
da9a3fc22cfc7f56769188bd64a2586e5249e9e7 | scausey/matzobot | /scrape.py | 3,216 | 3.59375 | 4 | from urllib.request import urlopen
from urllib.error import HTTPError
from bs4 import BeautifulSoup
import requests
from collections import defaultdict
import pprint
# TODO: Check for errors when loading php.
url = "https://www.smith.edu/diningservices/menu_poc/cbord_menus.php"
response = requests.get(url)
bsObj = Be... |
d5d73cfa1635c255ea26e4b49ad71e72951c27f5 | wavestoweather/enstools-compression | /enstools/compression/emulators/emulator_class.py | 1,176 | 3.71875 | 4 | """
Abstract class which defines the methods that the emulators need to have.
"""
from abc import ABC, abstractmethod
import numpy as np
from enstools.encoding.api import Encoding
class Emulator(ABC):
"""
This class provides an emulator.
The emulator is initialized with a compression specification (compr... |
aa815e48fda770f3d33d50265dd9ce5d87028d1a | wavestoweather/enstools-compression | /enstools/compression/slicing.py | 8,244 | 4.09375 | 4 | """
This file contains classes and methods to divide a multi dimensional slice in different parts, via selecting a
chunk size or the number of desired parts.
"""
import logging
from typing import List, Tuple
from itertools import product
import numpy as np
def split_array(array: np.ndarray, parts: int):
"""
... |
78af189107537a996ae22edb3cf39d27d775a219 | wesenu/LearnOpenSource | /Kshitij/Coffee Machine/coffee machine/mainwithoutfunctions.py | 5,803 | 4.1875 | 4 | MENU = {
"espresso": {
"ingredients": {
"water": 50,
"coffee": 18,
},
"cost": 1.5,
},
"latte": {
"ingredients": {
"water": 200,
"milk": 150,
"coffee": 24,
},
"cost": 2.5,
},
"cappuccino": {
... |
bbfe0baa969fee9ac2d8dae86345bd3b9ecb6a7d | JohnStevensonWSU/Ranking | /IndexList.py | 3,855 | 4.09375 | 4 | import IndexNode
# indexList is a linked list representing a term index
# for a document corpus.
class indexList(object):
# Constructor creates an indexList whose
# head points to an indexNode for the
# given term.
def __init__(self):
self.head = None
# Adds a term/docID tuple to the ... |
0964f1d92b02db0e9f25664c7049d657c3be4549 | yy02/test | /Python/Python学习笔记/字符串操作.py | 703 | 4.15625 | 4 | str = 'hello world'
# 转换大小写
# print(str.lower())
# print(str.upper())
# 切片操作
# slice[start:end:step] 左闭右开原则,start < value < end
# print(str[2:5])
# print(str[2:])
# print(str[:5])
# print(str[::-1])
# 共有方法
# 相加操作,对字符串列表和元组都可以使用
strA = '人生苦短'
strB = '我用Python'
listA = list(range(10))
listB = list(range(11,20))
# ... |
4e0ce47617641b67aec51055403941a1862ef175 | Tharunsai-0512/Coursera | /Assignments/Python-Data-Structures/assignment7_2.py | 547 | 3.5 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sat Dec 7 18:57:44 2019
@author: VIGNESHWAR REDDY
"""
# Use the file name mbox-short.txt as the file name
count = 0
addOfValues = 0
fname = input("Enter file name: ")
fh = open(fname)
for line in fh:
if line.startswith("X-DSPAM-Confidence:") :
colon = line.find(':')... |
64ba459b0b322274f900e1716496e7643d90bde1 | shermansjliu/Python-Projects | /Ceasar Cipher/Ceaser Cipher.py | 1,888 | 4.21875 | 4 | def ReturnEncryptedString():
code = input("Enter in the code you would like to encrypt")
code = code.upper()
newString = ""
tempArr = list(code)
for oldChar in tempArr:
newString += EncryptKey(oldChar)
print(newString)
def ReturnDecryptedString():
code = input("Enter in the code you ... |
5d9e6975568ece0a55a827ba8b30080307b4ae86 | YiLisa/DSCI560-hw2 | /visualization.py | 405 | 3.546875 | 4 | import matplotlib.pyplot as plt
import pandas as pd
def main():
input = pd.read_csv('random_x.csv', header=None)
x = input[0].tolist()
output = pd.read_csv('output_y.csv', header=None)
y=output[0].tolist()
plt.plot(x, y)
plt.grid(True)
plt.title('y = 3x + 6')
plt.savefig('plot_x_y.png')... |
874a49dc92c5a328f4d728a2b93f85782a39668d | sweeeeeet/python | /lesson2-function.py | 1,134 | 3.921875 | 4 | #定义函数
def add(x,y):
#函数体
ret=x+y
return ret
#函数调用
ret=add(2,4)
print(ret)
#在定义函数时赋值默认参数
def mius(x,y=0):
return x-y
print(mius(4))
#一个函数可以返回多个值
def get_point():
x=10
y=20
return x,y
#解包 unpack
x,y=get_point()
print(x,y)
#高阶函数:在参数中允许传入函数
def addPlus(x,y,f):
return f(x)+f(y)
print(a... |
364bfdd2cd3357abc93bc6762dbcf25b8b72588b | EddyCSE/CSE | /Eduardo Sanchez - Game - Backup.py | 16,464 | 3.59375 | 4 | class Item(object):
def __init__(self, name):
self.name = name
class Player(object):
def __init__(self, starting_location, health, shield, name, weapon):
self.name = name
self.current_location = starting_location
self.inventory = []
self.health = health
self.shi... |
f71d4c4e64b7ec540c4342520303b95f1fc29579 | EddyCSE/CSE | /notes/hello world.py | 5,109 | 4.3125 | 4 | import random
print("hello world")
# This is a comment. This has no effect on the code
# but this does allow me to do things. I can:
# 1. Make notes to myself.
# 2. Comment pieces of code that do not work.
# 3. Make by my code easier to read.
print("Look at what happens here. Is there any space?")
print()
print()
pri... |
b6dae1eb5340cbd79237c3184ec88987643499c1 | EddyCSE/CSE | /notes/Eduardo Sanchez - Hangman.py | 1,689 | 4 | 4 | import random
import string
AllLetters = string.ascii_letters
words = ["thigh", "computer", "mouse", "chair", "shirt", "o'clock", "concatenation", "pajama", "soccer", "sweater",
"goldfish", "human", "haphazard", "wildebeest", "pixel", "Wiebe"]
guesses = 6
output = []
randword = (random.choice(words))
wordlis... |
0561cf0ce7ea015818af70852c72a91afb105c59 | kenpos/LearnPython | /正規表現とか色々/BigSmallMatch.py | 606 | 3.625 | 4 | #大文字,小文字を無視したマッチング
#compileオプション「re.I」をつける
import re
#1つ以上の数字の次に空白文字があり,一つ以上文字,数字,下線
robocop_regex = re.compile(r'RoboCop',re.I)
mo = robocop_regex.search('RoboCop is part man,part machine,all cop.').group()
print(mo)
#検索し,パターンマッチした奴を全部抽出する
mo1 = robocop_regex.search('ROBOCOP is part man,part machine,all cop.').group... |
74d738e09d72eb4d08091a3a18b68929de0baa5e | rbetik12/ai-lab2 | /astar_search.py | 2,041 | 3.515625 | 4 | from cities import cities
from distances import distances
from greedy_search import Node
class ANode(Node):
def __init__(self, name, parent):
super().__init__(name, parent)
self.h = 0
self.g = 0
self.f = 0
def __str__(self):
if self.parent:
return "Name: " ... |
68dc5c4931436e5b83c619401a48beefc9b69088 | davidvargaspuga/CurbsideRecycling | /blob_detection.py | 500 | 3.546875 | 4 | import cv2
import numpy as np
# Read in an image in grayscale
img = cv2.imread('updated_300.png', cv2.IMREAD_GRAYSCALE)
detector = cv2.SimpleBlobDetector_create()
# Detects the blobs in the image
keypoints = detector.detect(img)
# Draw detected keypoints as red circles
imgKeyPoints = cv2.drawKeypoints(img, keypoint... |
48def1c3190fb8e4463f68dd478055621b12e4b6 | yooshxyz/ITP | /Feb19.py | 1,702 | 4.125 | 4 | import random
# answer = answer.strip()[0].lower()
def main():
while True:
user_choice_input = int(input("What Function do you want to Use?\nPlease type 1 for the No vowels function, type 2 for the random vowels function, and 3 for the even or odd calculator.\n"))
if user_choice_input == 1:
... |
38dfab114e3fb05038bbef3e959c7da0de87b1c2 | yooshxyz/ITP | /fileIO.py | 864 | 3.859375 | 4 | import random
nouns_file = open("nouns.txt")
# names = open()
adj_file = open("adj.txt")
# print(nouns_file)
# for line in nouns_file:
# word = line.strip()
# nouns.append(word)
nouns = [line.strip() for line in nouns_file if line.strip()!=""]
adjectives = [line.strip() for line in adj_file if line.stri... |
ecf358b69a9eccda46fe310e7989346fb7001be2 | BelongtoU/nguyentienanh-labs-C4E26 | /lab2/homework/5_te.py | 210 | 3.578125 | 4 | from turtle import*
def draw_star (x, y, lenght):
penup()
setpos(x, y)
pendown()
left(144)
forward(lenght)
for _ in range(4):
right(144)
forward(lenght)
mainloop() |
fe1f445c91e1949579163cd0545c019966d83095 | BelongtoU/nguyentienanh-labs-C4E26 | /lab2/homework/6_te.py | 405 | 3.90625 | 4 | from turtle import*
def draw_star (x, y, lenght):
penup()
setpos(x, y)
pendown()
left(144)
forward(lenght)
for _ in range(4):
right(144)
forward(lenght)
speed(0)
color('blue')
for i in range(100):
import random
x = random.randint(-300, 300)
y = random.randint(-3... |
e01def81ca1637d220670aae48dae515193b743f | Saptarshi-prog/LeetCode-problems-code | /3. Longest Substring.py | 280 | 3.5625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Mon Sep 7 22:46:33 2020
@author: 91842
"""
s = input()
m = 0
d = []
for char in s:
if char in d:
d = d[d.index(char)+1:]
d.append(char)
print(d)
m = max(m, len(d))
print(m) |
a09d239c09374761d9c78ae4cfd872eec416a71c | NishadKumar/leetcode-30-day-challenge | /construct-bst-preorder-traversal.py | 1,585 | 4.15625 | 4 | # Return the root node of a binary search tree that matches the given preorder traversal.
# (Recall that a binary search tree is a binary tree where for every node, any descendant of node.left has a value < node.val, and any descendant of node.right has a value > node.val. Also recall that a preorder traversal displa... |
12ce47dd742dc5e152b21eb815a5bf33e6436a41 | NishadKumar/leetcode-30-day-challenge | /binary-tree-valid-sequence.py | 1,200 | 4.03125 | 4 | # Given a binary tree where each path going from the root to any leaf form a valid sequence, check if a given string is a valid sequence in such binary tree.
# We get the given string from the concatenation of an array of integers arr and the concatenation of all values of the nodes along a path results in a sequence... |
02b3cdcf689007b5cf1224ab3cb87d30a0dfadcc | DarynaZlochevska/Practic | /1 день/1.py | 627 | 3.96875 | 4 | import datetime
def printTimeStamp(name):
print('Автор програми: ' + name)
print('Час компіляції: ' + str(datetime.datetime.now()))
a = float(input("Введіть об'єм вашого контейнера: "))
b = int(input("Введіть кількість ваших контейнерів: "))
if a < 1:
c = b * 0.10
template = '{:.' + str(2) + 'f}'... |
af95e3682c89276ddc707bed79e14ee7e36a1add | DarynaZlochevska/Practic | /3 день/12.py | 380 | 3.5625 | 4 | import datetime
def printTimeStamp(name):
print('Автор програми: ' + name)
print('Час компіляції: ' + str(datetime.datetime.now()))
def GCD(a, b):
if a == b:
return a
elif a > b:
return GCD(a - b, b)
elif a < b:
return GCD(a, b - a)
print(GCD(500, 150))
... |
b1d83a286acfa0d779945d7ab5f0cfbb608f735e | nandanabhishek/C-programs | /Checking Even or Odd/even_odd.py | 249 | 4.21875 | 4 | a = int(input(" Enter any number to check whether it is even or odd : "))
if (a%2 == 0) :
print(a, "is Even !")
# this syntax inside print statement, automatically adds a space between data separated by comma
else :
print(a, "is Odd !")
|
652167ca3f075156a408e474ba047a8d204b093f | Atifmoin19/Sig-Python | /Module 2/q2.py | 437 | 3.921875 | 4 | print("Atif moin\n")
print("1900300100051\n")
print("Q.2=>Write a Python program to check a triangle is equilateral, isosceles or scalene.\n")
s1=int(input('length of side 1 : '))
s2=int(input('length of side 2 : '))
s3=int(input('length of side 3 : '))
if s1==s2==s3:
print(' This is Equiletral triangle\n')
el... |
6041b3112f596d67d1e95eca6953cbfe698be278 | Atifmoin19/Sig-Python | /Module 5/question2.py | 487 | 3.921875 | 4 | print("Atif Moin")
print("19003000100051")
list1=[]
list2=[]
n=int(input('Enter Number of element in list : '))
for i in range(0,n):
ele=str(input('Enter element : '))
list1.append(ele)
print("List name is : ",list1)
for j in range(0,n):
list2.append(len(list1[j]))
print("List length is : ",list2)
maxim... |
a4ba4a598a77283a303e5cbc97fec434ff007df0 | ankuagar/leetcode | /pythoncode/all_rectangles_2d_array.py | 4,767 | 4.15625 | 4 | #!/usr/bin/env python3
"""
Imagine we have an image. We'll represent this image as a simple 2D array where every pixel is a 1 or a 0.
The image you get is known to have potentially many distinct rectangles of 0s on a background of 1's. Write a function that takes in the image and returns the coordinates of all the 0 ... |
9f790dbf9f80207fe4c8e5102ef0e5a862b72819 | ankuagar/leetcode | /pythoncode/heap.py | 4,271 | 4.03125 | 4 | #!/usr/bin/env python3
import unittest
class Heap(object):
'''
Min Heap. Every root node is <= child nodes
Uses 1 based indexing
'''
def __init__(self, capacity):
self.capacity = capacity
self.arr = []
def size(self):
return len(self.arr)
def push(self, ele):
... |
3507349ce69a165ef1b4165843a3ba72e09e4a12 | Rishab-kulkarni/caesar-cipher | /caesar_cipher.py | 1,861 | 4.40625 | 4 | import string
# Enter only alphabets
input_text = input("Enter text to encrypt:").lower()
shift_value = int(input("Enter a shift value:"))
alphabet = string.ascii_lowercase
alphabet = list(alphabet)
def encrypt(input_text,shift_value):
"""
Shifts all the characters present in the input text b... |
ebe5f04f9ae3e7572d6595ea85caeb0833cfa352 | Sipoufo/Python_realisation | /Ex-5/high_score.py | 329 | 3.84375 | 4 | student_score = input("Input a list of student score\n").split()
high_score = 0
for n in range(0, len(student_score)):
student_score[n] = int(student_score[n])
print(student_score)
for score in student_score:
if score > high_score:
high_score = score
print(f"The highest score in the class is : {high... |
0e8366c415dd5b7ba4812b30d1a97dd5b4bf7763 | Sipoufo/Python_realisation | /Ex-12/guess_number.py | 1,389 | 4.125 | 4 | from art import logo
import random
print("Welcome to the Number Guessing Game")
# init
live = 0
run = True
# function
def add_live(difficulty):
if difficulty.lower() == 'easy':
return 10
elif difficulty.lower() == 'hard':
return 5
def compare(user, rand):
if user < rand:
print("... |
91c61dec3ac0cac535dabcc6f543bd1f95fb4955 | ingdanielmichel/estudio0todatascientist | /prueba.py | 420 | 3.859375 | 4 | def complejidad(lista):
for x in lista:
if x == 33:
print('Esto es lo que buscamos!')
return(x)
print('No esta lo que buscamos')
def simplicidad(lista):
if len(lista)>0:
print('Tenemos datos!')
return
print('No tenemos datos!')
return
... |
eefef27fae7d18c378b4abfec6d3c543209a04e4 | Kevnien/Lambda-Technical | /Search in Sorted Matrix/solution.py | 731 | 3.734375 | 4 | def search_in_sorted_matrix(matrix, target):
row = 0
col = len(matrix[0]) - 1
while col >= 0 and row < len(matrix):
if matrix[row][col] > target:
col -= 1
elif matrix[row][col] < target:
row += 1
else:
return [row, col]
return [-1, -1]
matrix = [
[1, 4, 7, 12, 15, 997, 999],
... |
fc3b3ba9561dd23a4ec7442043683b28aab0e31f | RulasLalo/HackerRank | /Python3/FRUPS.py | 276 | 3.875 | 4 | #Find the Runner-Up Score! program
n=int(input())
lista=[]
unico=[]
datos=input()
lista= [int(d) for d in datos.split()]
lista.sort()
for i in lista:
if i not in unico:
unico.append(i)
#print(unico)
unico[-2:-1]
for i in unico[-2:-1]:
print(i)
|
f55819c8e653d6b4d94ad5f74cffd6a8121ddda2 | cmparlettpelleriti/CPSC230ParlettPelleriti | /Lectures/Dictionaries_23.py | 2,317 | 4.375 | 4 | # in with dictionaries
grades = {"John": 97.6,
"Randall": 80.45,
"Kim": 67.5,
"Linda": 50.2,
"Sarah": 99.2}
## check if the student is in there
name = input("Who's grade do you want? ")
print(name in grades)
## if not there, add them
name = input("Who's grade do you want? ").capitalize()
if name in grades:
prin... |
ad45fe4fddbfc734955ab84e434975e7bea7aa6d | cmparlettpelleriti/CPSC230ParlettPelleriti | /Lectures/Conditionals_6_BLANK.py | 452 | 4.0625 | 4 | # if elif else
# baggage check
# bank rewards
# and or
# friends
# maybe you're not so picky....
# and/or with comparisons
# conditional expressions
# name check
name = "Chelsea"
if name == "Chelsea":
print("You're the professor.")
else:
print("You're a student.")
# Daniel Craig
day = "Sunday... |
9aba99649efeda7100d760f8464fe9697075d923 | cmparlettpelleriti/CPSC230ParlettPelleriti | /Classwork/Conditionals_6.py | 3,573 | 4.375 | 4 | # Class Activities + Review (Class 6)
# Together------------------------------------------------
# 0. Questions?
# 1. If/Elif/Else
# 2. And/Or
# 3. Conditional Expressions
# Classwork-----------------------------------------------
'''
1. Help me figure out where to go on campus! On MW I tech in Keck.
On TTh I teach ... |
a47c6e062100a927376d78bb6a292fe8b76b3e4c | cmparlettpelleriti/CPSC230ParlettPelleriti | /Lectures/Dictionaries_23_BLANK.py | 707 | 3.796875 | 4 | # in with dictionaries
grades = {"John": 97.6,
"Randall": 80.45,
"Kim": 67.5,
"Linda": 50.2,
"Sarah": 99.2}
## check if the student is in there
## if not there, add them
# sets
# creating sets
## can't put mutable objects inside a set
## but you can mix types
# set methods
## union, intersection, differe... |
d56bfae8d6f3ed3c39ce1464c95c056f8c31d4ac | cmparlettpelleriti/CPSC230ParlettPelleriti | /Classwork/ListsAndTuples_16.py | 4,496 | 4.125 | 4 | # Class Activities + Review (Class 16)
# Together------------------------------------------------
# 0. Questions?
# 1. modifying vs. nonmodifying
'''
Modify your bridge_crosser() function *again* (from the last classwork),
so that it returns a list with two things:
at index 0, it returns the # of successful steps,
... |
998e19b6bd3fd6f73471a13fd3e08a177c499e5e | cmparlettpelleriti/CPSC230ParlettPelleriti | /Classwork/Dictionaries_24.py | 3,697 | 4.21875 | 4 | # Class Activities + Review (Class 24)
# Together------------------------------------------------
# 0. Questions?
# 1. dicts are mutable like lists, what does that mean about changing it in a function?
'''
1. Using the Book dictionary below, write the following functions that do things
with the Book dictionary.
- ... |
5ace467fb1083c7a5a15a0fab41026c737172902 | taiharry108/captcha_recognition | /captcha_generation.py | 3,197 | 3.5 | 4 | from captcha.image import ImageCaptcha
from shutil import copyfile
from os.path import join
import numpy as np
import os
from config import CAP_LEN, CHARACTERS, RESULT_FILE_NAME, NO_TRAIN_CAP, NO_TEST_CAP, DES_PATH, OUT_FILENAME
from collections import defaultdict
import pandas as pd
def gen_str(size, characters):
... |
13a40128d38fc83d7494f692c61bf7f8a1935269 | luisfmgoncalves/adventOfCode2020 | /day5/day5.py | 982 | 3.65625 | 4 | import math
def read_input():
file = open('input.txt')
puzzle_input = [line.strip() for line in file]
file.close()
return puzzle_input
def interval(tuple, char):
lower, upper = tuple[0], tuple[1]
middle = (upper - lower) / 2
b = math.floor(upper - middle) if char == 'F' or char == 'L' el... |
788b81702a0cafc6a44fcc011447d30f84178680 | luisfmgoncalves/adventOfCode2020 | /day12/day12.py | 3,675 | 3.5625 | 4 | def read_input():
file = open('input.txt')
puzzle_input = [line.replace('\n', '') for line in file]
file.close()
return puzzle_input
NORTH_RIGHT = {90: 'E', 180: 'S', 270: 'W'}
NORTH_LEFT = {90: 'W', 180: 'S', 270: 'E'}
EAST_RIGHT = {90: 'S', 180: 'W', 270: 'N'}
EAST_LEFT = {90: 'N', 180: 'W', 270: 'S... |
11f9cd49d79abaa09b7a02d18e06af81a20332ff | Muthupriya20/LetsUpgrade_pythonEssentials_B7_assignment | /B7_day8_assignment.py | 745 | 3.828125 | 4 | #!/usr/bin/env python
# coding: utf-8
# # Question 1
# In[5]:
def getinput(arg_func):
def wrap_function():
x=int(input("enter:"))
arg_func(x)
return wrap_function
# In[ ]:
@getinput
def fibo(n):
if n<=1:
return n
else:
return(fibo(n-1)+fibo(n-2))
nterms=int(input(... |
1afd54bded4dc958e33ae0484aceaaa7658d8a1b | CosmoAndrade/Fic-programador_web | /Hospitalar em Python/hospital.py | 1,685 | 3.828125 | 4 | import sqlite3
from sqlite3 import Error
class Hospital:
def __init__(self,nome,tipo,especialidade,avaliacao):
self.nome = nome
self.tipo = tipo
self.especialidade = especialidade
self.avaliacao = avaliacao
def inserir(self):
try:
conec... |
34f595312e5ea7350c60fbffc54a1690a35fa8d1 | LuisFros/AdvancedProgramming | /Tareas/T02/estructuras.py | 6,449 | 3.703125 | 4 |
class Nodo:
def __init__(self, valor=None):
self.siguiente = None
self.valor = valor
class ListaLigada:
def __init__(self, *args):
self.cola = None
self.cabeza = None
for arg in args:
self.append(arg)
def __len__(self):
largo = 0
... |
781947d55ede62f31a47dc2a4c17cd7eef4007db | EduardoHenSil/testes_python3 | /iteraveis/itertools/accumulate.py | 650 | 4.28125 | 4 | #!/usr/bin/python3
# coding: utf-8
import itertools
import operator
summary = """
itertools.accumulate(it, [func])
Produz somas accumuladas; se func for especificada, entrega o resultado da sua aplicação
ao primeiro par de itens de it, em seguida ao primeiro resultado e o próximo item.
Diferente da função functools.r... |
eb8229ed52395f30d81fa3b7e0f36889fee37f65 | srvendrix/hangman | /triangle.py | 239 | 3.71875 | 4 | class Triangle():
def __init__(self, x, y):
self.teihen = x
self.height = y
def calculate_area(self):
return (self.teihen * self.height) / 2
a_triangle = Triangle(5, 8)
print(a_triangle.calculate_area())
|
9e49375a8250aefe77b9aeeb6a8093710a37f4e0 | shira19-meet/meet2017y1lab5 | /fun1.py | 190 | 3.75 | 4 |
def add_numbers(start, end):
c = 0
for number in range (start, end+1,2):
# print(number)
c = c+number
return(c)
answer1 = add_numbers(333 ,777)
print(answer1)
|
1aabb86c880a4bd196d00d4266b6df3533d748ad | adarshadrocks/pyhonActivities | /menubar.py | 2,152 | 3.5 | 4 | #!/usr/bin/python
import time
import os
import webbrowser
import urllib
option='''
press 1 : current date and time
press 2 : To create a file
press 3 : To create a directory
press 4 : To search on google
press 5 : logout your system
press 6 : Shutdown your os
press 7 : To check internet connection in your pc
press 8 : ... |
872311d701a810ead37b49cd9e37d62707fe6da9 | KR4705/algorithms | /palindrome_recursive.py | 241 | 3.71875 | 4 | # palindrome_recursive.py
from sys import argv
name , string = argv
def pal(arg):
if len(arg) == 1 or len(arg) == 0:
return True
elif arg[0] == arg[len(arg)-1]:
return pal(arg[1:len(arg)-1])
else: return False
print pal(string)
|
7a683f984c9fba0e0c3d2d53fa805e841d2d29dd | KR4705/algorithms | /routeFinder.py | 1,019 | 4.15625 | 4 | # need to implement a simple path finding game in python.
# import pprint
board = [[0]*7 for _ in range(7)]
def print_grid(grid):
for row in grid:
for e in row:
print e,
print
# print print_grid(board)
def set_goal(a,b):
board[a][b] = "g"
# set_goal(3,3)
# print print_grid(board... |
5f9534bfd81e358312cf779081cd7d1fd49bd224 | tied/DevArtifacts | /master/Challenges-master/Challenges-master/level-1/fizzBuzz/fizz_buzz.py | 757 | 3.75 | 4 | import sys
def main(input_file):
with open(input_file, 'r') as data:
for line in data:
# convert str list to int and unpack to variables
x, y, n = map(int, line.split())
print fizzbuzz(x, y, n)
def fizzbuzz(x, y, n):
result = []
for i in xrange(1, n + 1):
... |
732af18e55deacb0c0d41224943a551a6831e2de | tied/DevArtifacts | /master/tic-tac-ai-master/tic-tac-ai-master/game.py | 8,882 | 4.125 | 4 | import random
class Player:
"""
Interface class for a player.
"""
printing = False # Whether the player will print its status updates
label = '?' # Will be set to either 'X' or 'O'
scores = [] # A list containing the score
def __init__(self, printing=False):
self.prin... |
5ee79511cb6aad16dbafe72606cbd2b3ad8f89c2 | tied/DevArtifacts | /master/python-snippets-master/python-snippets-master/excel-xlrd.py | 811 | 4 | 4 | # Demonstrates basic xlrd functions for working with Excel files
# (Excel 97-2003)
import xlrd
wb = xlrd.open_workbook('excel-xlrd-sample.xls')
# Print the sheet names
print wb.sheet_names()
# Get the first sheet either by index or by name
sh = wb.sheet_by_index(0)
# Iterate through rows, returning each as a list ... |
80e1db6dd3af955ea83c04f7bca48ab0f93709a9 | tied/DevArtifacts | /master/python-snippets-master/python-snippets-master/facebook-api-sqlite.py | 1,422 | 3.5625 | 4 | # Fetch Facebook page metrics via Social Graph API into a SQLite DB
# Grabs the number of likes and "talking about" numbers
import requests
import sqlite3
import os
from datetime import datetime
# These are the accounts for which you will fetch data
names_list = [
'fallingskies',
'usatoday'
]
# API base URL
... |
890e0daec877b2e427ade34f86cda7f57177d8d5 | isaacroldan/tuentiChallenge4 | /C01/C1.py | 715 | 3.53125 | 4 | ##########################################
#
# #TuentiChallenge4 (2014).
# Challenge 1 (https://contest.tuenti.net/Challenges?id=1)
# Isaac Roldan (@saky)
#
##########################################
import mmap
cases = int(raw_input(""))
for case in range(1,cases+1):
try:
data = raw_input("")
with open(... |
c629fcd473e694c884abc1fb68e7fde47b97f73b | willdoliver/BD1 | /01 - Modelos de dados e XML/ExercicioHerois.py | 5,325 | 3.515625 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
'''
#Usando ElementTree para trabalhar com arquivos XML
from xml.etree import ElementTree as et
conteudo = et.parse('campeonato.xml')
lista_equipes = conteudo.findall("equipe")
for equi in lista_equipes:
print ("Nome da equipe: ", equi.find("descricao").text)
'... |
39a97c3366248770fba81735c9c4e231b34077b9 | kuwarkapur/Robot-Automation-using-ROS_2021 | /week 1/assignement.py | 2,292 | 4.3125 | 4 | """Week I Assignment
Simulate the trajectory of a robot approximated using a unicycle model given the
following start states, dt, velocity commands and timesteps
State = (x, y, theta);
Velocity = (v, w)
1. Start=(0, 0, 0); dt=0.1; vel=(1, 0.5); timesteps: 25
2. Start=(0, 0, 1.57); dt=0.2; vel=(0.5, 1); timesteps... |
1dec745e6821aaf844d7af3d983f05bfaa0704f7 | NadavOrzech/DL_project | /source/proj-311549455_312168354/src/cs236781/train_results.py | 1,176 | 3.5 | 4 | from typing import NamedTuple, List
class BatchResult(NamedTuple):
"""
Represents the result of training for a single batch: the loss
and number of correct classifications.
"""
loss: float
num_correct: int
class EpochResult(NamedTuple):
"""
Represents the result of training for a sin... |
b1b91d725b1a9664e9d61be5ebdad1fd8fd85869 | amsrafid/asl-simple-py-accounting | /controller/account.py | 2,373 | 3.640625 | 4 | from library.file import File
from model.user import User
from model.Models import Models
"""
Account Management
"""
class Account(Models):
table = "table/accountTable"
def __init__(self):
super().__init__(self.table, 'Account')
@staticmethod
def all():
return File.read('table/accountTable')
"""
Cre... |
4a5cbe1ed1209b768f36b1bc65e7cf4ee59336a2 | amsrafid/asl-simple-py-accounting | /library/file.py | 552 | 3.578125 | 4 | import json
# File input Output
class File:
# Read a JSON file
# @param string dir FIle directory with file name
# @return dictionary
@staticmethod
def read(dir):
with open('./' + dir + '.json', 'r') as file:
return json.load(file)
# Write a JSON Data into a Json file
# @param string dir F... |
a610a07aecfccd0201e9198b1d445066ddd01e70 | MadmanSilver/holbertonschool-higher_level_programming | /0x0C-python-almost_a_circle/models/base.py | 1,932 | 3.515625 | 4 | #!/usr/bin/python3
""" Contains the Base class. """
import json
class Base():
""" I'm the base for everything! """
__nd_objects = 0
def __init__(self, id=None):
""" Initializes the attributes. """
if id is not None:
self.id = id
else:
Base.__nd_objects += 1... |
5e6a0b129f5077b6db4e0583ce83fca398353db8 | MadmanSilver/holbertonschool-higher_level_programming | /0x0B-python-input_output/100-append_after.py | 488 | 4.09375 | 4 | #!/usr/bin/python3
""" Contains the append_after function. """
def append_after(filename="", search_string="", new_string=""):
""" Inserts line of text in file after lines containing new_string. """
with open(filename, "r+") as f:
contents = f.readlines()
for line in range(len(contents)):
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.