blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
60a8652cce087459fec3823044a14e8883bd660b | AlimKhalilev/python_tasks | /laba11.py | 456 | 3.828125 | 4 | def getNumber01(num):
while type:
getNumber = input('Введите число ' + num + ': ')
try:
getTempNumber = int(getNumber)
except ValueError:
print('"' + getNumber + '"' + ' - не является числом')
else:
break
return int(getNumber)
a = getNumber01(... |
13fc68a4202e0c939aee766ad65b4d27c1c1a0b2 | MrAch26/Developers_Institute | /WEEK 5/Day 2/OOP-exe-day2/main.py | 1,081 | 3.65625 | 4 | # EXE1
class Family():
def __init__(self, last_name,members=[]):
self.members = members
self.last_name = last_name
def born(self, **memberinfo):
self.members.append(memberinfo)
def is_child_18(self, name):
for i in range(len(self.members)):
if self.members[i... |
85081f01c0e741fddec7a7e74ee7ccd7e24b3b3c | JoseNA12/EncriptadorPY | /Tarea Final/encriptacionTelefonica.py | 3,807 | 3.75 | 4 | import validacion
def cifradoTelefonico(frase):
if (frase==""):
return ("Ingrese una frase.")
elif isinstance(frase, int) or validacion.validacion(frase.upper(),False)==False:
return ("Error, no es posible cifrar números ni caracteres especiales. Use únicamente el abecedario")
else:
... |
2c5b7a5a2b3360627bc165c89f46250a2e5ed9d5 | fabricio24530/ListaPythonBrasil | /EstruturaDeDecisao25.py | 1,241 | 4.21875 | 4 | '''Faça um programa que faça 5 perguntas para uma pessoa sobre um crime. As perguntas são:
"Telefonou para a vítima?"
"Esteve no local do crime?"
"Mora perto da vítima?"
"Devia para a vítima?"
"Já trabalhou com a vítima?" O programa deve no final emitir uma classificação sobre a participação da pessoa no crime.
Se a pe... |
126d7d5cdfa45a45568924fd50041a37b23513dc | DamarisMariscal01/alive1 | /LEVEL 6/SERIE AVANZADA.py | 171 | 3.875 | 4 | #Inputs
numero = int(input("Dime el número para hacer la secuencia hasta ahí: "))
#Proceso
contador = 1
while contador <= numero:
print(contador)
contador += 1
|
76adaebcb82065248e5d90e2c167588c7cf65463 | ChrisLiu95/Leetcode | /leetcode/median_of_two_sorted_arrays.py | 909 | 4.15625 | 4 | """
There are two sorted arrays nums1 and nums2 of size m and n respectively.
Find the median of the two sorted arrays. The overall run time complexity should be O(log (m+n)).
nums1 = [1, 3]
nums2 = [2]
The median is 2.0
nums1 = [1, 2]
nums2 = [3, 4]
The median is (2 + 3)/2 = 2.5
"""
# stupid solution
class Solutio... |
691962285338be5848fff17382275efa9245d77c | erolneuhauss/studies | /python/thomas_theis_einstieg_in_python/4.3.1_liste_eigenschaft.py | 1,021 | 4.4375 | 4 | #!/usr/bin/python
# Liste von Zahlen
z = [3, 6, 12.5, -8, 5.5]
print "print z", "entspricht", z
print "print z[0]", "entspricht", z[0]
print "print z[0:3]", "entspricht", z[0:3]
# Liste von Zeichenketten
cities = ["Hamburg", "Augsburg", "Berlin"]
print cities
# Anzahl Elemente
print "Anzahl:", len(cities)
# list in... |
88139ce5eab30577263060f66ad688d7f4023461 | pamixi10/Colaboratory-1 | /ブラックジャック.py | 1,435 | 3.625 | 4 | import random
deck=[1,2,3,4,5,6,7,8,9,10,11,12,13]*4
def deal():
hand=[]
for i in range(2):
card=random.choice(deck)
if card == 11:
card = "J"
if card == 12:
card = "Q"
if card == 13:
card = "K"
if card == 1:
... |
42a29f3dcbfc5d70ef584b1c08db1fcc3a81902c | cs-fullstack-2019-spring/python-classobject-cw-LilPrice-Code | /Classwork.py | 1,964 | 3.71875 | 4 | class Dog:
def __init__(self, name = "", breed = "", color = "", gender = ""):
self.name = name
self.breed = breed
self.color = color
self. gender = gender
def printAll(self):
print(self.name, self.breed, self.color, self.gender)
class PersonStats:
def __init__(self... |
45e80a9b511fe6d92ce4b6952bcee741f0d6d433 | Forestf90/TOSI | /Zad3/rsa.py | 1,267 | 3.5625 | 4 | from Crypto.Util import number
import random
import math
def generate_key():
p_length = random.randrange(512, 2048-512, 8)
q_length = 2048 - p_length
p = number.getPrime(p_length)
q = number.getPrime(q_length)
while p == q:
q = number.getPrime(q_length)
n = p * q
phi = (p-1)*(q-1)
... |
e15e1dbcb8161031076a37be393a5cf190c0539a | leokitty/udacity | /cs215/unit05/lect01_mavel_weights.py | 1,820 | 3.9375 | 4 | # Created on Feb 12, 2013
#
# Write a program to read the Marvel graph and put a strength value on each link.
# The "strength" is the number of books in which the characters co-appear.
# Which link has the highest strength value?
import collections
import csv
def make_link(G, node1, node2):
if node1 not in G:
... |
8cdd1511b40fd6962bc79da2442e1486db8a5ce5 | Sranciato/holbertonschool-interview | /0x0C-nqueens/0-nqueens.py | 1,010 | 3.609375 | 4 | #!/usr/bin/python3
"""N Queens"""
import sys
def solve_NQ(n):
grid = []
for row in range(0, n):
solve(n, 0, row, grid)
for solution in grid:
print(solution)
def solve(n, col, row, grid, sol=[]):
if safe(col, row, sol) is False:
return
s = sol.copy()
s.append([col, row... |
4f4515ac3dc227851aa305169129b410617cb55e | nutllwhy/Leetcode_python | /Easy/1Array/8Move_zero.py | 742 | 3.8125 | 4 | # 移动零
# 给定一个数组 nums, 编写一个函数将所有 0 移动到它的末尾,同时保持非零元素的相对顺序。
# 例如, 定义 nums = [0, 1, 0, 3, 12],调用函数之后, nums 应为 [1, 3, 12, 0, 0]。
# 注意事项:
# 必须在原数组上操作,不要为一个新数组分配额外空间。
# 尽量减少操作总数。
class Solution:
def moveZeroes(self, nums):
"""
:type nums: List[int]
:rtype: void Do not return anything, modif... |
5f07ce49423d3265c56c01e03ab9b9a68393ae44 | YuriiKhomych/ITEA_course | /VsevolodSavchenko/6_strings/practise/ex1.py | 199 | 3.859375 | 4 | def generate_n_chars(n, str):
result = ""
for x in range(n):
result += str
return result
print(generate_n_chars(5, "x"))
print(generate_n_chars(3, "*"))
print(generate_n_chars(2, "Test ")) |
e1144747f8913e54e763ce338fe2dc9ae16f120d | LeilaBagaco/DataCamp_Courses | /Linear Classifiers in Python/Chapter2-Loss functions/4-implementing-logistic-regression.py | 1,326 | 4.1875 | 4 | # ********** Implementing logistic regression **********
# This is very similar to the earlier exercise where you implemented linear regression "from scratch" using scipy.optimize.minimize.
# However, this time we'll minimize the logistic loss and compare with scikit-learn's LogisticRegression
# (we've set C to a ... |
558caaa5039f844a1a4c474275a1ba76a65056c2 | Frycu128/CODE_ME | /BASIC/08_Wyjątki/zad_4.py | 303 | 3.8125 | 4 |
try:
list_nb = input('Type few numbers separated with comma:')
list_nb = list_nb.split(',')
sum_item = 0
for i in list_nb:
sum_item += float(i)
mid_item = sum_item/len(list_nb)
print(mid_item)
except (TypeError, ValueError) as e:
print(f'Error is {e}')
|
86faf697f913fc7ab28a91e616765c8f27613239 | f1amingo/leetcode-python | /链表 Linked-List/876. 链表的中间结点.py | 371 | 3.828125 | 4 | # Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
from util.List import ListNode
class Solution:
def middleNode(self, head: ListNode) -> ListNode:
s = f = head
while f and f.next:
s = s.next... |
377cbc128fe5139de9b5716e7c41d3dc13b26b51 | cjkndxl/BYGB7990 | /XuantingWangLab4.py | 908 | 3.9375 | 4 | #Xuanting Wang Lab4
gasPrice = 3
milesPerGallon = 35
origin = input('Please enter your starting location:\n>>')
firstOrigin = origin
keepGoing = 'y'
tripCost = 0
outputStrings = []
while keepGoing == 'y':
s = 'From ' +origin+', where will you travel?\n>>'
nextLocation = input(s)
st = 'How far a... |
86680068c73c91d827921e19876c05b4f377884b | qiubite31/Leetcode | /Math/leetcode-728.py | 1,388 | 3.890625 | 4 | """
728. Self Dividing Numbers
Difficulty: Easy
Related Topic: Math
A self-dividing number is a number that is divisible by every digit it contains.
For example, 128 is a self-dividing number because 128 % 1 == 0, 128 % 2 == 0, and 128 % 8 == 0.
Also, a self-dividing number is not allowed to contain the digit zero.
... |
1143ccf6349af5196fb0d48f2af7318d196ddaea | kmjennison/dfp-prebid-setup | /tasks/price_utils.py | 4,295 | 4.15625 | 4 |
def num_to_micro_amount(num, precision=2):
"""
Converts a number into micro-amounts (multiplied by 1M), rounded to
specified precision. Useful for more easily working with currency,
and also for communicating with DFP API.
Args:
num (float or int)
precision (int)
Returns:
an integer: int(num *... |
edee355aec5a7ce3a68aaa733c2524c3129df305 | gonzodeveloper/commodities_vs_weather | /reshape_tables.py | 2,332 | 3.828125 | 4 | # Kyle Hart
# Project: Commodities vs. Weather
#
# Description: Meant to reshape the tables from the World Bank and UN data.
# Note, the original csv's were all loaded into the sqlite database 'countries.db'
# The new tables are saved back into the database to be manually exported as csv's later
im... |
b000efec754d01e75a818f1da434f04105874299 | MingkaiLee/MatchEquation | /venv/bin/factors.py | 1,577 | 3.640625 | 4 | #数值
class Factors:
def __init__(self, value):
#键值
self.value = int(value)
self.bits = len(value)
if self.bits == 2:
#十位
self.ten = int(value[0])
#个位
self.one = int(value[1])
else:
self.ten = 0
self.one = ... |
118edab10aa0443db690aab180000cd4454628e8 | nghiango/python-excercise | /python/beginner/ex22_calculate_follow_formular.py | 306 | 3.890625 | 4 | def main():
number = 5
number1 = number*10 + number
number2 = number*100 + number1
print('Result:', number + number1 + number2)
string1 = str(number)
string2 = string1 + string1
string3 = string2 + string1
print('Result 2', int(string1) + int(string2) + int(string3))
main() |
37f4710b9460639fe4224c8dfbf558962718635d | ElenaRoche/python | /ordenar cifras.py | 207 | 3.90625 | 4 | def reorganizacioncifras():
n_cifras=0
numero=input("Dime un numero")
while numero>0:
numero=numero/10
n_cifras=n_cifras+1
print n_cifras
reorganizacioncifras()
|
42cddb5021e5a78df5262d89095e15a9a4a99044 | hguochen/algorithms | /python/sort/radix_sort.py | 1,443 | 4.09375 | 4 | ##############################################################################
# Author: GuoChen
# Title: Radix sort
##############################################################################
def radix_sort(a_list):
"""
Radix sort, like counting sort and bucket sort, is an integer based
algorithm. Henc... |
00a69271b584a21e99c35ee01cfae3be5d8ae2b9 | humanwings/learngit | /python/socket/testSocket_TCPServer03.py | 1,011 | 3.546875 | 4 | '''
TCP服务器03
- server和client 1对N, 支持并行通信。
- 进行多次收发,直到客户端发出exit或者空消息
'''
import socket, threading, time
def tcplink(sock, addr):
print('Accept new connection from %s:%s...' % addr)
sock.send(b'Welcome!')
while True:
data = sock.recv(1024)
time.sleep(1)
if not data or data.decode('ut... |
3148f3d203d2f1ec9b2781d64209abd639078957 | JedGStumpf/Early-Learning-Python | /Budget_begin.py | 5,985 | 3.75 | 4 | """
Found this old gem. 1st "program" I wrote after a coulple entry level Python couses.
I might think about refactoring, restructuring into classes, possibly adding a UI... to be continued?
Docstring added 3/17/2021 /// Last saved prior 9/23/2019
"""
expense_list = []
bill_list = []
household = []
fun = []
inco... |
02aff72d2bcf2624223635d2cdf9813bdec4ea55 | JosephLevinthal/Research-projects | /5 - Notebooks e Data/1 - Análises numéricas/Arquivos David/Atualizados/logDicas-master/data/2019-1/224/users/4431/codes/1691_1952.py | 428 | 3.625 | 4 | x=float(input("Digite o salario liquido: "))
if(x<=1659.38):
p=x*0.92
elif(x>=1659.39)and(x<=2765.67):
p=x*0.91
elif(x>=2765.67)and(x<=5531.31):
p=x*0.89
elif(x>5531.31):
p=x-608.44
if(p<=1903.98):
p=p-0
elif(p>=1903.99)and(p<=2826.65):
p=p*(92.5/100)
elif(p>=2826.66)and(p<=3751.05):
p=p*(85/100)
elif(p>=3751.0... |
107b4767c4f119bcb6ea56f77bd659067af4c4f8 | ravigaur06/PythonProject | /functools/filter_map_reduce.py | 555 | 3.9375 | 4 | from functools import reduce
# to find even mumber
l=[1,2,3,4,5,6,7,8,9,10]
evens=list(filter(lambda x : x%2==0 ,l))
print (evens)
# Return the square of all numbers in the list
square=list(map(lambda x: x*2 ,l))
print (square)
#to find the sum of all numbers in the list using reduce
sum=re... |
8313c2cf9fe5a1c478d690ddad54cdb7d459c56c | Philip-Loeffler/python | /SectionFive/nestedLists.py | 815 | 4.3125 | 4 | empty_list = []
even = [2, 4, 6, 8]
odd = [1, 3, 5, 7, 9]
numbers = [even, odd]
# this will print out [[2,4,6,8], [1,3,5,7,9]]
# you have a list within a list
print(numbers)
# will create the 2 seperate lists and print them out
for number_list in numbers:
print(number_list)
# will print out the values inside thos... |
1aaf41f7af803fd42f3249b8c58e85464aa72924 | aayushi-droid/Python-Thunder | /Solutions/harshadNumber.py | 694 | 3.859375 | 4 | """
Probem Task : "A number is said to be Harshad if it's exactly divisible by the sum of its digits. Create a function that determines whether a number is a Harshad or not."
Problem Link : https://edabit.com/challenge/eADRy5SA5QbasA3Qt
"""
def is_harshad(inp):
sum_of_digits = sum([int(digit) for digit in... |
e6d3cb7c84ebedfd560af5aab7494cf06293f7e2 | yograjsk/selenium_python | /OOP_Demo/abstraction_example/calculator.py | 725 | 4.34375 | 4 | from abc import abstractmethod, ABC
class calculator(ABC):
@abstractmethod
def add(self):
# def add(self, a, b):
# def add(self):
pass
@abstractmethod
# def multiply(self, a, b):
def multiply(self):
pass
# abstract class: the class which has at least one abstract method
... |
12cd0292328abcfa01d390c9bf511f87aaa68a52 | jumbokh/pyclass | /code/jPB371/ch04ok/sum5.py | 257 | 3.90625 | 4 | # -*- coding: utf-8 -*-
"""
某一個數字範圍內5的倍數進行加總
"""
sum = 0 #儲存加總結果
# 進入for/in迴圈
for count in range(0, 21, 5):
sum += count #將數值累加
print('5的倍數累加結果=',sum) #輸出累加結果
|
4d8f69c1ee21c8e7fd796377bce8177fa0a1513f | erjantj/hackerrank | /shifted-binary-search.py | 901 | 3.8125 | 4 | def shiftedBinarySearch(array, target):
if not array:
return -1
l = 0
r = len(array) - 1
while l <= r:
mid = (l+r)//2
print('mid', array[mid])
if target == array[mid]:
return mid
elif target == array[l]:
return l
elif target =... |
26ce28de5f095ceabee9d3ac354ffda7b1cc8f3b | daberg/algorithms | /sorting/bubble_sort.py | 674 | 4.09375 | 4 | def bubble_sort(a):
for i in range(len(a), 0, -1):
for j in range(1, i):
if a[j-1] > a[j]:
a[j-1], a[j] = a[j], a[j-1]
def better_bubble_sort(a):
for i in range(len(a), 0, -1):
has_swapped = False
for j in range(1, i):
if a[j-1] > a[j]:
... |
cc52f6a8235247fb375c5119fee7cc6e5c78bc8f | thomasccp/project-euler | /Python/3.py | 810 | 3.8125 | 4 | #def prime_factors(n):
# factors=[]
# d=2
# while n>1:
# while n%d==0:
# n/=d
# d=d+1
# if d*d>n:
# if n>1:
# factors.append(n)
# break
# return factors
#num=600851475143
#prime_factor_list = prime_factors(num)
#print max(prime_factor_li... |
2e99ccd3a4f47dd732102f82c4e1d467a771b4e2 | Mudasirrr/Courses- | /Rice-Python-Data-Visualization/week3- Plotting GDP Data on a World Map - Part I/Reconciling Cancer-Risk Data with the USA Map/cancerviz_week3.py | 4,321 | 4.34375 | 4 | """
Week 3 practice project template for Python Data Visualization
Read two CSV files and join the resulting tables based on shared FIPS codes
Analyze both data sources for anamolous FIPS codes
@author: salimt
"""
import csv
from collections import defaultdict
def print_table(table):
"""
Echo a nested list t... |
e0f643b7d606d23cc05cd3d89220f339b1c7f8ef | Denjesd/new2 | /Basic/Lesson 16/Lesson_16_Task_1.py | 974 | 3.9375 | 4 | # Lesson 16 Task 1
class Buffer:
def __init__(self):
self.values_list = []
self.sums_list = []
# конструктор без аргументов
def add(self, *a):
for item in a:
self.values_list.append(item)
# добавить следующую часть последовательности
def get_current_part(self):... |
9c6f9c43f4ad5f7d0529a85f55b0ac19886c8563 | TeoMoisi/python-projects | /lab1/sum_n.py | 156 | 3.984375 | 4 | def sum_n(n):
s = 0
for i in range(n):
s += i
return s
n = int(input("Enter the number: "))
s = sum_n(n)
print("the sum is " + str(s))
|
a1a5b7372f0d705771c39450b70d744fbd8dfe7f | SourDumplings/CodeSolutions | /OJ practices/牛客网:PAT真题练兵场-乙级/统计同成绩学生-返回非零.py | 973 | 3.828125 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Date : 2017-11-23 19:04:50
# @Author : 酸饺子 (changzheng300@foxmail.com)
# @Link : https://github.com/SourDumplings
# @Version : $Id$
'''
https://www.nowcoder.com/pat/6/problem/4064
'''
def main():
N = input()
N = int(N)
data = {}
grade_list = in... |
a434debf767e204317dfe08fdb8bf5c353306335 | phucmp/retrieveCensusData | /Classes/responder.py | 1,443 | 3.921875 | 4 | #libraries needed to capture and handle api call
import requests, json
#library needed for saving to csv format
import pandas as pd
#class to handle api call response
class Responder():
def __init__(self, url):
"""Responder Constructor"""
self.url = url
self.response = None
def get_r... |
4005faf71520029491466178b9beb2816307a514 | Everfighting/Learn-Python-the-Hard-Way | /ex4_1.py | 1,947 | 3.828125 | 4 | # coding=utf-8
# int(x [,base]) 将x转换为一个整数
print int('10',2)
print int('10',8)
# 默认进制为十进制
print int('10')
# hex(x) 将一个整数转换为一个十六进制字符串
print hex(16)
# oct(x) 将一个整数转换为一个八进制字符串
print oct(16)
# 类似的还有
# long(x [,base] ) 将x转换为一个长整数
# float(x) 将x转换到一个浮点数
# ... |
5ea8707e203183cb048f38ae6c6bc7ec0de10a34 | ignifluous777/Exercises | /data_structures/dictionaries_and_arrays/3.Difference/Solutions/solution.py | 400 | 3.921875 | 4 | from array import *
array_num = array("i", [12, 23, 34, 45, 56])
def find_greatest(arr):
greatest = arr[0]
for i in arr:
if i > greatest:
greatest = i
return greatest
def find_lowest(arr):
lowest = arr[0]
for i in arr:
if i < lowest:
lowest = i
return l... |
327fa61ab7f27b57370dc6e8a14c98f5d587a199 | HenkT28/GMIT | /iris_plot.py | 6,679 | 3.546875 | 4 | # Henk Tjalsma, 2019
# Iris Data Set - plotting iris data set
# https://www.kaggle.com/abhishekkrg/python-iris-data-visualization-and-explanation
# https://www.kaggle.com/jchen2186/machine-learning-with-iris-dataset
# https://machinelearningmastery.com/machine-learning-in-python-step-by-step/
# Importing libraries
im... |
19779baf15f59eed205b0c22516044b4899bed02 | mathewssabu/luminarpythonprograms | /pythoncore/flow controls/looping/demo.py | 108 | 3.671875 | 4 | #repeat
#while
#for
#initialisation
#condition
#inc or dec
i=1
while(i<=10):
print("hello")
i+=1
|
b238a1c80486bcf22ca602dd12285e60885d6a32 | akuelker/intermediate_python_class | /Exercise 6/Exercise6_3.py | 314 | 3.53125 | 4 | my_list = [1,2,3,4,5,6,7,8,9,10]
evens = list(filter((lambda x: x%2 ==0), my_list))
squared_evens = list(map(lambda x: x * x, evens))
print(squared_evens)
#you can also do it all at once
new_squared_evens = list(map(lambda x: x * x, \
list(filter((lambda x: x%2 ==0), my_list))))
print(new_squared_evens) |
8730186f995920eac43b550a3d87a563b5502f79 | shahabkamali/programmers-should-know | /python/SortingTechniques/SelectionSort/selection_sort.py | 344 | 3.796875 | 4 |
def selection_sort(lst):
for i in range(0, len(lst)-1):
min_index = i
for j in range(i+1, len(lst)):
if lst[j] < lst[min_index]:
min_index = j
temp = lst[min_index]
lst[min_index] = lst[i]
lst[i] = temp
return lst
lst = [5,10,15,1,8]
prin... |
b1e0981ccc43857b7381629105087415ea37261c | shivamyadav37/DataStructure | /CheckBinaryTreeIsBST.py | 1,742 | 4.125 | 4 |
class Node:
# Constructor to create a new Node
def __init__(self, data):
self.data = data
self.left = None
self.right = None
#print("Simple but wrong")
def binaryIsBST(root):
if root is None:
return True
if root.left is not None and (root.left.data <root.data) :
... |
5ee935a37c6795ba2bd0fe11ea2cea0e5db49169 | MDABUSAYED/Machine-Learning-Regression | /Simple Linear Regression/Simple Linear Regression.py | 5,969 | 4.21875 | 4 |
import graphlab
# # Load house sales data
#
# Dataset is from house sales in King County, the region where the city of Seattle, WA is located.
sales = graphlab.SFrame('kc_house_data.gl/')
sales
# # Split data into training and testing
# We use seed=0 so that everyone running this notebook gets the same results.... |
59b8c3277cc40165199aef3925181c93084561b0 | KAMeow/guess-number | /guess-number.py | 382 | 3.859375 | 4 | import random
r = random.randint(1, 100)
count = 0
count = int(count)
while True:
count += 1
que = input('please guessing number: ')
que = int(que)
if que == r:
print('Your number is correct!')
break
elif que > r:
print('your number is bigger than the answer.')
elif que < r:
print('your number is smaller ... |
9d5c73c57d544bf0e3a7b0e2302b917f87f8914c | tainaslima/special-topics-in-programming | /works/Semana 2/11111_GeneralizedMatrioshkas_TainaLima.py | 1,472 | 3.765625 | 4 | import sys
def isGeneralizedMatrioshka(case):
if(case):
entry = case.split()
stack_matrioshka = []
stack_inner_sum_matrioshka = [0]
isMatrioshka = True
stack_matrioshka.append(int(entry[0]))
for m in entry[1:]:
matrioshka = int(m)
#print(m)
... |
66c0bbc9794c5a2b0592bddba619602d96ef3826 | nsekulov/python-intro | /learning_area/statements.py | 417 | 4.3125 | 4 | dummy = 0
#Basic if and else statements
if dummy:
print(True)
else:
print(False)
#elif (Else if)
if dummy == 1:
print("Dummy is equal to 1")
elif dummy==3:
print("Dummy is equal to 3")
else:
print("Dummy is not equal to either 1 or 3")
#Conditional Expression
r = False
print("Let's go to the", '... |
5468d21931d8ba34838850144d04855afb2aba55 | a3910/aid1807-1 | /aid1807a/练习题/python练习题/python基础习题/14/homework2.py | 1,026 | 4.25 | 4 |
# 2.分解质因数,输入一个正整数,分解质因数
# 如:90则打印'2*3*3*5'
# 质因数是指最小能被原数整除的质数(不包括1)
def isprime(x):
for i in range(2, x):
if x % i == 0:
return False
return True
# def get_list(n):
# '''从2开始,到n//2,对其所有数求余,能整除且为质数的放在primes里'''
# primes = [] # 用来方所有质因数
# last = n # 保存除之后的数
# wh... |
4a1f718e0dceb275bdace16d32f8af1046b21f6c | mslpooh/python | /PersonalProject/MemberManagement/person/person.py | 1,119 | 3.6875 | 4 | class Person:
def __init__(self, name, age, gender):
self.name = name
self.age = age
self.gender = gender
def name_(self):
return self.name
def age_(self):
return self.age
def gender_(self):
return self.gender
def main():
while Tr... |
944c8136f1e444ccb9fb15eaacb731df40c67184 | nauman-sakharkar/Python-2.x | /Check Leap Year.py | 128 | 4.03125 | 4 | a=int(input("Please Enter The Year = "))
if a%4==0:
print(a," Is A Leap Year")
else:
print(a,"Is Not A Leap Year")
|
b178756008ec51e47cd4a94d51d2e8d895d7afed | allender/AdventOfCode | /2021/day1/day1.py | 386 | 3.5 | 4 | from aocd import numbers
def part1(data):
increases = 0
for i in range(1, len(data)):
if data[i] > data[i-1]:
increases = increases + 1
return increases
def part2(data):
sums = [ data[x] + data[x-1] + data[x - 2] for x in range(2, len(data)) ]
return part1(sums)
if __name__ =... |
f9ee2ff8b6db4f7e3e2f93bb322dc82e8b75e2ee | rajul/UVa | /438/circum.py | 512 | 3.5625 | 4 | import sys
import math
p = 3.141592653589793
def distance(a, b):
return math.sqrt(math.pow((a[0] - b[0]), 2) + math.pow((a[1] - b[1]), 2))
for line in sys.stdin:
t = [float(i) for i in line.strip().split()]
x = (t[0], t[1])
y = (t[2], t[3])
z = (t[4], t[5])
a = distance(x, y)
b = distance(y, z)
c = distanc... |
7600dffe177b06517fae12484407c9dc8d315ea5 | sambhu-padhan/My_Python_Practice | /51_Croutines.py | 571 | 3.71875 | 4 | #.....Coroutines in Python.........
def searcher():
import time
book = "This is a book on Sambhu and Harrry and good"
time.sleep(5)
while True:
text = (yield )
if text in book:
print("Your text is in the book")
else :
print("text is not in t... |
c2869256d9d177005ac9bf9b3dc87ca0c06c26b5 | baskaufs/msc | /python/defunct/convertXml.py | 1,667 | 3.515625 | 4 | # First row of the csv file must be header!
# example CSV file: myData.csv
# id,code name,value
# 36,abc,7.6
# 40,def,3.6
# 9,ghi,6.3
# 76,def,99
import csv
import codecs
def unicode_csv_reader(unicode_csv_data, dialect=csv.excel, **kwargs):
# csv.py doesn't do Unicode; encode temporarily as UTF-8:
csv_reade... |
ef7c96b050781882820c32a13172465576650f32 | SunMaungOo/angel-problem | /core/matrix.py | 3,565 | 3.890625 | 4 | from .board import Board
def get_avaliable_moves(board:Board,position:tuple,n:int)->set:
"""
Return all the avaliable move from the position
Return set will be a set of tuple (row_index,column_index)
the set will ignore the current position and all the blocked position
board : 2D matrix (composed o... |
bf3c557d892e98cf06c8bba88d6d414e5321c5c2 | Chincoya/Modelado2017-1 | /UnionFind.py | 717 | 3.96875 | 4 | parent = {}
rank = {}
def init_node(node):
parent[node] = node
rank[node] = 0
def find_root(node):
if parent[node] != node:
parent[node] = find_root(parent[node])
return parent[node]
def union(node1, node2):
root1 = find_root(node1)
root2 = find_root(node2)
if root1 != root2:
... |
329134521f12cbfe19173a58d522768e4930969e | Aasthaengg/IBMdataset | /Python_codes/p03624/s257306569.py | 134 | 3.703125 | 4 | import string
s = input()
t = string.ascii_lowercase
for i in t:
if i not in s:
print(i)
exit()
print("None")
|
f171ef0623b69fa421644a76b36c264d559dc350 | juwaini/project-euler-solutions | /0021-0040/problem_0028.py | 616 | 3.9375 | 4 | def sum_of_spiral_diagonals(n):
if n % 2 == 0:
return 0
number_of_terms = 2*n - 1
print(f'Number of terms for {n} is: {number_of_terms}')
skip = 1
ls_of_diagonals = [1]
for i in range(1, number_of_terms):
ls_of_diagonals.append(ls_of_diagonals[-1] + (skip * 2))
if i % 4 ... |
1ce734ebf68253a307155b8d5b75ce7f56d5c72a | nezlobnaya/leetcode_solutions | /14_patterns/sliding_window/longest_substring_with_k_unique_char.py | 3,222 | 3.90625 | 4 | """
Suppose we have a string we have to return the longest possible substring that has exactly k number of unique characters, if there are more than one substring of longest possible length, return any of them.
So, if the input is like s = "ppqprqtqtqt", k = 3, then the output will be rqtqtqt as that has length 7.
"... |
f9912e317d797c931d71049876490dcb79c44bf4 | Bhushanbk/mypython | /iter1.py | 445 | 3.59375 | 4 | class owniterator:
def __init__(self,num=0):
self.number=num
def __iter__(self):
self.x=1
return self
def __next__(self):
if self.x <=self.number:
own_iter=self.x
self.x +=1
return own_iter
else:
raise StopIt... |
b40b0f437b3fc926fde26a81905d293c51240bfb | ahammadshawki8/Standard-Libraries-of-Python | /09. json module.py | 8,674 | 4.46875 | 4 | # json module
# in this module, we will learn how to work with json data within python.
# json stands for "JavaScript Object Notation"
# it is a very common data format for storing informations.
# it is used most when fetching data from online api's,
# but it is also used for configuration files and that kind of data... |
43439135d05cab8a4d7bfb6b0e136c2ad5e6c30f | benjaminhechen/labfunctions | /lab_writing_programs.py | 491 | 3.96875 | 4 | def main():
print("This is a calculator.")
x = eval(input("How many calculations would you like to evaluate?"))
for i in range(x):
userInput = input("Enter a Mathematical Expression:")
evalUserInput = eval(userInput)
print(userInput + "=" + str(evalUserInput))
... |
d573fdee946ca15bdb87f72327a712bfdab634f6 | chung3011/tranngocbaochung-fundamental-c4e17 | /session6/f-math-problem/freakingmath.py | 669 | 3.671875 | 4 | import random
from random import choice
import eval
def generate_quiz():
x=random.randint(1,10)
y=random.randint(1,10)
op_list=["+","-",'*','/']
op=choice(op_list)
res=eval.calc(x,y,op)
error_list=[-1,1,0]
error=choice(error_list)
result = res+error
return [x, y, op, result]
def ch... |
c84f280605f1f2a38d1bf999a7d47a325fa767ad | dgilliga/hackerrank | /RR2_min_diff.py | 405 | 3.890625 | 4 | #!/bin/python3
"""
Given an array of integers, find and print the minimum absolute difference between any two elements in the array.
"""
import sys
n = int(input().strip())
a = list(map(int, input().strip().split(' ')))
# your code goes here
a.sort()
my_min = abs(a[0] - a[1])
for i in range(0, len(a)-1):
di... |
c4e9f968f3996748916fae76c841908fba0ef550 | hsyliark/python_selfstudy | /Basic programming/코딩도장/코딩도장 5.py | 811 | 3.515625 | 4 | # 세 자연수 a, b, c 가 피타고라스 정리 a**2 + b**2 = c**2 를 만족하면 피타고라스 수라고 부릅니다
# (여기서 a < b < c 이고 a + b > c ).
# 예를 들면 3**2 + 4**2 = 9 + 16 = 25 = 5**2 이므로 3, 4, 5는 피타고라스 수입니다.
# a + b + c = 1000 인 피타고라스 수 a, b, c는 한 가지 뿐입니다. 이 때, a × b × c 는 얼마입니까?
# 출처 : https://projecteuler.net/problem=9
import random as rd
Pythagorean = dic... |
5fbce3b93341ab16675f95999806bb86269ff39b | GabrielCarlosG/.py | /Aula_Python/ExPython.py | 378 | 3.578125 | 4 | # mnha solução para o desafio de um contador:
# cont_plus = 0
# cont_less = 10
# while cont_plus <= 10 and cont_less >= 0:
# print(cont_plus, cont_less)
# cont_less -=1
# cont_plus +=1
#solução do professor para o desafio de um contador:
# for p, r in enumerate(range(10,1,-1)):
# print(p, r)
# print... |
00dba4e063a32926c3d3b0e8ed6a11939fef9bd4 | msklarek/Coursera-Learn-to-Program-The-Fundamentals | /convert_to_minutes.py | 362 | 4.1875 | 4 | def convert_to_minutes(num_hours):
'''(int)->int
Return the number of minutes there are in num_hours.
>>>convert_to_minutes(2)
120
'''
minutes = num_hours * 60
return minutes
def convert_to_second(num_hours):
minutes = convert_to_minutes(num_hours)
seconds= minutes *60
return se... |
1035bd6c21f65c0e5a5cafe5fb31472291741dfa | Aathira-satheesh123/Git-tutotorial | /add.py | 232 | 3.703125 | 4 | def add2(n1, n2):
s = n1 + n2
return s
print add2(3, 4)
def add2(n1, n2, n3):
s = n1 + n2 + n3
return s
print add2(3, 4, 5)
def add2(n1, n2, n3, n4):
s = n1 + n2 +n3 + n4
return s
print add2(3, 4, 5, 6)
|
68a2acd5d0091618a1e3f884332d3fdae3ad8298 | AndreaEdwards/AndreaEdwards.github.io | /other/CSCI_1310/inheritance.py | 3,850 | 4.53125 | 5 | #!usr/local/python3
# Inheritance hierarchy. In these examples we are using the default constructor
# no __init__ here
# will not see inheritence more than one level deep.
# in general the alternative to inheritence is called composition, and
# composition (which we will get to in c++) is more favored than inherite... |
01f40984d3be0cc36b8bd50559ba7e739ce4e2a2 | Luisarg03/Python_desktop | /Apuntes_youtube/bucles.py | 704 | 3.6875 | 4 | #el bucle se usa para repetir lineas de codigo, ej: el uso de bucles en ventanas de login, si logeas mal la cuenta debe vovler a reiniciar el login.
#hay bucles determinados, que se sabe cuantas veces se repetiran las lineas de codigo.
#y bubles indeterminados que no se puede saber cuantas veces se repetira, solo dep... |
3a8acd53edd7ee251aafc25d28e929cd7d4dc201 | PeterSzasz/GraphApp | /graph_methods.py | 3,153 | 3.765625 | 4 | # graph related algorithms
from core.graph import Graph, Node, Edge
from graph_visualisation import VisGraph
def breadth_first(graph: Graph, start_node: Node) -> tuple:
'''
A breadth first graph traversal
makes one traversal from start_node.
Args:
graph (Graph): full graph
start_n... |
3fa834494902262c9301fbb979d20682fff04a51 | BrianArb/CodeJam | /Round_1A_2008/minimum_scalar_product.py | 2,466 | 3.890625 | 4 | #!/usr/bin/env python
"""
Problem
You are given two vectors v1=(x1,x2,...,xn) and v2=(y1,y2,...,yn). The scalar
product of these vectors is a single number, calculated as x1y1+x2y2+...+xnyn.
Suppose you are allowed to permute the coordinates of each vector as you wish.
Choose two permutations such that the scalar pro... |
e56b913e24fbe2a7aa514292ab67070e5359d84e | guo-chong/tess-two | /sort.py | 4,036 | 3.765625 | 4 | def adjustNode(arr,node,len):
temp=arr[node]
k=node*2+1
while(k<len):
if(k+1<len and arr[k+1]>arr[k]):
k+=1
if(arr[k]>temp):
arr[node]=arr[k]
node=k
k = node * 2 + 1
else:break
arr[node]=temp
def heapSort(arr):
for i in range(le... |
9f61df0e5a0ceca239d6fa77df485a2b9efb8bbf | SuzanneRioue/programmering1python | /Arbetsbok/kap 3/övn 3.5 - beräkna bensinpris - kap 3, sid. 5.py | 1,226 | 3.8125 | 4 | #!/usr/local/bin/python3.9
# Filnamn: övn 3.5 - beräkna bensinpris - kap 3, sid. 5.py
# Skapa program eller skript
# Programmeringsövningar till kapitel 3 - Arbetsbok
# Programmet frågar efter tankad volym i liter och efter bensinpris i kr/liter.
# Därefter skriver det ut ett kvitto.
# Skriv ut programmets rubrik
p... |
3a2a3614e6d6cb6ea6e7843d3a101b09229eb0ea | Remchu/Loginthing | /Ken'sDad.py | 1,196 | 3.59375 | 4 | import re
LoginDetails = {}
data = open('login users.txt')
subaru = data.readline()
for x in data:
x = x.strip().split('|')
LoginDetails[x[0]] = x[1]
def Login(username, password):
for user in LoginDetails:
if username == user and password == LoginDetails[user]:
return True
return ... |
a41cb703602e6c6290c1aa8459fe4a32bdf5bfa0 | 7983-drashti/python | /day8.py | 572 | 4.03125 | 4 | #exception handling.....
'''try:
x=int(input('enter a no.'))
y=int(input('enter a no.'))
z=x/y
print('Div is',z)
except Exception as e:
print('tjere is any issue',e)
except Exception:
print('Any issue')
except ZeroDivisionError:
print('second no.is zero')
except ValueError:
print('wrong value pass')
finally... |
62e5a0c6605f13a7a7ad61008ba0b9b70cfb5b9d | l-Shane-l/Python-Projects | /minKnightMovesBFS.py | 1,418 | 3.53125 | 4 | def solution(src, dest):
steps = 0
movesPossible = [src]
prevMoves = []
while isDestPresent(movesPossible,dest) != True:
steps = steps + 1
movesPossible = possibleMoves(movesPossible)
movesPossible = set(movesPossible)
movesPossible = [x for x in movesPoss... |
0d8a122a65703c319da3d84db59698c4f44f48eb | prachi464/Python-assignment | /PYTHONTRAINNING/module5/list1.py | 587 | 4.21875 | 4 | #Nested list comprehnesion
matrix=[]
for i in range(5):
matrix.append([])
for j in range(5):
matrix[i].append(j)
print(matrix)
print("\n")
matrix=[[j for j in range(5)]for i in range(5)]
print(matrix)
print("\n")
#flatter a given 2d list
matrix=[[1,2,3],[4,5,6],[7,8,9]]
fl_mat=[1,2,3,4,5,... |
0e722a5107080df183e700d91446f00185630139 | xhanak2/CodeWars-Python | /order.py | 484 | 3.75 | 4 | def order(sentence):
if len(sentence)>0:
sentence+=' '
count=0
word=''
words=['','','','','','','','','']
for c in sentence:
if (c!=' '):
word+=c
if c in '123456789':index=int(c)
else: words[index]=word;word='';count+=1... |
44f8fbd51ca2355604093cfa95f16464ebe34f78 | jaekwon/jae-python | /time_utils.py | 602 | 3.5 | 4 | import datetime
def timeago(timestamp):
""" returns:
- x minutes ago
- x hours ago
- x/y/z
"""
now = int(datetime.datetime.utcnow().strftime('%s'))
diff = now - timestamp
dt = datetime.datetime.fromtimestamp(timestamp)
# strange case where timestamp is in the future... just show the date
if diff < 0:
... |
1736477815b13e9486d7d6a55505766b4a4f7cb5 | SodaCookie/QuestBook | /monster.py | 8,033 | 3.546875 | 4 | import random
from moves import *
from constants import *
class Monster:
def __init__(self, difficulty = 1, monster = "", party = [], power = 1): # ELITE AND BOSS MONSTER HAVE GUARENTEED ABILITES, ABILTY IS BASED ON MAGIC
self.difficulty = difficulty
self.effects = []
self.args = []
... |
e2fd4fc5030a0eec5f1221eb1fb340ba42e7006a | cafebabeCoder/leetcode | /vs_py/450.删除二叉搜索树中的节点.py | 1,745 | 3.65625 | 4 | #
# @lc app=leetcode.cn id=450 lang=python3
#
# [450] 删除二叉搜索树中的节点
#
# @lc code=start
# 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 = right
class Solution:
def deleteNode(self, r... |
364990b857b6abf1f4ea8fbd1e8081362a506da2 | rishabhjaincoder/OTP-Finder | /OTP-Finder.py | 395 | 3.90625 | 4 | # OTP finder program
# regular expressions
import re
string="dear customer your otp for transacton in icici bank is 989832. valid for 10 minutes only." # complete
# compile regular ecxpressions
exp = re.compile('[0-9]{6}')
result= exp.search(string)
... |
01d0a299133880d3fe876c2029f1d6d6d92ff5a0 | qianrongping/python_xuexi | /python_文件操作/python_文件备份.py | 719 | 3.890625 | 4 | # 1.接收用户输入的文件名
old_name = input('请输入需要备份的文件名:')
# 2.规划备份文件名
# 2.1 提取后缀,找到名字中的点 --名字和后缀分裂
index = old_name.rfind('.')
# 有效文件才备份
if index > 0:
postfix = old_name[index:]
# 2.2 组织新名字 = 原名字 +【备份】 + 后缀
new_name = old_name[:index] + '[备份]' + postfix
print(new_name)
# 3.备份文件写入数据
# 3.1 打开源文件 和 备份文件
old_f = open(old_nam... |
e0f2eba39a837b20e4de1901d2d1239e0a7ca10b | pavantyagi/-Machine-Learning--BNP-Paribas-Insurance-Claims-Management | /dataprocessing.py | 16,806 | 3.53125 | 4 | '''
This file would do process the data from BNP scoure
The data-preprocessing method include that deal with missing value, factorize categorical value, convert type of data,
shuffle and sort the data, as well as increasing and reducing the dimension of the dataset
'''
import pandas as pd ... |
5ab7cd33177fd4e625012262e2b8dd97389e5235 | MrVeshij/tceh_cource | /tests/RIDDLE.py | 263 | 3.65625 | 4 | question = 'Что лучше Питон или С#?'
riddle_1_answer = 'питон'
request = int(input(question))
count = 0
if riddle_1_answer == request:
count += 1
print('Да вы правы!')
else:
print('Нет, вы не правы!')
|
78da2dbcf791f0d4c3ffd5b7302649700a89ba26 | rejgan318/fctests | /save abd tests/tstMultiprocessing/multiprocessing_example.py | 1,990 | 4.09375 | 4 | ''' Пример 3 multiprocessing example
https://www.journaldev.com/15631/python-multiprocessing-example '''
from multiprocessing import Lock, Process, Queue, current_process
import time
import random
import queue # imported for using queue.Empty exception
import pickle
class Outdata:
def __init__(self, info: st... |
d7ddeaa25a41b35b69f813fb160703f1897f218b | bedros-bzdigian/intro-to-python | /week5/pratical/Decorators/problem9.py | 269 | 3.625 | 4 | def Text ():
b = "Hi everyone"
x = make_lower("Hi everyone")
x = add_text("Hi everyone")
return (x)
def make_lower (x):
x = str(x)
x.lower()
return x
def add_text (y):
y = str(y)
y = y + "!!! Welcome to the party"
return (y)
print (Text ())
|
d0d8fc2cf0d0b4a41bb3ad8e3c8d5f507525c87e | FE1979/Dragon | /Python_4/words_count.py | 385 | 3.859375 | 4 | string = input('Type a sentence\n')
words = string.split(' ')
words_counted = []
words.sort()
while words:
word = words[0]
words_counted.append([word, words.count(word)])
while word in words:
words.remove(word)
print(words_counted)
words_counted.sort(key = lambda count: count[1], reverse = True... |
0988fac773cc47facbc6d94cfd67bad3ce6b1483 | CODEJIN/Tensorflow_Functions_for_Test | /Cosine_Similarity.py | 2,511 | 3.578125 | 4 | import tensorflow as tf;
def Cosine_Similarity(x,y):
"""
Compute the cosine similarity between same row of two tensors.
Args:
x: nd tensor (...xMxN).
y: nd tensor (...xMxN). A tensor of the same shape as x
Returns:
cosine_Similarity: A (n-1)D tensor representing the cosi... |
4c26cc06189c82aaa30959b7002c77fbfaa05b22 | gayathrireddyt/Python | /Scripts/lists.py | 219 | 3.703125 | 4 | # -*- coding: UTF-8 -*-
#x = [ 1, 2, 'joe', 99]
#print len(x)
#for i in x :
#print i
#print range((len(x))
#i[1] = 5
#print i(0),i(1), i(2),i(3),i(4)
#print ['red', 24, 98.6]
t = [9, 41, 12, 3, 74, 15]
print t[2:4] |
dd5b907e7ff412313d3ea6237ab34788ed3463ac | rafaelperazzo/programacao-web | /moodledata/vpl_data/420/usersdata/346/88283/submittedfiles/exe11.py | 117 | 3.546875 | 4 | # -*- coding: utf-8 -*-
x= int(input('Digite um valor com 8 casas decimais: '))
while (x<99999999):
print('NÃO SEI') |
870eee5345fe03772263352462e4a359a4e1c578 | peqadev/python | /doc/practices/24.data_types_lists_list_comprehension.py | 1,313 | 4 | 4 | # List Comprehension
frutas_a = ["manzana", "banana", "arándano"]
frutas_b = []
for fruta in frutas_a:
if "b" in fruta:
frutas_b.append(fruta)
print(frutas_b) # ['banana']
# [expression for item in iterable if condition == True]
# Mismo comportamiento que el for anterior pero con
# list comprehension.
f... |
99fcc3f8cdd5ac4bd01cf50231e506dc72d7dcb4 | calvinxuman/python_learn | /macheal_liao/exception.py | 884 | 3.796875 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2018/3/5 14:49
# @Author : calvin
# def div(a,b):
# try:
# return int(a)/int(b)
# except ValueError:
# print('数据类型错误!')
# except ZeroDivisionError:
# print('被除数不能为零!')
# finally:
# print('计算完成')
#
# A1 = input(... |
e8f9333b42eec699c9d873afeedbb6a9ed37e242 | DarknessRdg/URI | /strings/2049.py | 441 | 3.765625 | 4 | def main():
instancia = 1
while True:
try:
assinatura = input()
linha = input()
if instancia > 1:
print()
print('Instancia', instancia)
if assinatura in linha:
print('verdadeira')
else:
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.