blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
a92abc82c220d24429c693e68f19fbdbe8f7175e | pbarton666/virtual_classroom | /dkr-py310/docker-student-portal-310/course_files/begin_advanced/py_while_1.py | 304 | 3.859375 | 4 | #py_while_1.py
counter = 0
while True:
if counter == 1:
print("One is the loneliest number that there ever was.")
counter += 1
continue
print("The counter is now: {}.".format(counter))
if counter > 1:
break
counter += 1
else:
print("Yo. I'm done!")
|
3095511b4a23abc21c3797400ec5cc8bc9dfeef1 | shiseru/DataStructure | /disjoint_set.py | 804 | 4.125 | 4 | """
Disjoint set ADT
make_set(DS, v):
find(DS, v):
Union(DS, x, y):
"""
def make_set(DS, v):
node = new node with value v
DS.add(node)
return node
def find(DS, x):
curr = x
while crur.next is not null:
curr = curr.next
return curr
def union(DS, x, y):
end1 = find(DS,... |
2ee4c336fab2d302ea6ffd9eb24666164caf593a | Evilzlegend/Structured-Programming-Logic | /Chapter 03 - Understanding Structure/D2L Assignments/tiemens_rocks.py | 1,736 | 4.25 | 4 | # Variables to use for user.
tiny = 1
small = 6
medium = 12
large = 18
twelveStone = 168
#User input for tiny rocks.
tinyRock = int(input("How many tiny rocks were used? "))
#Calculate the tiny rock total weight.
tinyRockTotal = tinyRock*tiny
#Print the total of tiny rocks.
print("Your total weight for tin... |
ab55e1d5c8307736052c5a5f8364a42a110c5bc3 | perext5528/Python_2019 | /repl.it Example/2. Numbers/A. Day of week.py | 96 | 3.625 | 4 | a = int(input())
b = a%7
if b==0:
print(3)
elif 0<b<4:
print(b+3)
else:
print(b-4)
|
24301cf096cb67ac59c91e55d32714d993ab7ad4 | bedssys/Bedssys | /utilities/pose_remove.py | 1,545 | 3.640625 | 4 | n_steps = 5
# List them descending to reduce shifting operations
removes = [7, 6, 5, 4]
names = ["_train.txt", "_test.txt"]
for name in names:
for remove in removes:
fx = open("X" + name, "r+")
fy = open("Y" + name, "r+")
x = []
y = []
xtot = 0
ytot = 0
... |
379745111b864b5c8ad21cf7d70c0f5259397be5 | MichalBrzozowski91/algorithms | /leetcode/medium/0148_Sort_List.py | 2,003 | 4.3125 | 4 | # Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
# Merge sort
def merge(self, head1, head2):
'''
Merges two sorted linked lists \n
Return head and tail of a merged list \... |
71ee3d55e8d22da6f3948d3d047fcc0ced799183 | rchithra/EulerProblems | /problem2.py | 674 | 4.03125 | 4 | # Each new term in the Fibonacci sequence is generated by adding the previous two terms.
# By starting with 1 and 2, the first 10 terms will be: 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...
# By considering the terms in the Fibonacci sequence whose values do not exceed four million,
# find the sum of the even-valued terms.
... |
ab5abe8e2934fdafa8547e271034413295c2c38d | GoldF15h/LeetCode | /509. Fibonacci Number.py | 203 | 3.578125 | 4 | def fibo (n) :
if n == 0 :
return 0
if n == 1 :
return 1
else :
return fibo(n-1) + fibo(n-2)
class Solution:
def fib(self, n: int) -> int:
return fibo(n) |
10ca85576c1392053d9df77ff23004350be53b39 | Taoge123/OptimizedLeetcode | /LeetcodeNew/DynamicProgramming/LC_032_Longest_Valid_Parentheses.py | 2,924 | 3.984375 | 4 |
"""
Given a string containing just the characters '(' and ')', find the length of the longest valid (well-formed) parentheses substring.
Example 1:
Input: "(()"
Output: 2
Explanation: The longest valid parentheses substring is "()"
Example 2:
Input: ")()())"
Output: 4
Explanation: The longest valid parentheses subs... |
12fe73de09951e78e9d50414b0320c62a54ae88c | fdfzjxxxStudent/CS001 | /CS001-lesson2/Square.py | 89 | 3.765625 | 4 | #Square.py
s = input("Enter a number:")
x = int(s)
print('Square of', x, 'is', x**2)
|
78e6458d48760fa3e1c7ad23d256dda60c25dde8 | vh62/artificial-intelligence | /vwh2107_hw1/driver.py | 9,869 | 3.796875 | 4 | from __future__ import division
from __future__ import print_function
import sys
import math
import time
import heapq as hq
#import heapq as hq
from collections import deque
#### SKELETON CODE ####
## The Class that Represents the Puzzle
class PuzzleState(object):
"""
The PuzzleState stores a board config... |
76faa55d5496b3e0b08bf66ab13e483e96161b72 | ni-da/iap_1819 | /iap_1718/ex_4.8.py | 139 | 3.53125 | 4 | m = 6
n = 4
for i in range(1, m + 1):
res = 1
for j in range(1, n+1):
res = res*i
print(res, end=" ")
print()
|
b2c6828cd5447eebb74d39318545a1b9316b96f5 | nlebedevinc/machine-learning-basics | /3_2/T3_1/Task3_1d.py | 243 | 4 | 4 | import sys
def max(*nums):
max_n = -sys.maxsize - 1
# print(max_n)
print(nums)
for n in nums:
if max_n < n:
max_n = n
print("Max: ", max_n)
max(3, 5)
max(4, 5, 6, 7)
max(1, 2, 3, 5, 6) |
00a732311b9dec24611426193a3a326c4a863011 | davidkellis/py2rb | /tests/numpy/random_randint.py | 434 | 3.671875 | 4 | import numpy as np
def print_array(data):
datas = []
for i in data:
datas.append(i)
print(datas)
x = np.random.randint(3)
if 0 <= x <= 3:
print('OK')
else:
print('NG')
x = np.random.randint(1,3)
if 1 <= x <= 3:
print('OK')
else:
print('NG')
x = np.random.randint(1,3,(3,3))
print(... |
c5861436e75700d4d7ef76d07257ef14d841caf4 | yurimalheiros/IP-2019-2 | /lista4/amanda/questao3.py | 435 | 4.25 | 4 | numero = float(input("Digite seu número: "))
lista = [ ]
maiorvalor = numero
menorvalor = 0
while numero != 0:
lista.append(numero)
if numero > maiorvalor:
maiorvalor = numero
elif numero < menorvalor:
menorvalor = numero
numero = float(input("Digite seu número: "... |
7369265247c29c0366c37f83ec874af784077ef4 | 7kjmol/PythonTestProject | /Exeicise/1-20/example19.py | 475 | 3.828125 | 4 | '''
题目:一个数如果恰好等于它的因子之和,这个数就称为"完数"。例如6=1+2+3.编程找出1000以内的所有完数。
请参照程序Python 练习实例14。
'''
import math
def isWanShu(num):
sum = 0
i = 1
for i in range(1, num):
if(0 == (num % i)):
sum = sum + i
if(num == sum):
return num
else:
return 0
for num in range(1,1000):
if... |
82f8d2075300a22d9b2b860a2b8c3ab110e385c9 | frankplus/kattis-solutions | /robotprotection.py | 1,584 | 3.78125 | 4 | """
Solution to the Robot Protection problem: https://open.kattis.com/problems/robotprotection
Author: Francesco Pham
Date: 11/12/2019
"""
def andrew_hull(P):
if len(P) < 2: return P
P = sorted(P)
L = []
U = []
for pt in P:
while len(L) > 1 and turn(L[-2], L[-1], pt) <= 0: L.pop... |
6d2980fbaed050f4ded99fbec8d463894540b386 | hpiza/PythonExcercises | /Sesion8a.py | 2,711 | 3.671875 | 4 | estr = "Do#exhq#hqwhqghgru/#srfdv#sdodeudv"
dstr = ""
# descencriptar la cadena de texto estr
for c in range(len(estr)): # c = 0, 1, 2, 3, len = 4
echar = estr[c] # echar = D, E, F, 8
ecode = ord(echar) # ecode = 68, 69, 70, 56
dcode = ecode - 3 # dcode = 65,... |
9603d5e0d733b722db78807aa2ac65836e0960ca | lacitrus/examplecode | /fibonacci_sequence.py | 674 | 3.65625 | 4 | #Fibonacci sequence code by Garry, classmate in LC101 Tampa
def fib_sequence(num):
a = 1
b = 0
def get_sequence(a,b):
for i in range(num):
c = b
b = a+b
a = c
return (b)
return get_sequence(a,b)
print(fib_sequence(4))
#Here are two set of code from... |
534fcfc69bb02bb51c340a909590b533eecc0516 | SkyYongFly/Python | /01_Helloworld/while.py | 839 | 3.640625 | 4 | # ---------循环 while-----------
num = 1
while num < 10:
print(num)
num += 1
# 使用break
print('你猜我想的是哪个数字?')
num = input('请输入:')
while True:
if num == '0':
print('退出程序!')
break
elif num == '99':
print('恭喜你猜对啦!')
break
else:
num = input('你猜错啦,重新猜一个:')
# continu... |
835c6dd29cc4ca7faa0a611ab54e3f9c9c9a8ea5 | Walrick/Projet_3 | /package/character.py | 936 | 3.9375 | 4 | #!/usr/bin/python3
# -*- coding: utf8 -*-
class Character:
""" Class Character for character management """
def __init__(self, name, data):
""" init the character """
self.name = name
self.data = data
self.bag = 0
def move(self, direction, collision):
""" move t... |
edbf748a0536b4308ee76e27d0dc5a3ab34d93fa | aafagundes/IntroducaoProgramacaoParaBiociencias | /tac3ex1.py | 1,007 | 4.09375 | 4 | #1
#Escreva um código em Python para ler o nome, as três notas e o número de faltas
#de um aluno e escrever qual a sua situação final:
#Aprovado, Reprovado por Falta ou Reprovado por Média.
#A média para aprovação é 7,0 e o limite de faltas é 25%
#do total de aulas. O número de aulas ministradas no semestre foi de... |
c9a8c5f8656f63b739f967260afb81f310f535ef | xzj963179571/python_demo | /python_demo/python_selenium_01/python_selenium_06.py | 4,819 | 3.59375 | 4 | # # _*_ coding:UTF-8 _*_
# #
# # import unittest
# # class UserTestCase(unittest.TestCase):
# # """setup()用于测试前的初始化工作;"""
# # def setUp(self):
# # print("===setup==")
# # self.name = "小D课堂"
# # """tearDown()测试后的清除工作,在每个测试方法运行时被调用"""
# # def tearDown(self):
# # print("===tesrDown=... |
f7f266c45182b569320376c78afa6c662d59a247 | cmrawls071/Python-Challenge | /PyPoll/main.py | 3,671 | 3.90625 | 4 | import csv
# make a list to hold candidate names
candidates = []
# open Budget_data CSV file
with open('election_data.csv', mode= 'r') as election:
csvreader = csv.reader(election, delimiter = ",")
# skip header row
next(csvreader, None)
# find the total number of votes cast by counting each row in... |
8c0208d45c6c2437592b230efe94b7acb3ffb3d9 | Ridicz/Python | /second/Six.py | 441 | 3.828125 | 4 | def edge(length):
out = "+"
for j in range(length):
out += "---+"
return out
def middle(length):
out = "|"
for j in range(length):
out += " |"
return out
print "Type number of rows: "
rows = input()
print "Type number of columns"
columns = input()
output = ""
output ... |
ce1e03dc851cca8b3e1e6e38e5026984433b9ad4 | erictleung/rosalind | /python-village/INI6_Dictionaries/dictionary.py | 1,222 | 3.75 | 4 | #!/usr/bin/python
# dictionary.py
# Given: A string s of length at most 10,000 letters
# Return: How many times any word occurred in string. Each letter (upper or
# lower) in word matters. Lines in output can be in any order
# Usage: python dictionary.py FILE
# Date: 2015 Sept 23
# Version: 2.7.10
# import packag... |
6772dbfd4a173716ddcddd524ac39fce79d2c959 | lizuyao2010/bachelor-thesis | /liblinear-1.94/python/read_triple.py | 1,831 | 3.578125 | 4 | # -*- coding: utf-8 -*-
def returndict1(fileName):
f=open(fileName,'r')
d=dict()
n=0
num=0
for line in f:
row = line.strip().split('\t')
if len(row)==1:
continue
if d.has_key(row[0]):
None
else:
d[row[0]]=dict()
for col in r... |
e30a4643ab1183bbb454564bd07d9a881e2417f1 | gushiyu01/NLP | /demo/base/test1.py | 2,826 | 3.8125 | 4 | # 列表
list1 = [4, 7, 1, 2]
# 函数
# len 函数返回列表中的元素个数len(list1)
# max 函数返回列表元素最大值max(list1)
# min 函数返回列表元素最小值min(list1)
# 方法
# append 方法用于在列表的末尾追加新的内容list1.append('1')
# count 方法用于统计某个元素在列表中出现的次数list1.count(1)
# extend 方法表示追加内容,它可以在列表的末尾一次性追加另一个序列中的多个值,也就是用新列表扩展原有列表list1.extend(list1)
# index 方法用于从列表中找出某个元素第一次匹配的位置的索引位置 li... |
ba75c3b7845664271a81b39ebbd19ee32885cb65 | PPythonic/LeecodePython | /array/array_9.py | 1,310 | 3.734375 | 4 | # coding=utf-8
"""
给定一个整数数组和一个目标值,找出数组中和为目标值的两个数。
你可以假设每个输入只对应一种答案,且同样的元素不能被重复利用。
示例:给定 nums = [2, 7, 11, 15], target = 9
因为 nums[0] + nums[1] = 2 + 7 = 9
所以返回 [0, 1]
"""
# 方法1,4000+ms测试通过时间
class Solution(object):
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int... |
eb2ffc9b40a1bda26452dca1ddf220197803612c | kiponik/Python | /Lecture1/HomeTask4.py | 464 | 4.0625 | 4 | # Ввод положительного числа
positiveNumber = int(input("Введите пожалуйста целое положительное число: "))
largeNumber = 0
# Проверка на самую большую цифру в числе
while(positiveNumber > 0):
checker = positiveNumber % 10
if largeNumber < checker:
largeNumber = checker
positiveNumber = positiveNu... |
ae95bfe3f6fb16cd8dc43299beeff5b18943e575 | cnk113/assignments | /problem12.py | 1,167 | 3.671875 | 4 | #!/usr/bin/env python3
# Name: Chang Kim (cnkim)
# Group Members: None
import sys
'''
This program takes in from stdin and a collection of kmers seperated by new lines
Outputs to stdout the adjacency of a deBrujin graph
'''
def deBrujin(lines):
'''
constructs the deBrujin graph in the form of an... |
21b71b407af61533b529d47cbc341f8dd28348a5 | httptaniyan/codility | /codility_code/lesson2-1 copy 2.py | 420 | 3.65625 | 4 | # you can write to stdout for debugging purposes, e.g.
# print("this is a debug message")
#計算方法の改善が必要
import collections
def solution(A):
tmp = set(A)
counter = 0
unpair_num = 0
for i in tmp:
counter = A.count(i)
if counter % 2 = 0:
A.remove(i)
else:
un... |
893ba1399ebe28f1124b3544debbf2c3ec7ec843 | aufbakanleitung/ProjectEuler | /dana.py | 897 | 3.9375 | 4 | class Herman:
def __init__(self, *values):
self.values = values
def __repr__(self):
if len(self.values) == 0:
return "This is an object oriented Herman 🤘"
elif len(self.values) == 1:
return f"Herman is {self.values[0]}"
elif len(self.values) == 2:
... |
941aee2d4927b4299cfc4e051ed524426a722813 | namnguyen6595/nguyenthanhnam-fundamential-c4e19 | /Session3/another_test.py | 651 | 3.6875 | 4 | # food1 = "Kem"
# food2 = "Xoi"
# food3 = "Pho"
# food4 = "Thit"
# food5 = "Tao Pho"
# list / array
menu = ["Kem","Xoi", "Pho", "Thit", "Tao Pho"]
# del: xoa theo index
# del menu [1]
# pop: xoa theo index
# menu.pop(1)
# remove: xoa theo item
# menu.remove ("Tao Pho")
#sep = separator: khoang cach
# print (*... |
cf9707cd8a1c79bfa0d0d08a49abc4ce678f620d | ArmaanJH/EncryptedDictionary | /EncryptedDictionary.py | 2,347 | 3.828125 | 4 | from EncryptionClass import Encryption
from DictionaryClass import Dict
import time
import os
CrPa_loop = False
while CrPa_loop is False:
passw1 = input("Enter a Password: ")
passw2 = input("Please reenter Password: ")
if passw1 == passw2:
encrypt = Encryption(passw1)
EK = encrypt.generate_... |
e789eaa993edaee8d315ef6eb9c1c0a3ab891f14 | xiao-a-jian/python-study | /month01/day16/day16/demo06.py | 721 | 4.0625 | 4 | """
生成器表达式
"""
list01 = ["a", 10, "b", 1.5, True, 20]
# 将list01中所有整数存储在list02中
# list02 = []
# for item in list01:
# if type(item) == int:
# list02.append(item)
list02 = [item for item in list01 if type(item) == int]
for item in list02:
print(item)
# 生成器函数:函数体中有yield
# def find01():
# for ite... |
4c25e361f870246859d430d83011e9274e5a1c5c | Jonatas-Soares-Alves/Exercicios-do-Curso-de-Python | /MUNDO 1/Aula 07a.py | 128 | 4.0625 | 4 | from math import sqrt
num = int(input('Digite um Número: '))
print('A raiz quadrada de {} é {:.2f}'.format(num, sqrt(num)))
|
522f11666c4d1713de02dcdd3b66f05bb69295c1 | jfarmer864/BlackJack | /cards.py | 3,528 | 3.625 | 4 | import random
import sys
list_of_suits = ['Spades','Clubs','Hearts','Diamonds']
list_of_faces = ['Ace', 2, 3, 4, 5, 6, 7, 8, 9, 10,'Jack','Queen','King']
class Card:
def __init__(self, face, suit):
self.face = face
self.suit = suit
class Deck:
def __init__(self):
self.deck = []
... |
864d4d32c070ad8b5545117876fafd3efb628f1b | tatyanakovalchuk/homework | /createmodule.py | 1,501 | 4.03125 | 4 | import sys
import sqlite3
conn = sqlite3.connect('phonebook.db')
cur = conn.cursor()
def create_note():
while True:
name = input("Введите имя: ")
if len(name) != 0:
break
else:
print("Пожалуйста, введите имя")
while True:
surname = input("В... |
adf82573635248c73578b53a4c14d0f92c901ca2 | muhamadsutanalrasyid10/ArkademyK-5 | /Jawaban nomor 2.py | 829 | 3.5625 | 4 | import re
def is_username_valid(username):
usernameregex = re.compile(
r'^[^0-9!@#\$%\^\&\*\)\(\+\=\.\_\-][0-9a-zA-Z!@#\$%\^\&\*\)\(\+\=\.\_\-]{5,9}$')
match = usernameregex.search(username)
if match:
return True
else:
return False
def is_password_valid(password):
... |
de70b603252e9c4e256f7c8537d89b9aa3809654 | jask05/PythonCourse | /Ejercicios/17_bucles_iv_while.py | 885 | 4.0625 | 4 | # -*- coding: utf-8 -*-
i = 1
while i <= 10:
print(f"Iteración número: {i}")
print("Iteración nº " + str(i))
i = i + 1
edad = int(input("¿Cuál es tu edad? "))
while edad <= 0 or edad >= 100:
print("La edad que has introducido es incorrecta.")
edad = int(input("¿Cuál es tu edad? "))
print("[-] P... |
d18cdd848d947136a9be12aea43d2e1ce056c65a | samsvp/crypto | /train.py | 1,255 | 3.5 | 4 | """
Script to train a Random Forest Classifier to differentiate
between four different encription methods: the caesar cypher,
the vigenere cypher, rail_fence cypher and xor cypher
"""
#%%
import numpy as np
from typing import Tuple, List
from sklearn.ensemble import RandomForestClassifier
def read_set(train: bool) ->... |
a7dba39a70de7af7c2f2022822d5b7bd9c14c9bf | imsavin/quantory_python_hw | /hw19_server.py | 1,002 | 3.59375 | 4 | # Standard library
import socket
def main():
port = 5353 # DNS operates on port 53 by default, we use 5353 to mock traditional behavior
ip = "127.0.0.1"
dns_dict = {'ya.ru':'87.250.250.243', 'www.org':'128.30.52.17', 'savin.org.ru':'194-67-90-3'}
sock = socket.socket(socket.AF_INET, socket.... |
db6c72c6cc714c03b72684b777cd4929991c4379 | miwilska/pythonProject | /zolwie/drzewo_analityk.py | 788 | 3.75 | 4 | import turtle
import random
t = turtle.Turtle()
t.speed(0)
t.setheading(90)
t.penup()
t.goto(0, -200)
t.pendown()
def gałąź(t, len):
if len == 0: return
nt = t.clone()
nt.pensize(len * 3)
if len < 3:
nt.color('green')
nt.forward(50)
if random.randint(0, 2) in (1, 2):
... |
6a1ee1c0cc62ad0c52b03a8548b382a2d18921c5 | ruchi2310/tathastu_week_of_code | /day 6/program 10.py | 274 | 4 | 4 | # tathastu_week_of_code
lst=[]
n=int(input("enter number of list n"))
for i in range(0,n):
print("list",i)
k=int(input("enter the no.of element"))
for j in range(0,k):
ele=int(input())
lst.append(ele)
print(lst)
print("merge list is k=",lst)
|
87e98ba38f28f714034cd38144bf1336532fb8da | vipsinha/Python | /Udacity/2_ControlFlow.py | 9,581 | 4.46875 | 4 | # '''
# You decide you want to play a game where you are hiding
# a number from someone. Store this number in a variable
# called 'answer'. Another user provides a number called
# 'guess'. By comparing guess to answer, you inform the user
# if their guess is too high or too low.
# Fill in the conditionals below t... |
2019c940140eb093e4f08a4d53c34101d2c60479 | ikottman/devcon-word-cloud | /submission_cleaner.py | 1,200 | 3.609375 | 4 | from nltk.stem import WordNetLemmatizer
import string
class SubmissionCleaner:
@staticmethod
def combine_similar_words(words_list):
lemmatizer = WordNetLemmatizer()
reduced_list = []
# find the lemma of each word
for word in words_list:
reduced_list.append(lemmatize... |
01f64f5675e87ef10a6adaa40f4063dc0598b466 | olevare/Compresseur | /FinalARChis.py | 6,623 | 3.59375 | 4 | #!/usr/bin/python
# -*-coding:utf-8-*-
import os,sys,re,time
def temp(): #juste parce que c'est classe
nbr=0
while nbr!=10 :
time.sleep(0.25)
print" ."
nbr+=1
print "-----------------------------------------------------------------------"
res="... |
56ee4d1690cc64d9ce0654a26c255fc66d516348 | Subhasish1985/pythonProject2 | /dictionary.py | 1,121 | 4.28125 | 4 | '''
Details:
Return to your first homework assignments, when you described your favorite song.
Refactor that code so all the variables are held as dictionary keys and value.
Then refactor your print statements so that it's a single loop that passes through each item in the dictionary and
prints out it's key and then i... |
28eadd793033aaf0f625c2dccdf9f7d6200b5977 | Shivampanwar/algo-ds | /Trees/GenericTree.py | 463 | 3.8125 | 4 | class Node(object):
def __init__(self, data):
self.data = data
self.children = []
def add_children(self, obj):
self.children.append(obj)
def print_children(root):
print
root.data
for i in root.children:
# print i.data
print_children(i)
root = Node(2)
p = ... |
d25a0a142c8015a5ac684f5e73eeeed9b043df08 | BrianDinh91/PLTWCSP1920 | /team8.py | 2,699 | 3.546875 | 4 | ####
# Each team's file must define four tokens:
# team_name: a string
# strategy_name: a string
# strategy_description: a string
# move: A function that returns 'c' or 'b'
####
#version 1/28/30
team_name = 'collusion8' # Only 10 chars displayed
strategy_name = ''
strategy_description = 'Always collude... |
c268a1c48caafcb39da0efd9e7c30a2240285323 | dconn20/MPP.Project | /shop.py | 7,313 | 4.5 | 4 | from dataclasses import dataclass, field
from typing import List
import csv
# A data class is a class whose main purpose is to store data without functionality.
# This kind of class, also known as a data structure, is very common.
@dataclass
class Product:
name: str
price: float = 0
@dataclass
class Produ... |
13a708ba642835d2d55e05c3e684a5dc401bc258 | JRubin09/EscapemetProyect | /asd.py | 1,110 | 4 | 4 |
hola = 'hola,como,estas'
# with open("Database.txt","a+") as db:
# datos = db.write('texto,a,escribir')
with open("Database.txt") as db:
efe = db.readlines()
for i in range(len(efe)):
a = i + 1
if a > len(efe):
print(a)
db.writelines(efe+'\n'+hola)
print(efe+'\n'+hol... |
64f97fc2a8771209967f70e519492bfa5b8933a4 | KiraGol/Hillel | /homework_1/9.py | 516 | 3.9375 | 4 | john = {
"full_name": "John",
"age": 35,
"salary": 456.7,
"gender": True,
"friends": {"first": "Mark", "second": "Jack"},
"coordinates": (46.4873195, 30.7392776)
}
marta = {
"full_name": "Marta",
"age": 37,
"salary": 534.89,
"gender": True,
"friends": {"first": "Molly", "sec... |
ff8c86535b8412ab77c6a14d74d97149f146b1e9 | shahrozimtiaz/codingPractice | /python Practice/car.py | 425 | 3.65625 | 4 | from vehicle import Vehicle
class Car(Vehicle):
def __init__(self,vehicleType,doors,wheels,carType,maker):
super().__init__(vehicleType)
self.doors = doors
self.wheels = wheels
self.carType = carType
self.maker = maker
def toString(self):
print('VehicleType:',sel... |
d6d4dab7051ba78cfbbfac60e3701e49448e0c07 | Jafet6/Jafet6.github.io | /computer-science/exercises/39_3/exercise1.py | 3,868 | 3.9375 | 4 | from node import Node
class LinkedList:
def __init__(self):
self.head_value = None
self.__length = 0
def __str__(self):
return f"LinkedList(len={self.__length}, value={self.head_value})"
def __len__(self):
return self.__length
def insert_first(self, value):
f... |
6b622964baf25ce8767b4554ba9f818e00b3b4e5 | leejihoo/baekjoon-py | /11723.py | 1,556 | 3.703125 | 4 | import sys
input1 = sys.stdin.readline
# def binary_search(li, val):
# # low = 0
# # high = len(li) - 1
# # while low <= high:
# # mid = (low + high) // 2
# # if li[mid] < val:
# # low = mid + 1
# # elif li[mid] > val:
# # high = mid - 1
# # else:
# ... |
76615305ccb5996472b7572e3a76393460006aa6 | devansh27201/AkashTechnolabs_Internship | /D-3-Tasks/cal6.py | 280 | 3.671875 | 4 | class cal6:
def setdata(self):
self.length = length
def Area(self):
self.a = length*length
def display(self):
print('Area of Square is : ', self.a)
length = int(input('Enter length: '))
c = cal6()
c.Area()
c.display()
|
c606744b12399550c5a6d69c18c3c5509d6c9156 | ryantakeshihagerty/Code-Test | /goal_difference.py | 1,575 | 3.671875 | 4 | import os.path
import sys
import pandas as pd
import file_parser as fp
# Headers for weather data file
headers = ['Team', 'P', 'W', 'L', 'D', 'F', 'A', 'Pts']
# Check command line arguments for filename, default to 'soccer.dat' if not provided
if len(sys.argv) > 1:
filename = sys.argv[1]
else:
fil... |
9fb439de7e2fe099e94e37b2666e1fd8eb2b7fb6 | majesticfish/sonnet-generation | /preprocess.py | 3,274 | 3.578125 | 4 | import re
import numpy as np
def get_token_dict():
print("getting token")
f = open("data/Syllable_dictionary.txt", 'r')
lines = f.readlines()
wordlist = []
syllable_count = []
wordlookup = {}
for line in lines:
l_split = line.split(" ")
l = len(l_split)
# create dic... |
7ed62ae6d6d7f29bfe9e498203106be91f3377a6 | wavefancy/WallaceBroad | /python/utils/Excel2Txt/Excel2Txt.py | 2,397 | 3.546875 | 4 | #!/usr/bin/env python3
"""
Convert Excel file (xls, xlsx) file to txt file.
@Author: wavefancy@gmail.com
Usage:
Excel2Txt.py -f filename [-i index]
Excel2Txt.py -h | --help | -v | --version
Notes:
1. Read content from -f file, and output results to stdout.
2. Line in... |
eda349867e51c68dc432fbdefcf0872aa9a9c4ae | 0zancan/AlgorithmBasics | /Week 3/hw3_4.gyp | 236 | 3.828125 | 4 | # n klavyeden girilen pozitif bir sayıdır.
# 1'den n'ye kadar olan sayıların toplamını ekrana yazdıran program
n = int (input("Pozitif bir tam sayı giriniz: "))
toplam = 0
for i in range(n):
toplam +=i
print(toplam)
|
2d1b922fc2f8fd554638ee055a3f00bf7ebe4740 | zhengxiang1994/optimization | /simulated_annealing.py | 1,303 | 4.03125 | 4 | import numpy as np
import matplotlib.pyplot as plt
'''
find the minimum point by using simulated annealing method
'''
def obj_function(x):
y = x ** 3 - 60 * x ** 2 - 4 * x + 6
return y
# plot
# x = np.linspace(0, 100, 1000)
# y = obj_function(x)
# plt.plot(x, y)
# plt.show()
if __name__ == '__main__':
... |
cf9fc6779bc7bf42eaad95f3f890c379f7aee1b4 | Suspious/functions-tryout | /fibonacci.py | 359 | 3.875 | 4 | getallen = int(input('hoeveel termen? '))
n1, n2 =0, 1
count = 0
if getallen <= 0:
print("Please enter a positive getal ")
elif getallen == 1:
print("Fibonacci sequence upto",getallen,":")
print(n1)
else:
print("Fibonacci sequence:")
while count < getallen:
print(n1)
nth = n1 + n2
n1... |
1f693b26a7ff7ba2d9565dfea543fa027e74597b | IrinaKyryliuk/HW_git | /HW_1/HW1_2.py | 361 | 3.796875 | 4 | '''
weight : cheese's weight
costCheese: cost of cheese
price: price of cheese
'''
costCheese = input("Input the cost of cheese ")
costCheese=float(costCheese)
print('1kg chees =', costCheese, 'grn')
print('weight, g\t', 'price, grn\t')
for weight in range(50, 1050, 50):
price = costCheese / 1000 * weight
p... |
e295f343c82e1478d45ec42525db4a8363626eda | Argonauta666/coding-challenges | /grokking-coding-interview/13-top-k-elements/maximum-frequency-stack.py | 1,852 | 3.90625 | 4 | # https://leetcode.com/problems/maximum-frequency-stack/
import heapq
class Element:
def __init__(self, number: int, frequency: int, sequenceNumber: int):
# value of the number
self.number = number
# current frequency of the number when it was pushed to the top
self.frequ... |
ff22d376ba751fc8780ea502984d064e6ce4379c | talksis/python | /EP_04_stirng method_input_output/input_format_04.py | 2,004 | 3.5 | 4 | """
4. 문자열 format 심화
문자열을 다루다보면 우리가 출력하고 싶은 정보를 출력하기에 번거로운 부분이 있을 수 있습니다. 이를 위해서 + 기호를 사용하고 end 의 값을 변경할 수 있지만,
문자열 자체를 우리가 원하는 문자열로 바꾸어 출력하는 방법도 생각해 볼 수 있습니다. 이를 위해서 문자열 메소드 중 format 메소드가 존재합니다.abs
**str.format(*args, **kwargs)**
<https://docs.python.org/3/library/stdtypes.html#str.format>
format 메소드에서도 *과 **이 존재하는데... |
8f84b36afb3ecf5386272035e53bcdc701bd08da | dhanashreesshetty/Project-Euler | /Problem 21 Amicable numbers/pyprog.py | 545 | 3.5 | 4 | def calculate(n):
sum=0
for j in range(1,int(n/2)+1):
if n%j==0:
sum+=j
return sum
i=4
amic_sum=0
while i<10001:
sum=calculate(i)#calculates sum of divisors
if sum>i and sum<10001:#if the sum is greater than the number itself and doesn't exceed 10000, calculate sum of... |
20ff8fe8d421a537799976d4584c41b0e047f6ed | meighanv/05-Python-Programming | /LABS/Labs-6-1/lab6-1-onBudget.py | 1,538 | 3.921875 | 4 | from functools import reduce
#Define main
def main():
budget = getBudget()
expenses = []
getExpenses(expenses)
overOrUnder(budget,totalExp(expenses))
def getBudget():
budget = input('What is your budget? (Ex: 3206.10):\n')
#Input validation checking numeric and a positive number
while flo... |
359571e2c9767cc177bc45647dbfb1f369d8f084 | yxys01/interview | /3-字符串与正则表达式/如何使用fstring方式格式化字符串.py | 497 | 3.796875 | 4 | # 2、 fstring(大括号中可以直接使用各种Python变量)
name = 'Bill'
age = 20
def getAge():
return 21
s = f"我是{name},我今年{age}岁,明年{getAge()}岁" # 将变量放到{}中;不仅能放变量也能放函数
print(s)
class Person:
def __init__(self):
self.name = 'Mike'
self.age1 = 40
def getAge(self):
return 41
person = Person()
s1 = f"我是... |
df58ac3a2a5c935cca4f72edf7f17f09cb51db05 | Francisde/PropaedeutikumSoSe2019 | /Material/Uebungsaufgaben/Blatt4/aufgabe5.py | 884 | 3.796875 | 4 |
# Funktion zur Prüfung ob ein korrekter Punkt-Klammer-Ausdruck vorliegt
# liefert True oder False zurück
def checkPunktKlammerAusdruck(string):
oeffnendeKlammern=0
for zeichen in string:
if(zeichen=="("):
oeffnendeKlammern +=1
if(zeichen==")"):
if oeffnendeKlammern >0:
... |
298a90512c9844d6defe92149c44a8773c60cfcf | RobertGodin/CodePython | /ExempleSequenceSurUneLigne.py | 496 | 3.890625 | 4 | # -*- coding: utf-8 -*-
'''
Ce programme illustre le cas d'une séquence sur une ligne '''
# Saisir les deux chaînes de caractères qui représentent des nombres entiers
chaine1 = input("Entrez un premier nombre entier :")
chaine2 = input("Entrez un second nombre entier :")
# Convertir les deux chaînes de caractères en ... |
d9faa1c191a9651426a589536973864d62666fa0 | Aasthaengg/IBMdataset | /Python_codes/p03042/s806167573.py | 251 | 3.5625 | 4 | S = input()
S1, S2 = S[0:2], S[2:5]
if (int(S1) >= 1 and int(S1) <=12) and (int(S2) >= 1 and int(S2) <=12):
print('AMBIGUOUS')
elif int(S2) >= 1 and int(S2) <= 12:
print('YYMM')
elif int(S1) >= 1 and int(S1) <=12:
print('MMYY')
else:
print('NA')
|
c5e9c3cdf6362e541cdf89aa994cd844dada5181 | mandarspringboard/notes | /Pandas_notes/pandas_column_hierarchical_indexing.py | 521 | 3.84375 | 4 | # -*- coding: utf-8 -*-
"""
Nachiket Gokhale
Wes McKinney's Python for data analysis
page 218
"""
import pandas as pd
import numpy as np
frame = pd.DataFrame(np.arange(12).reshape((4, 3)),
index=[['a', 'a', 'b', 'b'], [1, 2, 1, 2]],
columns=[['Ohio', 'Ohio', 'Colorado'],
['Green'... |
ef0076c42eb5bd8c373b09ee24b2d2f4609ca700 | APandher/ProjectEuler | /Problem 1.py | 288 | 3.890625 | 4 | import math
def main():
total = 0
end_limit = 1000
for number in range(1,end_limit):
if number%3== 0 or number%5 ==0:
total += number
return total
#Find the multiples of 3 below 1000
#Find the multiples of 5 below 1000
#Remove duplicates and add the remaining multiples
|
402d62ba0cdf6f8389f84ea13279b8f70cc90f82 | aulb/ToAsk | /Technical Questions/150 - Polish Notation.py | 1,192 | 4.15625 | 4 | #!/usr/bin/env python
# Reverse Polish Notation
# https://interactivepython.org/runestone/static/pythonds/BasicDS/ImplementingaStackinPython.html
class Stack:
def __init__(self):
self.items = []
def isEmpty(self):
return self.items == []
def push(self, item):
self.items.appen... |
93aaa8def73ac7fc3cf5bd273bf97aa6d6502085 | cu-swe4s-fall-2019/trees-alisoncleonard | /binary_tree.py | 2,812 | 4.03125 | 4 | """
Module to build and search through an AVL tree
"""
import csv
class Node:
def __init__(self, key, value=None, left=None, right=None):
"""
creates a node
Parameters
----------
key: the key of the node
value: the value associated with key
lef... |
0932f400b4f9ff4091743d8ee5362b499b4e5ac6 | TishinIlia/jobeasy-algorithms-course | /lesson_6/Pair_sum.py | 282 | 4.125 | 4 | # Function has given a list of integer numbers and k integer number.
# It returns all pairs of numbers from the list which equal to k.
# E.g. pair_sum([1, 3, 4, 6, 8, 2, 2], 4) returns (1,3) and (2,2)
def pair_sum(arr, k):
pass
print(pair_sum([1, -1, 3, 4, 2, 2, 0, 5], 4))
|
b3a622392c9e067b07b3000ecb1acf20e911e507 | lachlanhughes/Practicals | /prac4/warmup.py | 401 | 3.90625 | 4 | # 3
# 2
# 1
# 3, 1, 4, 1, 5, 9, 2
# 1, 5
# 5
# 2
# 1
# 3, 1, 4, 1, 5, 9, 2, 6, 5, 3
numbers = [3, 1, 4, 1, 5, 9, 2]
print(numbers[0])
print(numbers[-1])
print(numbers[3])
print(numbers[:-1])
print(numbers[3:4])
print(5 in numbers)
print(7 in numbers)
print("3" in numbers)
print(numbers + [6, 5, 3])
print("")
numbe... |
7b318542793f66bf01932fe9f3786dd5c7adda1a | qyl1006/MyGitHub | /Python_World/类练习.py | 4,835 | 3.890625 | 4 | class Dog():
"""一次模拟小狗的简单尝试"""
def __init__(self, name, age):
"""初始化属性name和age"""
self.name = name
self.age = age
def sit(self):
"""模拟小狗被命令时蹲下"""
print(self.name.title() + ' is now sitting.')
def roll_over(self):
"""模拟小狗被命令时打滚"""
print(self.name.title() + ' rolled over!')
my_dog = Dog('w... |
735c222ae89d418987b1dd04af8dfed32718c7a7 | ehdgua01/Algorithms | /data_structures/tree/lcrs/lcrs.py | 816 | 3.8125 | 4 | class Node(object):
def __init__(self, value) -> None:
self.child = None
self.sibling = None
self.value = value
def append(parent: Node, child: Node) -> None:
if parent.child is None:
parent.child = child
else:
temp = parent.child
while temp.sibling:
... |
35541fe593edb9c3dd0cec1fd9bbba8287bc9fb9 | Zenardi/Udacity-Intro-Machine-Learning | /chicago-bikes/bikes/chicago_bikeshare_task6.py | 1,530 | 3.953125 | 4 | # coding: utf-8
# Começando com os imports
import csv
# import matplotlib.pyplot as plt
# Vamos ler os dados como uma lista
print("Lendo o documento...")
with open("chicago.csv", "r") as file_read:
reader = csv.reader(file_read)
data_list = list(reader)
print("Ok!")
# Vamos verificar quantas linhas nós temos... |
ac92b160f0eec319969d8632f574cf33c2757596 | leemingeer/datastruct | /fact_sum.py | 1,337 | 4.09375 | 4 | #!/usr/bin/env python
class Factorial(object):
def __init__(self, n):
self.n = n
if not isinstance(self.n, int) and self.n < 1:
print("input must be integers(>0)")
return None
def fact(self, n):
if n == 1:
return 1
return n*self.fact(n-1)
... |
6c2166b61be6f451eac2fb37480159026cc3f34a | parth04/Data-Structures | /Strings/addString.py | 1,034 | 4.1875 | 4 | 415. Add Strings
Easy
Given two non-negative integers num1 and num2 represented as string, return the sum of num1 and num2.
Note:
The length of both num1 and num2 is < 5100.
Both num1 and num2 contains only digits 0-9.
Both num1 and num2 does not contain any leading zero.
You must not use any built-in BigInteger lib... |
16b0b76a3e8514f01e86c0190db46763ac6e48ad | arironman/MSU-Python | /ex-7/26.py | 299 | 4.40625 | 4 | side=[]
for x in range(0,3):
a=int(input(f"Enter side{x+1}: "))
side.append(a)
if side[0]==side[1]==side[2]:
print("Triangle is Equivalent")
elif side[0]==side[1] or side[1]==side[2] or side[0]==side[2]:
print("Triangle is isosceles")
else:
print("Triangle is scalar")
|
cde297451f91da4348f927f6c3ece9c3d3a96d17 | danslavov/Programming-Basics-Python-2017-MAY | /07_AdvancedLoops/P14_NumberTable.py | 222 | 3.890625 | 4 | n = int(input())
for row in range(1, n + 1):
for colAscend in range(row, n + 1):
print(colAscend, end=" ")
for colDescend in range(n - 1, n - row, -1):
print(colDescend, end=" ")
print()
|
28bad3c419997b406f5f76e89bb8bc5f7894f6de | HalfMoonFatty/Interview-Questions | /081. Search in Rotated Sorted Array II.py | 516 | 3.890625 | 4 | '''
Problem:
Follow up for "Search in Rotated Sorted Array":
What if duplicates are allowed?
Would this affect the run-time complexity? How and why?
Write a function to determine if a given target is in the array.
'''
# Solution: If duplicates are allowed, the only way to search is linear scan, so r... |
771152f440e7cb6e573531ab7e3a0d48b194741a | liseyko/CtCI | /Chapter 2 - Linked Lists/c0202.py | 846 | 3.765625 | 4 | """ find the kth to last element of a singly linked list """
from random import randint
from linkedlist import LinkedList
N_OF_ELEMENTS = 8
k = randint(1,N_OF_ELEMENTS)
l1 = LinkedList()
l1.populate(N_OF_ELEMENTS)
print(l1)
#Sol 1
t = 0
n = l1.head
while n:
n = n.next
t+=1
n = l1.head
for _ in range(t-k):
... |
7d9f371f3253316de51c7020144da569534bd37e | jtew396/InterviewPrep | /trip.py | 438 | 3.609375 | 4 | def countTriplets(arr, r):
arr_set = set(arr)
arr_of_arr = []
count = 0
for i in range(len(arr)):
arr_of_arr.append([arr[i],arr[i]*r,arr[i]*r*r])
for j in arr_of_arr:
if j[0] in arr_set and j[1] in arr_set and j[2] in arr_set:
count += 1
print(arr_of_arr)
return... |
d59933d43e42961758d3b297800291e23bf24107 | Ngyg520/python--class | /预科/7-23/全局变量与局部变量的作用域.py | 1,641 | 4.28125 | 4 | """
座右铭:路漫漫其修远兮,吾将上下而求索
@project:预科
@author:Mr.Yang
@file:全局变量与局部变量的作用域.PY
@ide:PyCharm
@time:2018-07-23 11:24:28
"""
#变量的作用域:是指一个变量所产生的作用范围,也就是说在哪一个范围内变量能够被解释器所识别
#变量分为:全局变量和局部变量
#全局变量:一般声明在函数的外部
#全局变量的作用域:整个.py文件内都可以使用,都可以被识别
#局部变量:一般声明在函数的内部.
#局部变量作用域:只能在函数的内部使用,超出范围,变量就不能再使用
#list1相当于全局变量,作用域是整个.py文件
list1=[]
d... |
d674573ce862324fe8d9291b2793c24e19718e94 | JeffersonLobato/Curso-Completo-de-Python-no-Youtube | /Curso_Python/funcoes.py | 537 | 3.609375 | 4 | def soma(num1, num2):
soma1 = num1
soma2 = num2
soma_total = soma1 + soma2
return soma_total
def sub(num1, num2):
sub1 = num1
sub2 = num2
sub_total = sub1 - sub2
return sub_total
def mult(num1, num2):
mult1 = num1
mult2 = num2
mult_total = mult1 * mult2
return mult_tota... |
18bfc8f2f48fa6a8f0a1c98a51b1c7863448dc55 | blues-lead/python_prog | /kierros1/T161.py | 135 | 3.546875 | 4 | def main():
nimi = input('Tell your name: ')
print("Hi " + nimi + ", your coding skills are great!",eioo)
print(x)
main() |
2b03d0caebf73daf08b3fc21562b1121a67eeaa3 | lofues/LeetCode-Excerise | /965_单值二叉树.py | 782 | 4.0625 | 4 | # Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def isUnivalTree(self, root: TreeNode) -> bool:
if root is None:
return True
elif root and root.left is None ... |
cb5a0435f603fc3e1dcdaee050e6871bcee9b40c | vincent-kangzhou/Leetcode_Easy | /263_Ugly Number.py | 273 | 3.625 | 4 | class Solution(object):
def isUgly(self, num):
"""
:type num: int
:rtype: bool
"""
if num<=0: return False
for i in [2,3,5]:
while num%i==0:
num=num//i
return True if num==1 else False
|
79f516630313e286eafd14b284cd47537f8f787b | damasktb/AdventOfCode2020 | /Day10.py | 516 | 3.5 | 4 | import itertools
from operator import mul
adaptors = sorted([int(a) for a in open("Day10.txt")])
adaptors.append(max(adaptors) + 3)
def getSteps(adaptors, steps = [1]):
steps.extend([j-i for i, j in zip(adaptors[:-1], adaptors[1:])])
return steps
s = getSteps(adaptors)
print s.count(1) * s.count(3)
repeats = [lis... |
5db5dcf1d2755f22fc87dd1f3c6d8341f9788ec8 | ALICE5/Python | /py_demo/输入输出.py | 198 | 4.1875 | 4 | print('Hello, World!')
x = int(input('Enter a number:'))
print(x+x)
print('''
hi everybody,welcome to \
python's MOOC course.
Here we an learn something about
python.Good luck.
''')
# 续航符: \
|
d0da5302d69c4d9c1d9bcfb890d0931437b263af | b96705008/py-lintcode-exercise | /basic/ch2/recover_rotated_sorted_array.py | 875 | 3.734375 | 4 | class Solution:
"""
@param nums: An integer array
@return: nothing
"""
def swipe(self, nums, start, end):
first = start
last = end
while first < last:
nums[first], nums[last] = nums[last], nums[first]
first = first + 1
last = last - 1
... |
d9d433384b0538c728b331edd3cfcc2091db2e68 | sakalypse/rsa | /decipher.py | 1,116 | 3.5625 | 4 | import math
import MathUtils
import StringUtils
def TrouverClePrivee(n, c):
"""
Trouve la clé privée associée à une clé publique
param n: n de la clé publique
param c: d de la clé publique
return: l'entier d de la clé publique
"""
divider = [d for d in range(2, int(math.sqrt(n))) if n%d == 0]
p = divider[0]... |
a51bc23a448da194213b56f66a28ed888b5d8ff2 | methsaan/python | /usefulprograms/functiongraph.py | 854 | 3.625 | 4 | #! /usr/bin/python3
from math import *
import time
from tkinter import *
tk = Tk()
canvas = Canvas(tk, width=1000, height=1000, bg="lightblue", bd=0, highlightthickness=0)
canvas.pack()
def plot(x, y):
xcoord = 500+x
ycoord = 500-y
canvas.create_oval(xcoord-1, ycoord-1, xcoord+1, ycoord+1, fill="red", out... |
f36a1cd45c3447e8c0ca853fe0af7c3ab5e17410 | anastasia-pashkova/aap_learning_python | /search_insert.py | 1,245 | 3.75 | 4 | class Solution:
# def searchInsertIndex(self, nums: List[int], target: int, left: int, right: int) -> int:
# if left >= right:
# if nums[left] < target:
# return left + 1
# else:
# return left
# mid = ( right - left ) // 2 + left
# ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.