blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
e950719ad063b834c4b1b2bd3db5ccda2cfca0fd | Am0ralz/Technical-Interview-Questions | /WallBreakersQuestions/Multiset/SortCharactersByFrequency.py | 577 | 4.09375 | 4 | # Given a string, sort it in decreasing order based on the frequency of characters.
# Example 1:
# Input:
# "tree"
# Output:
# "eert"
#
# Example 2:
# Input:
# "cccaaa"
# Output:
# "cccaaa"
#
# Example 3:
# Input:
t ="Aabb"
# Output:
# "bbAa"
from collections import Counter
from collections import Counter
class Solut... |
0b2f1b355fc1deaff7c0e406a1b6c03636dbdab0 | KujithaMannepuri/CSPP1 | /module 20/CodeCampMatrixOperations/matrix_operations.py | 2,872 | 4.21875 | 4 | '''calculate addition and multiplication of two matrices'''
import copy
def mult_matrix(m_1, m_2):
'''
check if the matrix1 columns = matrix2 rows
mult the matrices and return the result matrix
print an error message if the matrix shapes are not valid for mult
and return None
... |
295b38cccc723aa3f9cc29c2fe7c3c67985b74f3 | Ahmed-Abdelhak/Python | /OOP/abstract class.py | 1,330 | 4.03125 | 4 | from abc import ABC, abstractmethod
class InvalidStreamOperation(Exception):
pass
class Stream(ABC): # this is an abstract class (inherits from the ABC class)
# you cannot create an obj from abstract class, it's just a contract
def __init__(self):
self.__opened = False ... |
7e0a270a5606178037285b2ac44a14b8461f465b | ValentynaGorbachenko/cd2 | /ltcd/canThreePartsEqualSum.py | 1,151 | 3.875 | 4 | '''
Given an array A of integers, return true if and only if we can partition the array into three non-empty parts with equal sums.
Formally, we can partition the array if we can find indexes i+1 < j with (A[0] + A[1] + ... + A[i] == A[i+1] + A[i+2] + ... + A[j-1] == A[j] + A[j-1] + ... + A[A.length - 1])
Example ... |
6dcb7ec671a3c5ecf57a685dd42493da2e811974 | zakuro9715/aoj | /2589.py | 407 | 3.8125 | 4 | from fractions import Fraction
import numbers
while True:
s = input()
if s == '#':
break
if s[0] == 'w':
f = Fraction(90)
else:
f = Fraction(0)
i = 1
while i < len(s):
tf = Fraction(90, pow(2, i + 1))
if s[i] == 'w':
f += tf
i += le... |
00d34a02f0a3f6297a07948c73f9c388b9895e7a | sabbir-ul-alam/pythonHackerRank | /Map and Lambda Function.py | 293 | 3.59375 | 4 | def fib(n):
a=0
b=1
res=[0]
for i in range(n-1):
res.append(b)
tmp=a
a=b
b=tmp+b
return res
n=int(input())
#print(fib(n))
# res=lambda x:x for x in range(1,n) x=x
if n==0:
print([])
else:
print(list(map(lambda x:pow(x,3),fib(n))))
|
ef29aa43db60e16743c0097aea2a2e0305fb470f | StevanCakic/SPA-2020 | /Nedelja 4/Zadaci za vjezbu 3/stack_.py | 2,126 | 4.0625 | 4 | class Stack:
def __init__(self):
self.items = []
def push(self, item):
return self.items.append(item)
def pop(self):
if not self.is_empty():
return self.items.pop()
def is_empty(self):
return len(self.items) == 0
def peek(self):
if ... |
8163184dfa470f2337e07f09718449bfc726dea4 | Andrewlearning/Leetcoding | /剑指offer/面试题57 - II. 和为s的连续正数序列(滑动窗口).py | 1,821 | 3.546875 | 4 | """
输入一个正整数 target ,输出所有和为 target 的连续正整数序列(至少含有两个数)。
序列内的数字由小到大排列,不同序列按照首个数字从小到大排列。
示例 1:
输入:target = 9
输出:[[2,3,4],[4,5]]
示例 2:
输入:target = 15
输出:[[1,2,3,4,5],[4,5,6],[7,8]]
"""
class Solution(object):
def findContinuousSequence(self, target):
"""
:type target: int
:rtype: List[List[... |
452aeb3298d0d47d94abeaf32ac922ccd70d62b1 | leandro-alvesc/estudos_python | /guppe/exercicios/secao_04/ex010.py | 159 | 3.6875 | 4 | # Leia uma vel em km/h e apresente conv em m/s
vel = float(input("Digite a velocidade em Km/h: "))
conv = vel / 3.6
print(f"A velocidade em m/s é: {conv}")
|
090fa7b4bd018a44463a510596e69b77b112a795 | parkjaewon1/python | /ch01/mult1.py | 289 | 3.625 | 4 | print(4 * 5)
# 문자열에 곱하기 하면 반복 횟수
print("대박! " * 5)
print(3 ** 3)
print('나눗셈 : ', 13 / 5)
print('몫 : ', 13 // 5) # 몫
print('나머지 : ', 13 % 5) # 나머지
a = b = c = 0 # a,b,c에 0을 대입
print('a = ', a)
print('b = ', b)
print('c = ', c)
|
f855a481bd61abdcaf71c09ae0dd190b42d951b6 | lucasclaude3/mastermind | /mastermind.py | 4,088 | 3.640625 | 4 | #!/usr/bin/env python
# coding: utf-8
import numpy as np
class Game:
def __init__(self):
self.couleurs = ['R', 'J', 'B', 'O', 'V', 'N']
self.nombre_essais = 1
self.board = []
print('Bienvenue dans mon petit jeu de Mastermind !')
print('J\'espere que tu vas t\'enjailler en t... |
604a12911907d26336d086e8798762430ee976b4 | Z3Prover/z3 | /examples/python/bounded model checking/bubble_sort.py | 2,466 | 3.625 | 4 | # File name: bubble_sort.py
#
# BUBBLESORT - Copyright (c) June, 2020 - Matteo Nicoli
from z3 import Solver, Int, Array, IntSort, And, Not, If, Select, Store, sat
def init(i,j) :
return And(i == 0, j == 0)
def invert(A0, A1, tmp, i0, i1) :
return If(Select(A0, i0) > Select(A0, i0 + 1), \
... |
73eb729ca690cde5908aa337d0c4c2d588b20860 | djones2/Python | /DataStructures/DoublyLinkedList.py | 2,292 | 3.9375 | 4 | import sys
import random
"""
Linked list implementation.
"""
class DoublyLinkedList:
def __init__(self):
self.head = None
def printList(self):
temp = self.head
while temp:
print(temp.data, end=" ")
temp = temp.next
print("")
def insert(self, data... |
35406fde67379e1833dca7d0d5bbb146e38b576a | sanneabhilash/python_learning | /Concepts_with_examples/lambdas/lambda.py | 555 | 4.03125 | 4 | add_l = lambda x, y: y / x
result = add_l(2, 4)
print(result)
print(add_l)
print(type(add_l))
# lambda function to determine max of two numbers
maximum = lambda x, y: x if x > y else y
# lambda function to determine min of two numbers
minimum = lambda x, y: x if x < y else y
max3 = lambda x, y, z: z if z > (x if x >... |
3b8684c6d2dea2b3143ca9db253a6ea98d69fa28 | LorenzoVaralo/ExerciciosCursoEmVideo | /Mundo 2/Ex069.py | 1,953 | 3.875 | 4 | #Crie eum programa que leia a idade e o sexo de verias pessoas.
# A cada pessoa cadastrada o programa deverá perguntar se o usuario
# quer ou não continuar. No final, mostre;
# A) quantas pessoas tem mais de 18 anos.
# B) Quantos homens foram cadastrados.
# C) Quantas mulheres tem menos de 20 anos.
tot18 = tot... |
cf440bb166cad9a3eb8e86b12211355f66bf19bc | vlong638/VL.Python | /0.Basis/3.Algorithoms/Completed/2.109.数字三角形.py | 1,238 | 4 | 4 | class Solution:
"""
@param triangle: a list of lists of integers.
@return: An integer, minimum path sum.
给定一个数字三角形,找到从顶部到底部的最小路径和。
每一步可以移动到下面一行的相邻数字上。
"""
def minimumTotal(self, triangle):
# write your code here
if len(triangle)==None:
return None
if len(t... |
f83a6a1eb05c0cef621b8e9ef890796a576960ea | TheFatPanda97/Introduction-to-Python | /Assignment 3/handins/Michael_TianA3.py | 2,637 | 4.1875 | 4 | from typing import List, Dict
A = ["", "", ""]
B = ["", "", ""]
C = ["", "", ""]
possible_moves = ["A1", "A2", "A3", "B1", "B2", "B3", "C1", "C2", "C3"]
lines = ["A", "B", "C", "1", "2", "3", "/", "\\"]
game_board = [A, B, C]
"""
This is the logic portion of Tic Tac Toe game you are in charge of.
Note: store this and... |
26b497e8357ec33505980170a6779f70cf942c91 | salahuddinjony/Python- | /practice of python/volume of sphere.py | 110 | 4.15625 | 4 | radius=float(input("Enter the radius of volume:"))
volume_sphere=4/3*3.1416*radius**3
print(volume_sphere)
|
8d1f2e329cd4e2ca29cbe8c87690a16e72ae3a4a | runtime7error/Atividade_Unip | /Ativ_9.py | 373 | 3.765625 | 4 | i = 0
soma_idade = 0
while i < quantidade:
idade = int(input("Informe a idade: "))
soma_idade = soma_idade + idade
i += 1
media_idade = soma_idade / quantidade
print("Média das idades é: ", media_idade)
if 0 <= media_idade <= 25:
print('Turma jovem')
if 26 <= media_idade < 60:
print('Turma adulta... |
837fb5d15b9e75edf875df62b052897c6baabf02 | harmankaler2000/Python-Mini_Projects | /sudoku_solver.py | 2,993 | 4.09375 | 4 | def find_next_empty(puzzle):
#finds the next row, col on the puzzle that is not filled yer -->rep with -1
#return row, col tuple (None, None) is there is none
#we are using 0 - 8 indices
for r in range(9):
for c in range(9): #range(9) is 0,1,..8
if puzzle[r][c] == -1:
... |
ea5aa701585cf9c4c245cd387b093ef7db39e3e8 | Oldby141/learning | /day7/属性方法.py | 660 | 3.90625 | 4 | #!_*_coding:utf-8_*_
class Dog(object):
def __init__(self,name,food):
self.name = name#调用的不是这个name
self.__food = food#None
#@staticmethod#实际上和类没关系了
#@classmethod #没用过e
@property
def eat(self):
print("%s is eating %s"%(self.name,self.__food))
@eat.setter
def eat(self,... |
bed864865b73d1f14d782d8e0fcd33df987a10ef | kathuman/Python-Experiments | /Python-Games/Python-Chess/ChessEngine.py | 2,367 | 3.890625 | 4 | """
https://www.youtube.com/watch?v=EnYui0e73Rs
This class is responsible for
1.- storing all of the information about the current state of the chess game
2.- Determining the valid moves at the current state
3.- Keep a move log.
"""
class GameState():
def __init__(self):
# board is an 8x8 2d list and each... |
7fe8846795aada33c0941e714ed2acb1f8045d6d | TomKingUK/python-sorting-algorithms | /insertion_sort.py | 569 | 4.3125 | 4 | #### Insertion Sort ###
'''
https://en.wikipedia.org/wiki/Insertion_sort
'''
def insertion_sort(arr):
# From second element to last element in array
for i in range(1, len(arr)):
# While current element larger than previous element
# (1 >= 1 checks if previous element exists)
while arr[i - 1] > arr[i] and i >= 1... |
ae97a83fced7bbb2dac14583ab5359b815c45d8c | naveenramees/python-pro | /count.py | 221 | 3.84375 | 4 | a = int(input("Enter the number:"))
if a < 10:
print "1"
if a > 9 and a < 100:
print "2"
if a > 99 and a < 1000:
print "3"
if a > 999 and a < 10000:
print "4"
if a > 9999 and a < 100000:
print "5"
|
737cbe506f545627f0a9122b599fc7b839beef79 | VniciusMiranda/Web-Scraping-with-Python | /chapters/chapter3.py | 4,276 | 4.125 | 4 | """
===> Chapter 3: Starting to Crawl <===
--- code samples from the book Web Scraping with Python ---
This chapter introduce the idea of crawling trough the web or a site.
Most part of the chapter relies on teaching techniques to find external
or internal links of a page and recursi... |
95889ac7502251b799acfc580fea53e4b7824151 | Gabvaztor/ConsciencesUtils | /Prints.py | 815 | 3.703125 | 4 |
def show_percent_by_total(total, count_number):
same_line = False if total == count_number else True
pt("Total Size", total, same_line=same_line)
pt("Count number", count_number, same_line=same_line)
progress = float(((count_number * 100) / total))
progress = "{0:.3f}".format(progress)
pt("Prog... |
06fcc2e8a42b393b1d4dc27515bec12076b978f0 | xxxhycl2010/image_utility | /count_files.py | 1,401 | 4.09375 | 4 | """
This script shows how to count all files in a specific directory.
"""
from argparse import ArgumentParser
import os
from collections import Counter
parser = ArgumentParser()
parser.add_argument('dir', type=str, help='target path')
args = parser.parse_args()
def get_extention(file_name=None):
"""
Return ... |
fc6bb6d7e80e2706c0ba3852cd28ee32bcd4a637 | Swarajk7/Programs | /Competitive Coding/Chrissarea.py | 307 | 3.53125 | 4 | def cross(a, b):
c = [a[1]*b[2] - a[2]*b[1],
a[2]*b[0] - a[0]*b[2],
a[0]*b[1] - a[1]*b[0]]
k= c[0]**2+c[1]**2+c[2]**2
return (k**0.5)/2.0
t=int(input())
for i in range(t):
a=map(float,raw_input().split())
b=map(float,raw_input().split())
print '%.3f'%(cross(a,b))
|
11f491da49f62a62455b9d45bd8bb202f2c5a1f6 | savchukndr/course02 | /mod06_datetime2.py | 220 | 3.96875 | 4 | import datetime
date1 = datetime.date.today()
date2 = datetime.date(2012, 3, 12)
result = date1 - date2
print(result.total_seconds())
print(type(result), result)
day = datetime.timedelta(days=1)
print(date1 + day * 3) |
9d9a03cb9224561969ecd9854b067b4ddd55508c | lutogin/project-euler | /sone_new/test.py | 499 | 3.8125 | 4 | ALPHABET = list('abcdefghijklmnopqrstuvwxyz')
def coun_alb(c_str: str) -> int:
"""Посчитывает сумму прдложения по системе a-1, b-2, c-3(номер буквы в ахлфавите) и так далее."""
raw_str = c_str.lower().split()
raw_str = "".join(raw_str)
summary = 0
for l in raw_str:
summary += (ALPHABET.in... |
0ca3d78ebe52bdf664b916ef3dd335d0dd9ffe7b | itcfangye/practices | /AI.py | 15,474 | 3.5 | 4 | #########################################################
# Last edited on June 21, 2016 #
# By Shu Cheng #
#########################################################
from graphics import*
win=GraphWin('五子棋',875,700)
win.setBackground('white')... |
cc70b7c0dba2b61e9fda0ddf7ee34801b015ad82 | qucode1/pythonCourse | /GuessingGame/v1.py | 813 | 3.984375 | 4 | from random import randint
min_number = 1
max_number = 10
answer = randint(min_number, max_number)
player = None
print("\nWelcome to my Guessing Game!\n")
while player != "n":
player = int(
input("Guess a number between {} and {}: ".format(min_number, max_number)))
if player < answer:
... |
0ddd2c54842ca83ffa3beb9ff04b6a34a6e5657b | 000x100000000000/Python | /Processing Lists/write_list.py | 471 | 3.75 | 4 | # Date: 16-09-2019
# Name: WenLong Wu
# Python programming practice
# Write list
# This program saves a list of strings to a file.
def main():
# Create a list of stings.
cities = ['New York', 'Boston', 'Atlanta', 'Dallas']
# Open a file for writing.
outfile = open('cities.txt', 'w')
# Write th... |
0e38a128a6b075c53e090d701674e4ff4b32026d | aratik711/100-python-programs | /isogram.py | 516 | 3.859375 | 4 | """
Determine if a word or phrase is an isogram.
An isogram (also known as a "nonpattern word") is a word or phrase without a repeating letter, however spaces and hyphens are allowed to appear multiple times.
Examples of isograms:
lumberjacks
background
downstream
six-year-old
The word isograms, however, is not an ... |
acef7f9c4fc4b8c3e61d64371f235d9f4219409e | gvassallo/LeetCode | /404-SumOfLeftLeaves.py | 583 | 3.78125 | 4 | # Find the sum of all left leaves in a given binary tree.
class Solution:
def sumOfLeftLeaves(self, root: TreeNode) -> int:
if root is None:
return 0
return self.helper(root, False)
def helper(self, root, is_left):
if root.left is None and root.right is None:
if... |
97f4a3b1e0a67ab4efeaf9c00e9f529a2abe998f | chinatsui/DimondDog | /algorithm/exercise/binary_tree/longest_univalue_path.py | 1,455 | 4.15625 | 4 | """
LeetCode-687
Given a binary tree, find the length of the longest path where each node in the path has the same value.
This path may or may not pass through the root.
Note: The length of path between two nodes is represented by the number of edges between them.
Example 1:
Input:
5
/ \
... |
1682d43b8528449c64882897a1f2fb56f90f7013 | cemzafer/mytest | /value.py | 133 | 3.859375 | 4 | while True:
avalue = input("Enter a city: ")
if avalue == 'quit':
break
else:
print("I'd love to go to "+avalue.title()+'!')
|
f1e708a5b92172e38f0a1ac1062ca134d25236f8 | henrypj/codefights | /Intro/12-LandOfLogic/sumUpNumbers.py | 1,323 | 4.28125 | 4 | #!/bin/python3
import sys
"""
# Description
#
# CodeMaster has just returned from shopping. He scanned the check of the
# items he bought and gave the resulting string to Ratiorg to figure out the
# total number of purchased items. Since Ratiorg is a bot he is definitely
# going to automate it, so he needs a program... |
f80da55a100a1036d02b2fd60e15f384d684cf07 | Andrewwu73/BioInformaticsAlgorithms | /ReverseComplement.py | 232 | 3.640625 | 4 | a = input("")
def flip(a):
if(a=="A"):
return "T"
if(a=="T"):
return "A"
if(a=="C"):
return "G"
if(a=="G"):
return "C"
ans = ""
for lul in a:
ans = ans + flip(lul)
print(ans[::-1]) |
52a38a914764d6c695ce254e5e1065c6bb3a12a5 | DavidNester/SoftwareEngineeringFA17 | /Project2/B/calculations.py | 498 | 3.734375 | 4 | import math
def distance_between_points(pair1,pair2):
return math.sqrt(((pair1[0]-pair2[0])**2 + (pair1[1] - pair2[1])**2)) #disance formula
def closest(p1, points):
#returns the index of the point closest to p1.
min_dist = distance_between_points(p1,points[0])
index = 0
for i in range(le... |
33cbe1480f363e3bd10d567f19ac55cccfea9539 | JadenHeo/PS-Study | /BOJ/11509 풍선 맞추기.py | 530 | 3.703125 | 4 | class Node:
def __init__(self, data):
self.data = data
self.next = None
class LinkedList:
def __init__(self, data):
self.head = Node(data)
self.tail = self.head
def append(self, data):
self.tail.next = Node(data)
self.tail = self.tail.next
def delete(se... |
bedb31986e51c824b5511e399d2fd16080c3bbaf | S2KtheGeek/Learn_Python_Free_Professionally | /Day4/Day4.py | 2,410 | 4.40625 | 4 | '''
Hello guys so in todays class we will be learnig about:
Class
Object
attributes
behaviours
Self variable
constructor
Class is known as a user-defined datatype.
Variable - Instance and Class or Static
Types of methods - Instance, Class and Static
Passing members of one class to another - Advanced Concept Needed for ... |
e192a4f8711285e6699ae5d836fadf26a6ad8050 | Aasthaengg/IBMdataset | /Python_codes/p02383/s541760611.py | 1,648 | 3.734375 | 4 | from enum import IntEnum
class Face(IntEnum):
One=1
Two=2
Three=3
Four=4
Five=5
Six=6
class Dice:
def __init__(self):
self.top=Face.One
self.bottom=Face.Six
self.back=Face.Two
self.front=Face.Five
self.left=Face.Four
self.right=Face.Three
... |
2f2486d1366ea8071dddca53edd6e00bbe733738 | lxw15337674/leetcode | /base_algorithm/0004/Shell_sort.py | 561 | 3.5625 | 4 | # 希尔排序
list = [9, 5, 3, 8, 6, 4, 2, 0, 10, 4, 1, 8, 7]
def sort():
length = len(list)
inc = 0
while inc <= length / 3:
inc = inc * 3 + 1
while inc >= 1:
for i in range(inc, length):
tmp = list[i]
for j in range(i, 0, -inc):
if tmp < list[j - inc]... |
e00f022c44c4bc01d2dde9ac473f30da9bb3d3c2 | tousif101/DecisionTreeFromScratchPython | /binarytree.py | 1,082 | 3.75 | 4 | class Node(object):
def __init__(self,attribute,threshold, isLeaf, entropy,classification):
self.left = None
self.right = None
self.attribute = attribute
self.threshold = threshold
self.isLeaf = isLeaf
self.entropy = entropy
self.classification = classificatio... |
7ef3b22640cccd099a2d29c9d9ca44cedfc4dcdd | GuhanSGCIT/Trees-and-Graphs-problem | /maximum sum.py | 1,880 | 3.703125 | 4 | """
Given an array of size N and two integers K and S, the special sum of a subarray is defined as follows:
(Sum of all elements of the subarray) * (K - p * S)
Where p = number of distinct prime factors of “product of all elements of the subarray”.
Find the maximum sum by considering all non-empty subarrays of the ... |
bbc2845746db5b2fc479d6ab1e2c4165572ee8ff | Vijay1234-coder/data_structure_plmsolving | /SEARCHING AND SORTING/Binary Search/AllocateMinNumOfPages.py | 1,664 | 3.984375 | 4 | '''BEST QUESTION OF BINARY SEARCH '''
'''Allocate minimum number of pages
Difficulty Level : Hard
Last Updated : 12 May, 2021
Given number of pages in n different books and m students. The books are arranged in ascending order of number of pages.
Every student is assigned to read some consecutive books. The task is to... |
9cd9b344a260e9aa8b608a131e9b54264731f776 | vikrambahadur/super_simple_stocks | /sss_calculator_trade_book_test.py | 1,464 | 3.546875 | 4 | import unittest
import pandas as pd
from sss_calculator import TradeBook
class Test_SSS_Calculator_Trade_Book(unittest.TestCase):
""" Test class to test Trade book functions"""
def setUp(self):
"""read the stock prices and initialize the trade book data frame"""
self.tradeBook = TradeBook( pd.... |
ccbe34206851582616d7180e3a505a1a10185e45 | juhom205/guess-my-number | /main.py | 1,920 | 4.03125 | 4 |
import random
attempts_list = []
print("-------------")
print("Made by juhom")
print("-------------")
def show_score():
if len(attempts_list) <= 0:
print("There is no high score.Take it or leave")
else:
print("The current high score is {} attempts".format(min(attempts_list)))
def start_game... |
81e5e0b66bd8e60d2ad0e77192c5d78ddcfaf15c | ryliemn/leetcode-python-solutions | /solutions/0226_invert_binary_tree/invertBinaryTree.py | 324 | 3.703125 | 4 | class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
def invertTree(root):
if root == None:
return None
else:
tmp = root.left
root.left = invertTree(root.right)
root.right = invertTree(tmp)
return ... |
0e151d2635273909d3b672c7d25a8c93d2a5dd35 | gustavost26/project_python | /aula/3º/ex2d.py | 583 | 3.75 | 4 | __author__ = 'gustavo'
#coding:utf8
#Jogo de acerte o número
import os #Biclioteca de funcoes do sistema operacional
import random
random.seed()
valor = random.randint(1, 50)
chute = 0
tentativas = 0
os.system('clear')
while chute != valor:
chute = int(input("Digite o seu palpite: "))
tentativas = tentativ... |
125cb0dd9e51be784beac4da445ac5a7070b824f | Carmen-1973/carmennuno | /aprender_con_Alf_ejercicios/Tipos_de_datos_simples/datos_simples_alf_ejercicio10/main.py | 534 | 4.25 | 4 |
"""
Escribir un programa que pida al usuario dos números
enteros y muestre por pantalla la <n> entre <m> da un
cociente <c> y un resto <r> donde <n> y <m> son los
números introducidos por el usuario, y <c> y <r> son
el cociente y el resto de la división entera
respectivamente.
"""
n = int(input("In... |
3bbcd38dee7841dda72d615865df33224b24d8f2 | mustafraca/Python-Ornekler | /2-Koşullu Durumlar/BedenKitleIndeksi.py | 685 | 3.96875 | 4 | #Problem 1
#Kullanıcıdan alınan boy ve kilo değerlerine göre beden kitle indeksini hesaplayın ve şu kurallara göre ekrana şu yazıları yazdırın.
# Beden Kitle İndeksi: Kilo / Boy(m) * Boy(m)
# BKİ 18.5'un altındaysa -------> Zayıf
# BKİ 18.5 ile 25 arasındaysa ------> Normal
# BKİ 25 ile 30 arasındaysa --------> Fa... |
b48f1b066fa523ab39aceffe44f8d427b2033c02 | Mr-Phoebe/ProgramLanguage | /Python Example/python 100 examples/077.py | 342 | 3.90625 | 4 | # -*- coding: UTF-8 -*-
'''
【程序77】
题目:填空练习(指向指针的指针)
1.程序分析:
2.程序源代码:
'''
if __name__ == '__main__':
s = ["man","woman","girl","boy","sister"]
for i in range(len(s)):
for j in range(len(s[i])):
print s[i][j],
print ""
|
5cc6fbe665ea1ace7110ba7e00ce97cd39bf3e77 | Dave11233/leetcode | /leetcode/leetcode1019.py | 732 | 3.828125 | 4 | from typing import List
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
def nextLargerNodes(self, arr):
if not arr:
return []
ans = [0] * len(arr)
stack = []
for i, num in enumerate(arr):
if len(sta... |
dc9a49914bef8adbf2ab0faacff4567156957743 | fennesz/ITROB-LAB1 | /drinkChoice/getUserInput.py | 669 | 3.578125 | 4 | import time
import pygame
def get_key_input():
try:
drinkInput = int(raw_input('Input'))
except ValueError:
print "Ivalid input"
return drinkInput
def ask_for_input(self, drinkInput):
print "Which drink to you want me to mix? You have to following options: \n Press 1 for Screwdriver w... |
1ecfb73fdf1a0fbfec1a473e2a1eecf9c3f08e96 | SaraKenig/codewars-solutions | /python/6kyu/uniq (UNIX style).py | 427 | 4.03125 | 4 | # Implement a function which behaves like the uniq command in UNIX.
# It takes as input a sequence and returns a sequence in which all duplicate elements following each other have been reduced to one instance.
# Example:
# ['a','a','b','b','c','a','b','c'] --> ['a','b','c','a','b','c']
def uniq(seq):
if not seq... |
f6f3281aea30f62722462f8febf8b8a35e6f3dd9 | grung3/PP-calculator | /Untitled-1.py | 502 | 4.28125 | 4 | print("Hello, and welcome to the pp identifier. Please enter your pp size ")
original = input("Please enter your pp size: ")
if ((original >= 'a' and original <= 'z')
or (original >= 'A' and original <= 'Z')):
print("That is not a number. Please enter a digit.")
elif original.isalpha and (original >=... |
923b29b86f5ba594c5ddb107638848dd4f6173e6 | Wahid259/Anisu-lslam | /AnisulIslamPython/PythonCode/range function1.py | 182 | 3.671875 | 4 |
num = list(range(10))#0-9 er range ase
print(num)
print(num[2])
num = list(range(5,11))#5-11 er range ase
print(num)
num = list(range(2,101,2))#2-100 & 2 kore interval
print(num)
|
0ecbd6f05ccc9149b1340bf9f2d48fb3b58e7bb6 | jenninrk/CalculatorRJ2 | /src/Calculator.py | 378 | 3.53125 | 4 | class Calculator:
def plus(self, x, y):
return int(x) + int(y)
def minus(self, x, y):
return int(x) - int(y)
def multiply(self, x, y):
return int(x) * int(y)
def divide(self, x, y):
return float(x) / float(y)
def squared(self, x):
return int(x) ** 2
... |
d8c25f2cc4100b93e555396e1e870510078b6473 | vishalkhondre/learnPython | /012-py-learnfunction-script.py | 848 | 3.953125 | 4 | def main():
shapestr = shape(triangle)
print(shapestr)
sayhelloword = decoratorexample(1)
print(type(sayhelloword))
print(id(sayhelloword))
print(sayhelloword)
def triangle(fname):
return f"Hi {fname}, this is triangle"
def circle(fname):
return f"Hi {fname}, this is circle"
def s... |
cabd11717e9b96ee7c1610e15c2d26db7d19a1dc | MichaelJones590/Intro_to_Data_Science | /Michigan_Intro to Data Science/DS07_Asmt2_Q2.py | 1,571 | 3.625 | 4 | # Include the file setup
import pandas as pd
df = pd.read_csv('olympics.csv', index_col=0, skiprows=1)
for col in df.columns:
if col[:2]=='01':
df.rename(columns={col:'Gold'+col[4:]}, inplace=True)
if col[:2]=='02':
df.rename(columns={col:'Silver'+col[4:]}, inplace=True)
if col... |
e48ecb35c15b1c4f036fe900d9f08716b5c29746 | maciejratajski1999/Algorytmy-i-struktury-danych-python | /Fraction.py | 4,949 | 4.21875 | 4 | class Fraction:
'''
Class Fraction
acts as a Fraction of two integers: nominator / denominator
'''
def __init__(self, num, dem):
'''
:param num (int): Numerator of a Fraction
:param dem (int): Denominator of a Fraction
given parameters are tested, if val... |
53249f4e7c0012a6104c41cc21a8de3722d1885b | dshah98/Python_Pattern | /Number Pattern/Pattern28.py | 210 | 3.734375 | 4 | '''
1 3 5 7
3 5 7 1
5 7 1 3
7 1 3 5
'''
n = int(input("Enter Number: "))
n = n*2
for i in range(1, n+1, 2):
for j in range(i, n+i, 2):
print((j-1) % n + 1, end="")
print("")
|
644f33d9b5706a7c259a1bb8ae2b8f3e519cef66 | swl5571147a/stone | /notes/example/f1.py | 867 | 3.625 | 4 | #!/usr/bin/env python
#coding:utf8
def pp():
print 'pp'
class Person(object):
count = 0
def __init__(self,name,sex):
self.name = name
self.sex = sex
Person.add_count()
print 'Now %s is created!There are %s users!'%(self.name,Person.get_count())
def __del__(self):
Person.minus_count()
print 'The use... |
5376a1abf58297eb2f6f81aaf1d65c65ae1d2829 | kashifpk/smpp5 | /smpp5/smpp5/lib/parameter_types.py | 3,194 | 3.8125 | 4 | """
Parameter Type Definitions
==========================
SMPP supports 4 types of parameters, Integer, CString, String and TLV. This module contains
classes for encoding and decoding these parameter types
"""
import struct
class Integer(object):
"""
Integer SMPP Parameter Type. Integers can be of length 1,... |
c9395667a113c81ef9eb63e567c5c3d6b8c1169d | ahmadmowalad/python | /conditions.py | 198 | 3.859375 | 4 | username=input("please insert your name : ")
passwor=input("please insert your password : ")
if username=='ahmad' and passwor=='123':
print('welcome to your email')
else:
print('error') |
b2bf621d29b66488990ab9d44476c720c78d1e49 | Paulo-Felipe-96/guppe | /exercicios/seção 5/ex04.py | 169 | 3.90625 | 4 | import math
n = float(input('Digite um número: '))
if n > 0:
print(f'{n} ao quadrado: {n * n}')
print(f'Raiz quadrada de {n}: {round(math.sqrt(n), 2)}')
|
8dd6d0482852e8d32007f532e8210952d93e118a | sunimalherath/organize-files | /organize.py | 1,450 | 3.546875 | 4 | import os
from pathlib import Path
SUBDIRECTORIES = {
"DOCUMENTS": ['.doc', '.docx', '.pdf', '.rtf', '.txt'],
"AUDIO": ['.mp3', '.wav', '.m4a', '.m4b'],
"VIDEO": ['.mp4', '.avi', '.mov'],
"IMAGES" : ['.jpg', '.jpeg', '.png', '.gif']
}
def getDirectory(file_extension):
for directory, extensions in ... |
b41a46c2456f1f535711187aabae3eb36da81647 | binodpanta/python-demos | /functions.py | 1,875 | 4.4375 | 4 | """Exploring function behavior in Python"""
"""
This will do what?
"""
# In the version shown in comments below, the default value empty for L is only evaluated o nce
# So for calls beyond the first one, L is already set!
"""
def f(a, L=[]):
L.append(a)
return L
"""
def f(a, L=None):
if L is None:
... |
dd00210be9949b96d85ade416d85ce86244081b0 | kayeschong/financial-systems-design | /lessons/week4/shape_polymorphism.py | 1,504 | 4.46875 | 4 | from math import pi
class Shape:
# There are no instance variables.
def area(self):
# "In user defined base classes, abstract methods should raise
# NotImplementedError when they require derived classes to override
# the method [...]."
raise NotImplementedError("Non-sp... |
df63b0c9ea1fec7e8d42e41f0558835e91551e14 | HsiangHung/Code-Challenges | /leetcode_solution/string/#648.Replace_Words.py | 872 | 3.8125 | 4 | # [#648] Replace Words
#
# Uber
#
class Solution(object):
def replaceWords(self, dict, sentence):
"""
:type dict: List[str]
:type sentence: str
:rtype: str
"""
sentence = sentence.split(" ")
min_dict = min([len(word) for word in dict])
sent_di... |
40ee95dd2e59f96eff314da3f0bb6fecc582eca2 | fengjiachen/leetcode | /300_349/303_Range_Sum_Query_Immutable.py | 643 | 3.546875 | 4 | class NumArray:
def __init__(self, nums: [int]):
if len(nums) == 0:
self.sum = []
else:
self.sum = [0] * len(nums)
self.sum[0] = nums[0]
for i in range(1, len(nums)):
self.sum[i] = self.sum[i-1]+nums[i]
def sumRange(self, i: int, ... |
58a35d83284f70a753788079157c8e7872c7d6ce | kaihami/tevec-rh | /data_science/caixa_eletronico.py | 4,736 | 3.828125 | 4 | import sys
class ATM():
"""
ATM class
"""
def __init__(self, bills = [50,20],
message_error = 'Sua mensagem de erro'):
'''
Here the ATM class have some flexibility,
Like the bills used when withdrawing cash is not hardcoded.
Also the error message is... |
f5db163ec6d94312f12c216cf4577f8c27c83147 | luisdomal/Python | /S1/tablas_multiplicar.py | 446 | 4.03125 | 4 | print("Ingresa el número: ")
n = input()
numN = int(n)
print("{} x 1 = {}".format(n, numN))
print("{} x 2 = {}".format(n, numN*2))
print("{} x 3 = {}".format(n, numN*3))
print("{} x 4 = {}".format(n, numN*4))
print("{} x 5 = {}".format(n, numN*5))
print("{} x 6 = {}".format(n, numN*6))
print("{} x 7 = {}".format(n, nu... |
b70aeaefc1112a5c5b21bd1c8f69af257f4ff2cf | sarathreddynaidu/Python-Concepts | /OOP/properties.py | 522 | 3.828125 | 4 | class Human:
def __init__(self, first, last, age):
self.first = first
self.last = last
self._age = age
@property
def age(self):
return self._age
@age.setter
def age(self, value):
self._age = value
@property
def full_name(self):
return f"{self.first} {self.last}"
@full_name.setter
def full_nam... |
8dbe32ea1274f704037c7b1cb82ebb6a458e54a7 | ShaojieLiu/sicp_js | /lecture/Lec2a_model_high_class.py | 985 | 3.796875 | 4 |
def close_enough(old, new):
return abs(old - new) < 0.001
def fixed_point(f, start):
# 这个方法来计算不动点:
# 思路就是不断把得数带入自变量里
# 前提条件是 这个过程 是收敛的
def iter(old, new):
if close_enough(old, new):
return new
else:
return iter(new, f(new))
return iter(start, f(start))
... |
7962e78c661ff779ae6e876cc9dc40c3817e6026 | spiralware/ArraySortAlgorithms | /array_sort_algos.py | 2,013 | 4.1875 | 4 | #предполагаем, что во всех алгоритмах нужно
#отсортировать целочисленный массив по возрастанию
#сортировка пузырьком
def bubble_sort(array):
for i in range(0, len(array) - 1):
for j in range(0, len(array) - 1 - i):
if array[j] > array[j+1]:
array[j], array[j + 1] = array[j + 1],... |
904af5474a9e1da1f4a304acf92a9e755600a0f6 | ProjektOsmium/All-Algorithms | /greedy/Python/huffman_encoding.py | 2,082 | 3.5625 | 4 | '''
Huffman Coding | Greedy algorithm
'''
import heapq
class Node:
def __init__(self, frequency, symbol=None, left=None, right=None):
self.f = frequency
self.s = symbol
self.l = left
self.r = right
def __lt__(self, other):
return self.f < other.f
def __str... |
3885c2df1366843be7eb59a28a28d59aef7ff4de | SothernyKosal/Data-Structure-Lessons-Code | /Data Structure-Task-cns-atcoder/Delimiters/circular_queue.py | 1,418 | 3.78125 | 4 | #
# circular_queue = []
# maxSize = int(input("Enter the size of queue: "))
#
# for i in range(1,maxSize+1):
# circular_queue.append(i)
#
# # head = circular_queue[0]
# # tail = circular_queue[maxSize-1]
#
# print(circular_queue)
#
# ele = maxSize + 1
#
# length = len(circular_queue)
#
# if length == maxSize:
# ... |
5b434dd75d5e6c84b9eacdd2ede675e96cb9e90e | UG-SEP/Data-Structure-and-Algorithms | /Leetcode/Maximum Frequency Stack/Maximum Frequency Stack.py | 1,105 | 3.5 | 4 | #Problem:https://leetcode.com/problems/subarrays-with-k-different-integers/description/
class Solution:
def subarraysWithKDistinct(self, A: 'List[int]', K: 'int') -> 'int':
far, near, ans, maps = 0, 0, 0, {}
# use hashmap to save the subarray
# two flags, far and near
# far ... |
42e93ebb45975270913abebc6cae1388736771cb | ioniakim/python3playground | /learningPython/ch26/klass.py | 261 | 3.90625 | 4 | #!/usr/bin/env python3
class C2: ...
class C3:
def __init__(self, who):
self.name = who
class C1(C2, C3):
def setname(self, who):
self.name = who
I1 = C1('bob')
I2 = C1('sue')
I2.setname('sue')
print(I1.name)
print(I2.name)
|
f67a5dc68bad39605f1398a07c14d27634c76277 | jjmerchante/my2048 | /logic2048.py | 6,838 | 3.5625 | 4 | #!/usr/bin/python
import random
from collections import deque
class Coord():
def __init__(self, x, y):
self.x = x
self.y = y
def __str__(self):
coorStr = "[" + str(self.x) + "," + str(self.y) + "]"
return coorStr
class Board():
def __init__(self):
self.matrix = [([0... |
4fda32d0937f3304f2b2ff6aba0eab0ee6b67c7c | marciof2/PYTHON- | /desafio80.py | 334 | 3.921875 | 4 | l=[]
n=0
for c in range(0,5):
n= int(input('Digite um valor: '))
if c == 0 or n > l[-1]:
l.append(n)
else:
pos=0
while pos < len(l):
if n <= l[pos]:
l.insert(pos, n)
break
pos+=1
print(f'Os valores digitados em orde... |
0b971c8222afb1dddd8a492382a594ce573bfbb2 | jigish18/mc_js | /Areaofcircle..py | 107 | 4.09375 | 4 | pie = 3.14
r = float(input('Radius of circle in cm')
area = (pie)*(r**2)
print("Area of circle is", area )
|
fdcc324b0daf90f6193c7dc19eb4467915531c25 | ashsingh16/Ashish_test | /fn.py | 122 | 3.6875 | 4 | #!/usr/bin/python
def fn(y):
if y < 2:
return y
else:
return (fn(y-1) + fn(y-2))
for i in range(10):
print(fn(i))
|
e7e870ffa242ae5279804e5d7685fe5395271681 | saavedra29/rgkit_py3 | /rgkit/mapeditor.py | 6,245 | 3.78125 | 4 | #!/usr/bin/env python2
import ast
import tkinter
import sys
import os.path
from rgkit.settings import settings
BLOCKSIZE = 20
PADDING = 4
color_mapping = {
'a': ('black', 'obstacle'),
's': ('#ddd', None),
'g': ('darkgreen', 'spawn'),
't': ('pink', 'start1'),
'h': ('lightgreen', 'start2'),
... |
0f47c0de79c21fa9946ecf5ecf924839899af5b3 | StephanJon/Interpolation | /src/testSeqs.py | 2,836 | 3.515625 | 4 | from CurveADT import CurveT
from SeqADT import SeqT
def main():
# check = True
# while (check):
# Choice1 = input("Which would you like to test:\n"
# "linVal (1)\n"
# "quadVal (2)\n"
# "npo... |
5f739428c69358926a95ee0e72710399e1708612 | dingens/girlsday2021 | /vig.py | 1,338 | 3.9375 | 4 | #!/usr/bin/env python
# -*- coding: utf8 -*-
import string
import itertools
"""
Helpers for en- and decrypting using the Vigenère or Caesar ciphers.
(The Caesar cipher is a special case of Vigenère with a key length of one.)
"""
CHARS = string.ascii_letters
def envig(text, key):
return ''.join(vig_(text, key, +1)... |
b711cb64f4762919774c5d28911bcb3a41022ead | davidozhang/codeforces | /life_without_zeroes.py | 368 | 3.6875 | 4 | #!/usr/bin/python
'''
Problem 75A: http://codeforces.com/problemset/problem/75/A
Solved on: 2015-03-08
Result: Accepted 92 ms 8 KB
'''
def main():
first, second=raw_input(), raw_input()
if (int(str(int(first)+int(second)).replace('0','')))==int(first.replace('0',''))+int(second.replace('0','')):
print 'YES'
else... |
f50d31e0c07fd9623d3e1920c75c4b22357083de | LavrikVadim/python201 | /12121.py | 197 | 3.65625 | 4 | import matplotlib.pyplot as plt
def generate(n:int):
a= [i for i in range(n)]
b = [i ** 2 for i in range(n)]
return a,b
a,b=generate(15)
print(a)
print(b)
plt.plot(a,b)
plt.show()
|
c8657194bec70846df104e36f8149c06875f727d | boisvert42/npr-puzzle-python | /2019/0127_vehicle_author.py | 1,128 | 3.59375 | 4 | #!/usr/bin/env python
"""
NPR 2019-01-27
https://www.npr.org/2019/01/27/688759364/sunday-puzzle-slogan-scramble
Name a vehicle in two words, each with the same number of letters.
Subtract a letter from each word, and the remaining letters in order will
spell the first and last names of a famous writer. Who is it?
""... |
a6685e66883ce523f4041dca53a40623232ed5ac | SirLeonardoFerreira/Atividades-ifpi | /Atividade 01 - semana 02/questão2_d_runcodes.py | 296 | 3.671875 | 4 | def segundos(hr, minu, segun):
return (((hr * 60) + minu ) * 60) + segun
def main():
hora = int(input())
minuto = int(input())
segundo = int(input())
segundo_totais = segundos(hora, minuto, segundo)
print(f"{segundo_totais:.2f}")
if __name__ == '__main__':
main()
|
2db27c843e61699aab5d8dc17667bd2f0d89e108 | VBV-121/DJ-CSI-2019-Hackathon | /calc.py | 606 | 3.546875 | 4 | import mysql.connector
for x in range(5):
name=input("Enter Name : ")
print(name)
income=int(input("Enter Income : "))
texpense=int(input("Enter Total Expense : "))
mydb = mysql.connector.connect(host="localhost",user="root",passwd="",database="trial")
mycursor = mydb.cursor()
idlist... |
003f599a7f59bda1ae9e5722e31f145b10d65954 | ishakir/mlgames | /mlgames/board.py | 1,625 | 4.03125 | 4 | from abc import ABC, abstractmethod
class Board(ABC):
# piece should be a player signifier (e.g. X or O)
# move should be whatever type you chose move to be (e.g. (x, y))
#
# Should return new version of same type (another Board)
@abstractmethod
def play(self, piece, move):
pass
# Should return the winner's... |
b13cbcfeb4bf0fad228d0efa9960642c17f8c803 | nooneischgl/learning | /netcook/1_1_local_machine_info.py | 321 | 3.625 | 4 | #!/usr/bin/env python3
import socket
def print_machine_info():
"""Print host_name and IP address"""
host_name = socket.gethostname()
ip_address = socket.gethostbyname(host_name)
print("Host Name: %s" %host_name)
print("IP Address: %s" %ip_address)
if __name__ == '__main__':
print_machine_info(... |
86941b1b7925df8e49ece05c1df9c3bcc2069220 | Eieyron/text_pokemon | /src/classes/Pokemon.py | 946 | 3.765625 | 4 | # This class imitates a real pokemon
import random
class Pokemon():
# constructor
def __init__(self, name, health=50):
# declare attributes
self.name = name
# self.type = type
self.health = health
self.damage = 10
self.speed = random.randint(0, 5)
... |
714c3a12b017292b967f73ee409047b0899ccf5a | shihengzong/mypython | /basics/myos/myos.py | 459 | 3.828125 | 4 | # 打开个关闭文件
import os
def saveFile(dir,file,str_content):
content = str_content.encode("utf-8")
dir_name = dir
file_name = dir_name + '/' +file
# 判断文件夹是否存在
dir_exist = os.path.exists(dir_name)
if dir_exist == False:
# 创建文件夹
os.mkdir(dir_name)
# 检查文件是否存在和可读写
fd = open(file... |
dc73d08fbdcf27e6ea7257056b7fe9115162c971 | ArlindKadra/Multiplication | /model.py | 2,119 | 3.53125 | 4 | from random import uniform
from sklearn.model_selection import train_test_split
import numpy as np
class Input(object):
'''A class which is responsible for creating and feeding the input to the network.
Attributes:
x_train: numpy array with all the training inputs
x_validation: numpy array w... |
a03a3efdc7069ab79c202eba19831e934d387e6d | shbhmbnsl1/DSCareerPath | /lesson8.py | 8,051 | 4.21875 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sun Oct 28 00:24:40 2018
@author: shubansa
Data Science Career Path - Lesson 8 Pandas Foundation
"""
"""
1. Data ingestion and inspection
1.1. Reviewing pandas data frames
1.2. Building dataframes from scratch
1.3. Importing and exporting data
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.