blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
91d95fedbb1001aee1cb45f8622ef6854b9e1cf0 | YeDeheng/spos | /src/others/test-tokenizer.py | 575 | 3.984375 | 4 | # -*- coding: utf-8 -*-
s = '\x97'
print unicode(s, errors='replace')
s = '上午'
print unicode(s, 'utf-8')
# s = unicode('上午')
# uni = unicode(s)
# f = open('output.txt', 'w')
# f.write(uni.encode('utf-8')+'\n')
# uni = unicode(s)
# print uni
InputString='ABC\x97abc上午'
print InputString
print InputString.decode('utf... |
829f9a07d488bad50f35a08c5fcd9164c6065b94 | SanthoshKR93/Python_Anandology_Solutions | /Modules/problem_4_directory_tree_versn_2.py | 618 | 3.890625 | 4 | # Write a program to print directory tree. The program should take path of a directory as argument and print all the files in it recursively as a tree.
import os,sys
from os.path import join,isfile
d = []
listt = []
val = ''
g = ''
def dir_tree(dlist,v = 0):
d = dlist.split("/")
val = d[-1]
#print(d)
l... |
e1388190d0ce88d4f8dd80b51dcd5ab63ed09ab2 | LiuJLin/learn_python_basic | /ex28.py | 1,022 | 4.125 | 4 | def true_false_to_NUM(bool_word):
if bool_word == False:
num_bool = 0
else:
num_bool = 1
print (num_bool)
true_false_to_NUM(True and True)
true_false_to_NUM(False and True)
true_false_to_NUM(1 == 1 and 2 == 1)
true_false_to_NUM("test" == "test")
true_false_to_NUM(1 == 1 or 2 != 1)
true_fals... |
ca95cd9e625ee61d541e9746e3525ce2226541bb | Artem7898/Python_Lesson_6 | /task_2.py | 880 | 4.21875 | 4 | """
Задание 2.
Предложить варианты оптимизации и доказать (наглядно, кодом) их эффективность
"""
import sys
class Point:
__slots__ = 'x', 'y', 'z'
def __init__(self, x, y, z):
self.x = x
self.y = y
self.z = z
ob = Point(1,2,3)
print(sys.getsizeof(ob))
"""
Задать ограниченный набор ат... |
17cef3d65e73cc83e6017cae98a2ca505d406e6f | huazhige/EART119_Lab | /hw4/submissions/passerscarlet_26789_1303788_HW 4 #3.py | 1,012 | 3.5 | 4 | #python2.7
"""
HW 4 #3
-Modify the Newton's method function so that the following
criterion is met: f(x0[i+1]) - f(x0[i]) < eps
@author: scarletpasser
"""
def my_Newton( fct, df_dt, x0, tol = 1e-4, N = 20):
"""
:param fct: - find root of this fct. closes to x0
:param dfct_dt: - derivatice of... |
491246aeefc9928eb6aa128d591164ba11374e4b | pytorch/captum | /captum/influence/_core/influence.py | 1,768 | 3.578125 | 4 | #!/usr/bin/env python3
from abc import ABC, abstractmethod
from typing import Any
from torch.nn import Module
from torch.utils.data import Dataset
class DataInfluence(ABC):
r"""
An abstract class to define model data influence skeleton.
"""
def __init_(self, model: Module, train_dataset: Dataset, *... |
6730f82b4ec7eed3d66ce4ae0864cbd6f2b8189f | jayantmadugula/aspect_detection_models | /absa_code/models/data_preparation.py | 1,598 | 3.734375 | 4 | import pandas as pd
import numpy as np
import math
def prepare_data(data_df, train_test_split, *args):
'''
Randomly splits the data according to the given
`train_test_split` (0.2 means 80/20 train/test split).
Only pandas DataFrames or numpy arrays may be provided
in *args -- the same random spli... |
58f7d7fb937991b505656fd780bdd41e578732c7 | asarfraaz/stylk | /result.py | 729 | 3.953125 | 4 | """This is a doc string
This program will calculate the percentage and grade the student
"""
def get_input():
print 'Marks obtained'
eng=float(raw_input('English'))
sci=float(raw_input('Science'))
math=float(raw_input('mathematics'))
return float(eng), float(sci), float(math)
def ca... |
c61b55bb551ffe99a9e98fffe8f9970fe18ed2b9 | RashikAnsar/everyday_coding | /gfg_python/basic/10_nth_fibonacci.py | 301 | 4.25 | 4 | def nth_fibonacci(n):
lst = [0] * (n+1)
lst[1] = 1
for i in range(2, n+1):
lst[i] = lst[i-1] + lst[i-2]
return lst[n - 1]
if __name__ == "__main__":
n = int(input("Enter n to genterate nth Fibonacci number: "))
print(f"{n}th Fibonacci number is {nth_fibonacci(n)}")
|
12518b537762baa6e30fc9ce3955fbf0ef42d61e | lyh71709/06_Quiz_Quest | /01a_QQ_number_checker.py | 386 | 3.59375 | 4 | # Quiz Quest Component 1 - have an integer checking function
# Int_check Function goes here
def int_check(question):
while True:
try:
response = int(input(question))
return response
# Error message
except ValueError:
print("Please enter an integer\n")
... |
1e0434560d8bb707beccb2c2f2327837a9305c76 | syurskyi/Python_Topics | /125_algorithms/003_stacks_and_queues/_exercises/templates/Cracking Coding Interviews - Mastering Algorithms/balance-parentheses.py | 834 | 3.71875 | 4 | # # Given a string containing just the characters
# # '(', ')',
# # '{', '}',
# # '[' and ']',
# # determine if the input string is valid
#
# # Example 1:
# # Input: "()"
# # Output: true
#
# # Example 2:
# # Input: "()[]{}"
# # Output: true
#
# # Example 3:
# # Input: "(]"
# # Output: false
#
# # Example 4:
# # Input:... |
4d3cc095c7f9ea238955444283e58c378c43fc1e | theturboturnip/GCSE-Computing | /ComputingHomework14_03_11/2 - Find And Replace/findreplace.py~ | 770 | 3.859375 | 4 | #!/usr/bin/env python
import os
path=os.path.split(os.path.abspath(__file__))[0]+"/"
def findreplace(to_look,to_replace,replace_with):
to_look=to_look.replace(to_replace,replace_with)
print to_look
return to_look
def openfile(old_path,new_path,to_replace,replace_with):
oldfile = open(old_path,"r")... |
8e5c36e7c1a9a7e557339a341f1e28d1a7bcb2ad | pangfeiyo/PythonLearn | /甲鱼python/课程代码/第30讲/文件系列:OS模块.py | 3,354 | 3.546875 | 4 | # 模块是一个包含所有你定义的函数和变量的文件,其后缀名是.py。
# 模块可以被别的程序引入,以使用该模块中的函数等功能。
import os
import random
sercet = random.randint(1,10)
print(sercet)
# C:\Users\PangFei\Desktop\Python学习\甲鱼python\课程代码\第30讲
# OS模块
# 返回当前工作目录
print(os.getcwd())
# 改变工作目录,转到D盘下 ch,change
os.chdir('d:\\')
print(os.getcwd())
os.chdir(r'C:\Users\PangFei\Des... |
7a249153a91f6151f824c8e110450e0b479f1d6b | michaelw2002/UG9_B_71210704 | /3_B_71210704.py | 260 | 3.9375 | 4 | Nilai1 = int(input("Nilai 1 : "))
Nilai2 = int(input("Nilai 2 : "))
Nilai3 = int(input("Nilai 3 : "))
#proses
Jumlah_nilai = Nilai1 + Nilai2 + Nilai3
rata_rata = Jumlah_nilai / 3
#print
print("Rata-rata dari",Nilai1,"+",Nilai2,"+",Nilai3,"adalah",rata_rata)
|
f6a38c06f4a7acf3a152b7a3fdac759d24615981 | syurskyi/Algorithms_and_Data_Structure | /The Complete Data Structures and Algorithms Course in Python/src/Section 20 Queue/MultiprocessingQueue.py | 256 | 3.6875 | 4 | # Created by Elshad Karimov on 31/05/2020.
# Copyright © 2020 AppMillers. All rights reserved.
# How to use multiprocessing.Queue as a FIFO queue:
from multiprocessing import Queue
customQueue = Queue(maxsize= 3)
customQueue.put(1)
print(customQueue.get()) |
31a3117f211fe2aaad4a2dc255db4db8710a8068 | rimys/L5 | /main.py | 181 | 3.875 | 4 | import fibonach
print(fibonach.my_add(3,8))
# (f_n)^2 + (f_{n+1}^2 = f_{2n+1}
n = 5
print(fibonach.fib_num_l(n)**2 + fibonach.fib_num_l(n+1)**2)
print(fibonach.fib_num_l(2*n+1)) |
01cf5b7791f40e0bc6e9be27ac94c1da1c188d6f | leozheng08/Machine_Learning-project | /Assignment 1/itemsets.py | 853 | 3.796875 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sun Feb 17 16:37:00 2019
@author: zhengleo
"""
datalist = ['A','B','C','D','E','F','G']
length = len(datalist)
totalItemset = []
def recurrsion(array):
for i in range(length):
for j in range(i,length):
data = []
for k ... |
4dae2c50901e7d28b8feaec65d061cb3a44a7e4e | Beadsworth/ProjectEuler | /src/solutions/Prob2.py | 604 | 3.96875 | 4 | import math
def make_fib(max_number):
fib_list = [1,2]
add_1 = 1
add_2 = 2
sum_1_2 = add_1 + add_2
while sum_1_2 <= max_number:
fib_list.append(sum_1_2)
add_1 = add_2
add_2 = sum_1_2
sum_1_2 = add_1 + add_2
return fib_list
def make_even(number_list):
eve... |
be24fa73ec6a42b125dfc0e33d167d9c29df1236 | aiifabbf/leetcode-memo | /707.py | 5,359 | 4.09375 | 4 | """
实现链表
不用看答案就知道最快的肯定是直接用py的list……
但是为了真正学会算法和数据结构,我这里还是认真了一下,写了个真链表。
"""
from typing import *
class MyLinkedList:
class ListNode:
def __init__(self, val):
self.val = val
self.next = None
def __init__(self):
"""
Initialize your data structure here.
... |
79cec2c0b45f19d41fd935552b5a5bf3fc23dc8d | cami-la/python_curso_em_video | /Mundo03:estruturas-compostas/exercicio-python#110-reduzindo-ainda-mais-o-seu-programa/operations.py | 1,065 | 3.78125 | 4 | def half(value=0, formated=False):
res = value / 2
return res if not formated else format_currency(res)
def double(value=0, formated=False):
res = value * 2
return res if not formated else format_currency(res)
def increase(value=0, tax=0, formated=False):
res = value * (tax / 100 + 1)
return... |
938b7a3606d93e2d6ab973d7d8066bca3dfe109c | sunoonlee/checkio | /number-radix.py | 773 | 3.828125 | 4 | """better: int(str_, base)"""
def char2digit(char):
if "0" <= char <= "9":
return int(char)
if "A" <= char <= "Z":
return ord(char) - ord('A') + 10
def checkio(str_number, radix):
result = 0
position = 0
for char in str_number[::-1]:
digit = char2digit(char)
if dig... |
201dac63b413a50dfff0fb51d6a4d21a532921a4 | ee08b397/datastructures | /trees/binarytree/node.py | 1,220 | 3.65625 | 4 | class Node:
BLACK = "BLACK"
RED = "RED"
def __init__(self, value='unset', leftNode=None, rightNode=None, parent=None, color = None, size = None):
self.value = value
self.setParent(parent)
self.setLeft(leftNode)
self.setRight(rightNode)
self.size = size
self.c... |
5417e1372dd9372e744b6fca59ac10fdf19b8e86 | qmnguyenw/python_py4e | /geeksforgeeks/python/hard/2_20.py | 1,099 | 4.0625 | 4 | Horizontal Boxplots with Seaborn in Python
**Prerequisite:** seaborn
The Boxplots are used to visualize the distribution of data which is useful
when a comparison of data is required. Sometimes, Boxplot is also known as a
box-and-whisker plot. The box shows the quartiles of dataset and whiskers
extend to ... |
594ede01e4717832048dda3d00a12d9965e2eb46 | thusyasin/aran | /anagrams.py | 464 | 3.5 | 4 | def main():
a=[]
arr=[]
new=[]
count=0
n=int(input())
for i in range(n):
b=input()
a.append(b)
for i in range(len(a)):
b=''.join(sorted(a[i]))
arr.append(b)
if n==1:
print(1)
else:
for i in arr:
x=arr.count(i)
if... |
b2f943031047d942db33ad68b4575f91f45f9ed8 | ShivDj/Python_Basic | /Excercise/finding the minimum and maximum value from given arthimatic operation.py | 889 | 3.96875 | 4 |
"""
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
* Purpose: finding the minimum and maximum value from given arthimatic operation
* @author: Sheevendra Singh Singraul
* @version: 3.8.6
* @since: 19-03-2021
*
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++... |
df442e4984101985f0f8e8281ee49143e659027c | henkjeebee/Python3 | /Exercise 7.1.py | 258 | 3.875 | 4 | filename = input("Which file would you like to open: ")
try:
filehandle = open(filename)
except:
print("File cannot be opened ", filename)
exit()
inp = filehandle.read()
for line in inp:
line = line.rstrip()
caps = inp.upper()
print(caps)
|
1b4d8a14eb5d0e494252dbc9be7fddb172a1af9b | hellomansour/python_work | /Chapter 9/favorite_languages.py | 322 | 3.828125 | 4 | #favorite_languages.py
from collections import OrderedDict
favorite_languages = OrderedDict()
favorite_languages = {
'jen': 'python',
'sarah': 'c',
'edward': 'ruby',
'phil': 'python',
}
for name,value in favorite_languages.items():
print(name.title() + "'s favorite language is " + value.title())
print('\n')... |
9be24cc77f92b9d6241e890a5d0ad2300687ec58 | ViktorKovinin/ds_python | /1.syntax/2.if_else.py | 1,102 | 4.15625 | 4 | # условные операторы
# a = 10
# if a == 5:
# c = "Равно 5"
# elif a == 4:
# c = "равно 4"
# elif a == 3:
# c = "равно 3"
# elif a == 2:
# c = "равно 2"
# else:
# c = "ничему не равно "
# b = - 1
# if b < 10 and b > 0:
# c = " 0 < b < 10 "
# #elif b > 0:
# # c = "> 0 "
# else:
#... |
c5f6e759f2ba5ddc7cc9790655204e468f89ccf8 | hahaliu/LeetCode-Python3 | /172.factorial-trailing-zeroes.py | 594 | 3.59375 | 4 | # ex2tron's blog:
# http://ex2tron.wang
# 别人的代码:
class Solution:
def trailingZeroes(self, n):
result = 0
while n > 0:
result += n // 5
n //= 5
return result
# class Solution:
# def trailingZeroes(self, n):
# """
# :type n: int
# :rtype... |
cd4c4235a05c0922b53974210f38df13bf96e99c | MrViniciusfb/Python-Crash-Course | /Parte 5/Exercícios/if_5.7.py | 423 | 3.796875 | 4 | #21/07/2021
fruits = ['abacaxi','morango','tangerina']
if 'abacaxi' in fruits:
print('\nVocê realmente gosta de abacaxi!')
if 'pera' in fruits:
print('\nVocê realmente gosta de pera!')
if 'morango' in fruits:
print('\nVocê realmente gosta de morango!')
if 'carambola' in fruits:
print('\nVocê realmente ... |
2e8b1681cff972b43d32d4cf3b7e3b04a319b3e3 | IvayloSavov/Programming-basics | /exams/20_21_april/easter_guests.py | 1,304 | 3.75 | 4 | from math import floor
# 1. Read input data
income = float(input())
average_grade = float(input())
min_salary = float(input())
excellent_scholarship = False
social_scholarship = False
# 2. Scholarship
# 2.1 social scholarship
if income < min_salary and average_grade > 4.5:
social_scholarship = True
social_scho... |
a8c71f19b075d57d5371c0e9a2a1677ce96f8242 | okayjones/data-structures-and-algorithms | /python/challenges/breadth_first/breadth_first.py | 513 | 4.25 | 4 | def breadth(tree) -> list:
"""Returns a breadth ordered list of binary tree values
Args:
tree (BinaryTree): Instance of BinaryTree
Returns:
list: list of values
"""
queue = []
result = []
if tree.root:
queue.append(tree.root)
while queue:
current = queue... |
1b47d3e34c3b968c07dd4695b3344dbda3449247 | bste1220/algorithm | /Do it python/chap01/median3a.py | 478 | 4.3125 | 4 | # 세 정수를 입력받아 중앙값 구하기 2
def med3(a, b, c):
if (b >= a and c <= a) or (b <= a and c >= a):
return a
elif (a > b and c < b) or (a < b and c > b):
return b
return c
print('세 정수의 중앙값을 구합니다')
a = int(input('정수 a 의 값을 입력하세요'))
b = int(input('정수 b 의 값을 입력하세요'))
c = int(input('정수 c 의 값을 입력하세요'))
pr... |
b1575a54627f429eb1c329cee09044c17c0654ce | eemets/Python-labs | /1/2.py | 191 | 3.875 | 4 | n = input("Введите трехзначное число: ")
n = int(n)
d1 = n % 10
n = n // 10
d2 = n % 10
n = n // 10
d3 = n % 10
print("Сумма цифр числа:", d1 + d2 + d3) |
ae8b07886fa2dfa052ffd8a76865158ee70ef6eb | shivangstreak/comp | /DesignPatterns/FactoryPattern/abstract_factory.py | 1,645 | 3.765625 | 4 | from abc import ABC, abstractmethod
class IButton(ABC):
def __init__(self):
pass
@abstractmethod
def press(self):
pass
class MacButton(IButton):
def __init__(self):
super().__init__()
def press(self):
print("This is a Mac Button")
class WindowsButton(IButton... |
960ede12b0a31fcb4f23c3f0450006d9f6771d6e | laxur1312/py4e | /ex_11_02.py | 603 | 3.578125 | 4 | # Este programa busca ciertos elementos en un archivo, extrae los números y
# promedia todos los números que cumplen con el criterio.
import re
lista=list()
fname=input('Enter file: ')
if len(fname)<1: fname='mbox.txt'
try:
fhandle=open(fname)
except:
print('File not found.')
exit()
for... |
f6cca83cd686970c2ea7013a24000619fa84f78a | bibongbong/pythonCookBook | /src/4.14.OpenNestSequ.py | 565 | 3.84375 | 4 | '''
问题:将一个多层嵌套的序列展开成一个单层列表
方案:yield from
'''
from collections import Iterable
items = [1, 2, [3, 4, [5, 6], 7], 8]
items1 = ['Dave', 'Paula', ['Thomas', 'Lewis']]
# ignore_types=(str, bytes) 是为了防止过度展开成单个字符
def openNestSeq(items, ignore_types=(str, bytes)):
for item in items:
if isinstance(item, Iterable) and not i... |
66785b4fb388ad0ba0f93cff4b58c9e48b3724b0 | Pollob001/Network | /Buffer1/Buffer.py | 2,427 | 3.78125 | 4 | class CircularBuffer(object):
def __init__(self, max_size):
self.buffer = [None] * max_size
self.head = 0
self.tail = 0
self.max_size = max_size
def __str__(self):
items = ['{!r}'.format(item) for item in self.buffer]
return '[' + ', '.join(items) + ']... |
f5f24fadae78929801ebc5fdceb2bb7ab91794a3 | vivekpisal/Dstructure | /dstructure/Graph.py | 1,566 | 4.1875 | 4 | class Graph:
def __init__(self):
self.edges={}
def insert(self,x,y):
"""
x,y: Insert the nodes using x,y
"""
try:
if self.edges[x] or self.edges[y]:
self.edges[x].add(y)
self.edges[y].add(x)
except:
try:
if self.edges[x]:
self.edges[x].add(y)
except:
self.edges[x]=set([y])
... |
2ae017fc6c769cd10290b06627b5575de85bdcea | KyleSMarshall/30-Day-LeetCoding-Challenge | /Day 09 - Backspace String Compare.py | 957 | 4.125 | 4 | '''
Given two strings S and T, return if they are equal when both are typed into empty text editors. # means a backspace character.
Note that after backspacing an empty text, the text will continue empty.
Ex:
Input: S = "ab#c", T = "ad#c"
Output: true
Explanation: Both S and T become "ac".
'''
# Solution
class Solu... |
15a769552e3de2761fa194331625267dac2db186 | vlaksi/OsnovneRacunarstva-BMI | /Predavanja/07 Petlje i logicìki izrazi/Predavanja/primeriSaPredavanja/primer11.py | 275 | 3.5625 | 4 | # za dve tacke proveri da li su jednake
p1 = (4, 1, 3)
p2 = (1.5, 3, 2)
if p1[0] == p2[0]:
if p1[1] == p2[1]:
if p1[2] == p2[2]:
print('tacke su jednake')
else:
print('nisu')
else:
print('nisu')
else:
print('nisu') |
ccec54069aea59f6dd5fad999b1709e672705fb4 | cravo123/LeetCode | /Algorithms/0045 Jump Game II.py | 1,449 | 3.625 | 4 | # Solution 1, Breadth-First-Search
class Solution(object):
def jump(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
left, right = 0, 0
n = len(nums)
tmp = right
steps = 0
for i in range(n):
tmp = max(tmp, i + nums[i]... |
bb7463d1f5f43f1e65d071655e2c2be2a7f16557 | yugov/tceh_homeworks | /homework4/homework4_1.py | 1,211 | 4.25 | 4 | #Реализовать класс Person, у которого должно быть два публичных поля: age и name. Также у него должен быть
# следующий набор методов: know(person), который позволяет добавить другого человека в список знакомых.
# И метод is_known(person), который возвращает знает ли знакомы ли два человека
class Person(object):
... |
fb0a0d489f15bcfc5c0652939e886b75c11bc5dd | itsdeepesh5/PythonProblems | /rege.py | 171 | 3.578125 | 4 | import re
str=" 2asd sad"
pattern=r"\b[0-9]+"
m=re.match(r'([ ]*)(?P<name>[+-]?[0-9]+)(\D*)', str)
#print("Deepesh", pattern, str)
if m:
print(m.group('name'))
|
b20a73a66215ee2dccaa2e6c5a568af9d8b9f9e4 | cyberkuv/tick-tack-toe | /tick-tack-toe.py | 3,384 | 3.59375 | 4 | import os
empt_board = {
'1': ' ', '2': ' ', '3': ' ',
'4': ' ', '5': ' ', '6': ' ',
'7': ' ', '8': ' ', '9': ' '
}
board_keys = []
for key in empt_board:
board_keys.append(key)
def opt_board(board):
clear = lambda: os.system('clear')
clear()
print('\u001b[32m'+board['1'] + '|' + board['... |
c4a2b5df2fe32afee9e4a40af94e6de55d819193 | plainspooky/giovannireisnunes | /usando-arquivos-csv-em-python/read_csv_file_as_dict.py | 422 | 3.90625 | 4 | #!/usr/bin/env python3
"""
Lê um arquivo CSV para um dicionário.
"""
from csv import DictReader
from json import dumps
# arquivo de entrada
STUDENTS_FILE = "students.csv"
if __name__ == "__main__":
# carrega todas as linhas do arquivo CSV
with open(STUDENTS_FILE, "r") as f:
students = [record for rec... |
f99949f9704f0a2b696c9dbfa9f69626dc470149 | AbidelLux/Matriz-Dispersa-Proyecto-Junio-2020 | /matriz_cont.py | 1,441 | 3.515625 | 4 |
class matriz_cont():
def __init__(self)-> None:
self.head = None
self.siguiente = None
self.anterior = None
self.arriba = None
self.abajo = None
def insertarx(self,posx,posy,listaCabeza,nuevoNodo):
listax = listaCabeza.cabX
while listax is not None:
... |
6589164ccf72c64dcbec12ef047323e16862afe4 | pgThiago/first-code | /aprendendo.py | 130 | 3.640625 | 4 | day = input ('day=')
month = input ('month=')
year = input ('year=')
print ('você nasceu no dia', day, 'de', month, 'de', year)
|
d052d6fb57e1cb3120f22c267ea0f95be313b5f5 | WinEga/PythonPlayground | /Loops/ifElse.py | 224 | 4.15625 | 4 | number = int(input("Enter any integer number "))
if number == 10:
print("Entered number is Equal to 10")
elif number < 10:
print("Entered number is Less than 10")
else:
print("Entered number is Grater than 10")
|
680180060d932b08700fb8e33323bf463d696671 | mooncrest/AdventOfCode2019 | /Q1/Part1.py | 158 | 3.515625 | 4 | def calculateFuel(fuel):
return fuel // 3 - 2
if __name__ == "__main__":
file = open("input.txt")
print(sum(calculateFuel(int(fuel)) for fuel in file))
|
36df956da2c3f48ad3a8f1892c9b5180be150a30 | annatoja/Advent-Of-Code | /1_1_19.py | 308 | 3.546875 | 4 | numbers = []
with open("1.in", "r") as f:
data = f.readlines()
for i in range(len(data)):
numbers.append(int(data[i].strip("\n")))
def fuel_counter(num):
fuel = num // 3 - 2
return fuel
result = 0
for i in range(len(numbers)):
result += fuel_counter(numbers[i])
print(result)
|
cf4d5153a9ea861ce94184920da597b6dcdf01de | PhilippePego95/eclipse-espaiTreball | /EI1003/Prac3/ej23.py | 757 | 3.65625 | 4 | respostes=input("Introduce la plantilla de respuestas correctas: ")
print("Ve introduciendo respuestas de alumnos, o vacío para acabar...")
resp="**"
cont=0
while len(resp)>0:
resp=input("Nuevas respuestas: ")
be=0
mal=0
ns=0
if len(resp)==len(respostes):
for i in range(0,len(resp)):
... |
cf84dd02e7ef7f585f8329c4b2a0125384b55b02 | HellyVora0802/DCS-BBN_HELLY | /code_try/try3.py | 1,621 | 4.09375 | 4 | '''here the code and program is same as bchai try copy 1
but we arent giving the first element directly into list instesd
we are adding last_transaction in add_value to have more better versatility of the code
now here we can give last_tansaction a kind of default value which is [1]
'''
blockchain = []
def get_last... |
af99c2f6b004f6e5d27e4d2a8823d4ee0d12612e | hncpr1992/Practice-Python | /queue/main.py | 299 | 3.828125 | 4 | from queue import queue
def main():
myQueue = queue()
element = [2,1,2,3,1]
# enqueue
for i in element:
myQueue.enqueue(i)
print(myQueue)
# dequeue
for i in element:
myQueue.dequeue()
print(myQueue)
if __name__ == "__main__":
main() |
1bfcbb4f008a9eae3a09c47197004ee48c26d46e | Myfour/Python_Basic | /algorithm/single_linked_list.py | 1,076 | 4.3125 | 4 | '''
输出单链表
'''
# 由两个list组成的单链表
listValue = [1, 5, 6, 2, 4, 3] # 每一个元素的值
listPointer = [3, 2, -1, 5, 1, 4] # 每个元素中指向下一个元素的地址
head = 0
print(listValue[head])
next = listPointer[head]
while next != -1:
print(listValue[next])
next = listPointer[next]
# 嵌套list组成的单链表
print('-----------------------------------------... |
e884103f4d22dcc5b0db655f88dc1e030232940a | adamshaul1/Crew-Email-Parser | /ftpConnection.py | 1,946 | 3.578125 | 4 | #################################################################################
# ftpConnection
#
# - Class file that connects to the ftp server and uploads all the contents
# of a folder
#
#################################################################################
import ftplib
import os
import getpas... |
84c086582906c29371a8650fd2f174605ca7beab | Nikame/Udemy-Abid-Malik-python-scripting | /100DaysOfCode/04-06-defaultdict.py | 420 | 4.34375 | 4 | from collections import defaultdict
# defaultdict: Default 'value' of dictionary 'key' if that does not exists
somedict = {}
#somedict[3] # KeyError
#output: KeyError: 3
# Note: Since key 3 does not exist, we get error
somedict = defaultdict(int)
somedict[3]
print(somedict)
#output: defaultdict(<class 'int'>, {3: 0})... |
93c4531cfd1db2d0d2ec77c430f53f68ed72cf76 | Qondor/Python-Daily-Challenge | /Daily Challenges/Daily Challenge #15 - Stop gninnipS My sdroW!/word_spinner.py | 496 | 4.09375 | 4 | def word_spinner(input_words):
"""Word spinner.
Takes a string and reverses words that are 5 characters long or longer.
"""
input_words = input_words.split()
reversed_list = []
for word in input_words:
if len(word) >= 5:
reversed_list.append(f"{word[::-1]:}")
else:
... |
d1c8e6df0c2a44e543b879dcfcee89a2f77557ba | NishadKumar/interview-prep | /dailybyte/strings/longest_substring_between_characters.py | 1,874 | 4.21875 | 4 | # Given a string, s, return the length of the longest substring between two characters that are equal.
# Note: s will only contain lowercase alphabetical characters.
# Ex: Given the following string s
# s = "bbccb", return 3 ("bcc" is length 3).
# Ex: Given the following string s
# s = "abb", return 0.
# Approach:
#... |
5972acb9ee057ece14ae5f4f3494145b3a6d7663 | Slothfulwave612/Coding-Problems | /Cracking The Coding Interview/02. Array and Strings/02. Example_Page_91/string_compression.py | 985 | 4.65625 | 5 | '''
String Compression: Implement a method to perform basic string compression using the counts
of repeated characters. For example, the string aabcccccaaa would become a2b1c5a3. If the
"compressed" string would not become smaller than the original string, your method should return
the original string. You can assume t... |
708cd5de1e15e1395d153238d7936f45d7d88985 | denissemo/Labs | /Laba_9_GitHub/sorting_test.py | 16,259 | 3.828125 | 4 | # Семенов Денис КНІТ 16-А
"""программа для теста алгоритмов"""
import numpy as np
from time import time
def bubble_sort(n, a, c):
""" Пузырьковая сортировка.
:param n: длина массива
:param a: массив, который необходимо отсортировать
:param c: выбор направления сортировки
:return: число сравн... |
4d110665b45485f011ce66fe726a622515ad5a16 | Aditya-A-Pardeshi/Coding-Hands-On | /4 Python_Programs/Programs to demo python concepts/decorator1.py | 320 | 3.8125 | 4 | # Inbuild function from module(we consider as)
def substraction(no1, no2):
return no1 - no2
def main():
no1 = int(input("Enter the first number:"))
no2 = int(input("Enter the second number:"))
ret = substraction(no1, no2)
print("The substraction is:", ret)
if __name__ == "__main__":
main()
|
9527277020b8976c1682136f0f6d3bdee094f02c | priyankataware23/DataStructuresAndAlgorithms | /a1_DS/Session9_Stack/TimeFunctions.py | 2,389 | 3.8125 | 4 | '''
https://leetcode.com/problems/exclusive-time-of-functions/
On a single threaded CPU, we execute some functions. Each function has a unique id between 0 and N-1.
We store logs in timestamp order that describe when a function is entered or exited.
Each log is a string with this format: "{function_id}:{"start" |... |
f7b01f3ff3dfb0154afdcc06767e2db59cea04c8 | abendm/Pandas-Stuff | /04-EDA-Practice-Review-master/ball_help.py | 2,744 | 3.515625 | 4 | def rename_cols(input_df):
input_df.rename(columns = {3: 'Visiting Team', 6: 'Home Team', 9: 'Runs Visitor', 10: 'Runs Home'}, inplace=True)
return input_df
def add_new_cols(input_df):
input_df['Home Win'] = (input_df['Runs Home'] > input_df['Runs Visitor'])
input_df['Visitor Win'] = (input_df['Runs V... |
e2d9a93498102295832dbbffe73b75aa12b3ec2c | deeksha567/Twowaits | /Day1 program2.py | 86 | 3.828125 | 4 | print("Enter the number: ")
s=int(input())
t=s**(0.5)
print("The square root is ", t)
|
f0e26d1e9048a04de5ce27c477ff0a6172d3fa40 | SirSamuelBiczo/TP-TicTacToe | /main.py | 4,899 | 3.890625 | 4 | #coding: utf-8
import random
HUMAIN = 'X'
ORDI = 'O'
VIDE = ' '
T_PLATEAU = 3
def init_plateau():
"""
rien -> liste de liste
Retourne un plateau de jeux vide
"""
plateau = []
for i in range(T_PLATEAU):
plateau.append([' ', ' ', ' '])
return plateau
def print_tableau(plateau... |
3072ecf2e9e55225311deb4713d3f6038264c6a0 | mayurim20/Pythonlab | /sumdigit.py | 114 | 3.875 | 4 | a=int(input("enter a number"))
s=0
while(a>0):
r=a%10
s=s+r
a=a//10
print("sum of digits is ",s)
|
9d3e05fe3b52c028eadd4a68a66694350d26e9df | SunnyRo/Python | /Machine Learning/KNN/KNN.py | 1,989 | 3.5 | 4 | import pandas as pd
import numpy as np
import math
from sklearn.model_selection import train_test_split
# to prevent dont have really large bias number
from sklearn.preprocessing import StandardScaler
# knn tool
from sklearn.neighbors import KNeighborsClassifier
# for testing
from sklearn.metrics import confusion_ma... |
43c15d612c751f9b57680cad356057890c4a68ad | ksulli123/2810ICT | /word_ladder.py | 6,899 | 4.0625 | 4 | import re
import queue
# Function for returning how many letters item & target have in common
def same(item, target):
<<<<<<< HEAD
# Adds character 'c' to a list if it is the same letter as 'f', it then returns the number of common letters
=======
if len(item) != len(target):
print("words not same len... |
286d7e48ce3b9d068ded751dd5f9a02dbfa999e2 | eerpini/fall2010-variational_bayesian_classification-data_extraction_scripts | /binned_random_classification.py | 3,118 | 3.9375 | 4 | #this program simulates random assignment of class labels to the data
#and checks for errors, for example for 20 classess the expected error
#should be around 95%, since the classification is random, no training
# is required, we can run the simulation directly on certain slices of test
# data.
# arg1 : label_count.tx... |
78fa548390a818f2ea1630d9a5fcd60e7bc537e5 | Guruscode/getting-started-with-python | /data-types/list.py | 5,326 | 4.40625 | 4 | # list is a collection of any data type.
# list literal
a = [1, 2, 3, 4, 5]
print(a)
# using list function
a = list({1, 2, 3, 4, 5})
print(a)
# list of different data types
a = [ 1, 3.14, "string", True, [1,2,3] ]
print("different data types =", a)
# length of a slice
a = [1, 2, 3, 4, 5]
b = len(a)
print( 'len(a) =... |
96f458e9759f6c56ad30809b15abf7030641711a | frankieliu/problems | /leetcode/python/126/126.word-ladder-ii.py | 2,862 | 3.703125 | 4 | #
# @lc app=leetcode id=126 lang=python3
#
# [126] Word Ladder II
#
# https://leetcode.com/problems/word-ladder-ii/description/
#
# algorithms
# Hard (16.71%)
# Total Accepted: 106.9K
# Total Submissions: 640.1K
# Testcase Example: '"hit"\n"cog"\n["hot","dot","dog","lot","log","cog"]'
#
# Given two words (beginWord... |
363aaa2dcda099f20a8696586d5d4fcc1ad0f4cf | sainikunal/attendance_reminder | /section.py | 1,287 | 3.515625 | 4 | from xlrd import open_workbook
def get_sections():
"""
Return a dictionary with Days as keys and no. of sections
to teach(on that day) as a list
"""
# src = 'C:\\Users\\Program Files\\rptTimeTableFaculty.xls'
src = '/home/mama/Desktop/FacultyUms/rptTimeTableFaculty.xls'
book = op... |
b10bf8ca015357e6f52dd2c718d2fa7afeed6419 | nshadov/cryptolib | /cryptolib.py | 1,218 | 4.46875 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Basic primitives for cryptography and cryptoanalysis tools.
"""
from itertools import izip
def pairwise(iterable):
"""
Converts string to list of pairs of consecutive symbol pairs.
example:
"The quick brown fox" => ['Th', 'e ', 'qu', 'ic', 'k ', ... |
9aca8212f8743909885d84908b2097b38eb5f6b1 | DmitryPukhov/pyquiz | /pyquiz/leetcode/AlienDictionary.py | 1,911 | 4.15625 | 4 | import collections
from collections import defaultdict
from typing import List
class AlienDictionary:
"""
There is a new alien language that uses the English alphabet. However, the order among letters are unknown to you.
You are given a list of strings words from the dictionary,
where words are sorted... |
f8cb27410220e6bdef44d53b3b8464ceb85a87f5 | joshuakim314/math_tools | /matrix.py | 18,662 | 3.96875 | 4 | # HEADER
# Note: Indices of rows and columns commences from 0 and ascend with an increment of 1.
# Remember to write up all error statements for each False return.
# Remember to write up Crammer's method.
from typing import List
from number_tools import *
class Matrix:
def __init__(self, row: int, col: int, dat... |
098d1ef801ae691f481ade6777810c5de121e26d | BhargavVemula/python-basic | /variables.py | 214 | 3.78125 | 4 | class Car:
wheels = 4
def __init__(self):
self.mil = 10
self.com = "BMW"
c1 = Car()
c2 = Car()
c1.mil = 8
Car.wheels = 5
print(c1.mil, c1.com, c1.wheels)
print(c2.mil, c2.com, c2.wheels)
|
f7a4b72b416da812296f1b54d23738ad8a390668 | lhd0320/AID2003 | /official courses/month01/day09/exercise05.py | 733 | 3.8125 | 4 | # ma = int(input("请输入心理年龄:"))
# ca = int(input("请输入实际年龄:"))
# iq = ma / ca * 100
# if iq >= 140:
# print("天才")
# elif iq >= 120:
# print("超常")
# elif iq >= 110:
# print("聪慧")
# elif iq >= 90:
# print("正常")
# elif iq >= 80:
# print("迟钝")
# elif iq >= 0:
# print("低能")
# else:
# print("数值错误!")
... |
313cde9f00b095d4aba40fd8101fa787e52a8dbf | shivanitalekar29/Python_Project | /readfile_lbl.py | 192 | 4.21875 | 4 | #Write a Python program to read a file line by line and store it into a list
f = open("demofile.txt","r")
for x in f:
print(x)
a=f.readlines()
b=list(f)
print(type(a))
print(type(b))
|
6b7b37ff29527a5673b8406784a37da1f3a459f9 | VaishnavJois/python_ws | /day1/first_N_prime.py | 362 | 4.0625 | 4 | '''Program to check prime or not'''
def is_prime(num):
if num < 2:
return False
for j in range(2,num//2+1):
if num%j == 0:
return False
return True
num = int(input('Enter number of prime'))
i=2
c=0
while True:
if is_prime(i):
print(i)
c+=1
... |
97c3a669dc300c1f10741f5aadf72cf98077fca0 | stevey1/try-python | /algorithms/math/permuation.py | 479 | 3.8125 | 4 | def Permutation (arr,m):
n=len(arr)
indices=[j+1 for j in range(m)]
i=m-1
while True:
while indices[i]>n:
indices[i]=i+1
i-=1
if i< 0: return
indices[i]+=1
arr[i:]=arr[i+1:]+arr[i:i+1]
else:
i=m-1
print(arr[0... |
74abb678a7dcc12cd46e9f08714b13bb4df9b088 | xzguy/LeetCode | /Problem 101 - 200/P109.py | 2,476 | 4.15625 | 4 | # Definition for singly-linked list.
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
# Definition for a binary tree node.
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = ... |
fd53bc7083c8fc15e4771e1e6d7d9c751c90642f | Hkoval/PythonHomework | /final_task/pycalc/difcalc.py | 4,793 | 3.671875 | 4 | import re
import pycalc.easyCalculation as easyCalculation
import math
from numbers import Number
class ComplexCalc(easyCalculation.Calculator):
"""more functional calculator than "Calculator" """
def __init__(self):
"""initializing data from "math" """
ComplexCalc.const = {
**{at... |
6ad19ddcde59e224e8b1b9f4176e1b36458c43ec | jianshen92/advent-of-code-2020 | /day_03/solution_1.py | 220 | 3.59375 | 4 | with open("data", "r") as f:
data = f.read().splitlines()
pattern_length = len(data[0])
start = 0
count = 0
for row in data:
if row[start % pattern_length] == "#":
count += 1
start += 3
print(count) |
eede2471b39ef2e4bad3014fd57b6ec2bcfce096 | yanglt7/programTest | /47.py | 342 | 3.6875 | 4 | '''
求1+2+3+...+n,要求不能使用
乘除法、for、while、if、else、switch、case等关键字及条件判断语句(A?B:C)。
'''
'''
'''
# -*- coding:utf-8 -*-
class Solution:
def Sum_Solution(self, n):
# write code here
ans = n
if ans:
ans += self.Sum_Solution(n-1)
return ans |
bacdee18df909be8cafff7541a67e783cb128f0e | tejashinde/.py | /Practice/num_denom.py | 461 | 3.59375 | 4 |
dict = {}
try:
for n in range (100,1000):
for d in range(100,1000):
nstr = str(n)
dstr = str(d)
if(int(dstr[-1]) == 0):
continue
if(int(nstr[0])/int(dstr[-1]) == n/d):
print("%s / %s = %f" % (nstr,dstr,(n/d)) + " and " + "%d ... |
e0de0a1395764e4f3658f348cff546f54ada76d2 | yusrilarzaqi/Tips-Trick | /12.py | 491 | 3.65625 | 4 | ###################################################
# CONVENTIONAL WAY
###################################################
nama = ['bejo', 'karti', 'tejo']
usia = [23, 31, 26]
listku = []
for i in range(len(nama)):
listku.append([nama[i], usia[i]])
print(f'listku={listku}')
########################################... |
b9031b3a0929517d1febf419dc4a3895a0e14d09 | skywalkermml/Sokoban_agent | /tree.py | 2,159 | 3.765625 | 4 | #Author:Joshua Wang, date :10/24 2013
#The data structure of the tree,
import sys
from collections import defaultdict
#Amazing tree structure. reference: https://gist.github.com/hrldcpr/2012250
def treestru(): return defaultdict(treestru)
class node(object): # class of a node
def __init__(self, state):
self.p... |
81eafabe05a329ff3e2a77dfe9880533f06026bd | DPNT-Sourcecode/CHK-srwb01 | /test/solution_tests/SUM/test_sum.py | 1,200 | 3.6875 | 4 | from solutions.SUM import sum_solution
from unittest import TestCase
class TestSum(TestCase):
def test_sum(self):
""" vanilla case """
self.assertEqual(sum_solution.compute(1, 2), 3)
def test_out_of_bounds_s1_s2(self):
""" both smaller than bounds """
with self.assertRaises(... |
c4d59ada7326798d05763c7fa6d06ea30691e678 | KenjaminButton/runestone_thinkcspy | /16_recursion/16.5.visualizing_recursion.py | 5,066 | 4.875 | 5 | # 16.5 Visualizing Recursion
'''
Some problems are easy to solve using recursion; however, it can still be difficult to find a mental model or a way of visualizing what is happening in a recursive function. This can make recursion difficult for people to grasp. In this section we will look at using recursion to draw so... |
02aab115b3f392242f6b39bfe1f2f9db6789259a | sethdeane16/projecteuler | /112.py | 1,373 | 3.734375 | 4 | import resources.pef as pef
import time
import math
"""
https://projecteuler.net/problem=112
5.284278869628906
"""
def main():
cntBncy = 0 # count of numbers that are bouncy
i = 0 # current number to test for bounciness
percentBncy = 0 ... |
ec83e566d5885dcd661d54977a25a2081caa3655 | manji369/Geeks4GeeksTop80InterviewQs | /Python/q38interpolationSearch.py | 1,528 | 3.75 | 4 | '''
38. Given a sorted array of n uniformly distributed values arr[], write a function
to search for a particular element x in the array.
Linear Search finds the element in O(n) time, Jump Search takes O(√ n) time and
Binary Search take O(Log n) time.
The Interpolation Search is an improvement over Binary Search for i... |
bdea7482e525a05da7abf67e967b12fdc1fc7bde | dakaii/udacity | /introToInferentialStatistics/lesson7/mean_and_sd.py | 647 | 3.859375 | 4 | import pandas as pd
import math
xl = pd.ExcelFile('Klout scores (Lesson 7).xlsx')
df = xl.parse(xl.sheet_names[0])
print('pandas calculates the mean value to be: ' + str(df.mean()))
print('pandas calculates the standard deviation to be: ' + str(df.std()))
sheet1 = xl.parse(0)
sum = 0
for i in range(len(sheet1)):
s... |
0a6dadb85f724c3ab0b8fd9e0fa437684769db25 | sharonkim/OnlinePython_Lectures | /AJAX_OOP/PersonOOP.py | 576 | 3.765625 | 4 | class Person(object):
def __init__(self, name, age):
self.name = name
self.age = age
self.stamina = 100
def walk(self):
self.stamina -= 1
def talk(self):
print "{} habla espanol un poco".format(self.name)
person1 = Person('Michael', 30)
person1.talk()
class Coder(Person):
def __init__(se... |
8752cf69e52e445dc96ac9caf2a2a24c6b6aaf8d | Vigyrious/python_fundamentals | /Dictionaries-More-Exercises/Judge.py | 1,152 | 3.640625 | 4 | dect_languages = {}
command = input()
while command != "no more time":
name, language, points = command.split(" -> ")
if language not in dect_languages:
dect_languages[language] = {}
if name not in dect_languages[language]:
dect_languages[language][name] = int(points)
else:
if in... |
ad0fa4db8e33b9d7997cc6b267157674bd4bbb28 | voicezyxzyx/python | /Exercise/函数/yx_17_杨辉三角.py | 719 | 3.625 | 4 | def triangel(n):
L=[1] #定义一个list[1]
while True:
yield L #打印出该list
L=[L[x]+L[x+1] for x in range(len(L)-1)] #计算下一行中间的值(除去两边的1)
L.insert(0,1) ... |
7529a84ffbed3f6ac50239c24322e3d53b7658a1 | sjojoh/cs1113-fall15 | /code/python/example.py | 700 | 3.890625 | 4 | #assinment commands
#{}
#x = 5
#{(x,5)}
#y = 6
#{(x,5),(y,6)}
#conditions
#or apply to two arguments
#if(x > 0):
# x = 0
# z = 10
#else:
# x = 1
# z = 11
#iteration
#times = 10
#while (times > 0):
# print ('Hello')
# times = (times - 1)
#procedures and procedure call
#def fun(a, b, c, x):
# resu... |
57d3d680ca417ab2db73d60fe2d7ca19a27b6eca | halessi/Covid19_Model | /utils.py | 109 | 3.921875 | 4 | import math
def is_square(integer):
root = math.sqrt(integer)
return integer == int(root + 0.5) ** 2 |
90ae285253e1f4f4ef734d658634083b68d6c8ba | HolyQuar/git_operation | /python_operation/classes_6/concept_1.py | 3,202 | 4.0625 | 4 | """
1.Python classes_6 provide all the standard features of Object Oriented Programming:
1.1.the class inheritance mechanism allows multiple base classes_6,
1.output_formatting_1.a derived class can override any methods of its base class or classes_6,
1.3and a method can call the method of a base class with the same na... |
c479eb1fa1ef31e4b2623f895e481445f2cfee83 | kcc112/Python-Lab-1 | /lcm.py | 176 | 3.84375 | 4 | def lcm(a, b):
output = a * b
output /= gcd(a, b)
return output
def gcd(a, b):
while b != 0:
a, b = b, a % b
return a
print(int(lcm(192, 348)))
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.