blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
3fd8b10f31ad50fc9ca184b476cdcc2bf55dc82e | supermao/Interview_Street_Questions | /All Passed/K Difference (C++, Java, Python)/k_difference.py | 2,780 | 3.515625 | 4 | # File: k_difference.py
# Author: Chris Lewis (cmslewis@gmail.com)
# -----------------------------------------------------------------------------
# This program offers a solution to the "K Difference" challenge on the
# InterviewStreet website (URL: https://www.interviewstreet.com/challenges/
# dashboard/#problem/4e... |
9e9cc9ceca23a921eab3a3f874c7a4ef7bbbf09d | ogurdima/interviewbit | /07 - Linked Lists/Merge Two Sorted Lists/mergesorted.py | 1,253 | 4 | 4 | # Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
# @param A : head node of linked list
# @param B : head node of linked list
# @return the head node in the linked list
def mergeTwoLists(self, ... |
567a85195f474274cb5770b0a32f57c63a285542 | ogurdima/interviewbit | /07 - Linked Lists/Rotate List/rotate.py | 1,035 | 3.859375 | 4 | # Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
# @param A : head node of linked list
# @param B : integer
# @return the head node in the linked list
def rotateRight(self, A, B):
if ... |
a7a13b173d6cc62cf057f003b37be5ce20dd7a67 | TylerLangtry/CP1404_Practicals | /prac_10/pyramid.py | 148 | 3.53125 | 4 | def get_blocks(rows):
if rows <= 0:
return 0
return rows + get_blocks(rows-1)
rows = int(input("rows?:"))
print(get_blocks(rows))
|
a7532e02b07189ba14e8f113b4b162b4f664e1ec | alverad-katsuro/Python | /Atividades/PY 01/quadrado.py | 122 | 3.859375 | 4 | x = float(input("Digite o valor correspondente ao lado de um quadrado: "))
print("perímetro:", 4*x, '-', "área:", x**2)
|
63b12786cdd7d6616b6217adb7274360c978b92c | alverad-katsuro/Python | /Atividades/PY 01/horas - Copia.py | 201 | 3.875 | 4 | idade = int(input())
if (idade < 18):
print (" Não pode tirar carteira de habilitação")
else:
if (idade >= 18):
print ("Pode tirar a carteira de habilitação")
|
11b7f8a0a45d7b987c5e2c3730ee6d6ded82f7c7 | alverad-katsuro/Python | /Atividades/PY 01/fizzbuzz_funcao.py | 249 | 3.953125 | 4 | def fizzbuzz(x):
r1 = "FizzBuzz"
r2 = "Fizz"
r3 = 'Buzz'
if x%3 == 0 and x%5 == 0:
return r1
elif x%3 == 0 and not x%5 ==0:
return r2
elif x%5 ==0 and not x%3 ==0:
return r3
else:
return x
|
eb9807360f3204e41b8adc387583e45dc236b44d | alverad-katsuro/Python | /Atividades/PY 01/jogo_nimv2.py | 6,398 | 3.625 | 4 | import random
import time
import sys
import sys
def computador_escolhe_jogada(n, m):
for pc_range in reversed(range(1, m + 1)):
if m>=n:
k=n
n=n-n
print('O Computador retirou %d peça(s)' % k)
print("Eu ganhei hahhahahaha")
return k
sys... |
09e7e2476d7019472d81178b541fc5888a82de80 | alverad-katsuro/Python | /Atividades/PY 01/Baskara.py | 649 | 3.9375 | 4 | ## delta < 0 = nao tem raiz =0 1 raiz , delta > 0 =2 raiz
def main():
import math
print("A seguir calcularemos equações de 2º Grau\nLembrado que a formula geral é\nax**2+bx+c=0")
a = float(input("Insira o valor de a: "))
b = float(input("Insira o valor de b: "))
c = float(input("Insira o valor de c: "))
d = ((b**... |
aec70871bb17bcf569b304c2ec4744e6f79bf774 | alverad-katsuro/Python | /python-examples-master/pilha-poo.py | 2,673 | 4.0625 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from os import system
class Cliente(object): # Classe cliente, vazia pois pode ser atribuido
pass # propriedades mais tarde
class Pilha(object): # Classe Pilha
def __init__(self): # metodo construtor
self.pilha... |
f495091a09d56a4bc44673e2690b0873d4366814 | jhwinter/star-wars-etl | /star_wars_etl/task_two.py | 3,290 | 3.796875 | 4 | #!/usr/bin/env python3
"""Task 2
Now we would like you to pull data from the films endpoint.
We would like you to do the following:
1. Pull data for the movie A New Hope
2. Replace the data for each of the endpoints listed in the
JSON object you receive from the API request (e.g. - In the example
above ... |
ab8ecbf9c3066dabc02f3f1add44507ab823bc64 | trutadan/encryptionalgorithms | /atbashcipher.py | 727 | 3.6875 | 4 | global atbashDictionary
atbashDictionary = {'A': 'Z', 'B': 'Y', 'C': 'X', 'D': 'W', 'E': 'V',
'F': 'U', 'G': 'T', 'H': 'S', 'I': 'R', 'J': 'Q',
'K': 'P', 'L': 'O', 'M': 'N', 'N': 'M', 'O': 'L',
'P': 'K', 'Q': 'J', 'R': 'I', 'S': 'H', 'T': 'G',
'U': ... |
6a74aac767e23b31fe9071b3d28908c3f5d5856f | michaelschuff/Python | /DailyCodingChallenge/199.py | 442 | 3.78125 | 4 | #Given a string of parentheses, find the balanced string that can be produced from it using the minimum number of insertions and deletions. If there are multiple solutions, return any of them.
#For example, given "(()", you could return "(())". Given "))()(", you could return "()()()()".
a="))()("
forw=0
back=0
for x... |
cb53aba31d94756988c98e57204c469031b25a10 | michaelschuff/Python | /George Fox 2019/cliff.py | 601 | 3.8125 | 4 | def findheight(cliff,x):
currentheight=0
for i in range(len(cliff)-1,0,-1):
if(cliff[i][x]=="C"):
currentheight+=1
else:
break
return(currentheight)
cliff=[]
for x in range(int(input())):
cliff.append(input())
currentheight=findheight(cliff,0)
biggestdif=0
current... |
edee73c05cf144c39462fa2bed3ad8d46fa34b4a | michaelschuff/Python | /GeorgeFoxPractice/2018/Draw.py | 1,643 | 3.828125 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat Mar 9 12:19:12 2019
@author: eatdacarrot
"""
def rectangle(r,c,filled):
for x in range(r):
if(filled or x==0 or x==r-1):
print("#"*c)
else:
print("#"," "*(c-2),"#",sep="")
def left(x,filled):
for z in ran... |
d78a069ebe597d07fe923aa51d71d087afd037f9 | KathleneTitus/ENGG3130-Final-Project | /logistic_map.py | 1,653 | 3.625 | 4 | import matplotlib.pyplot as plt
import numpy as np
# assume x between 0 and 1
def logistic_eqn(rate,x):
return rate * x * (1 - x)
def logistic_eqn_2(rate,x):
return rate * x * (1 - x**2)
def logistic_eqn_3(rate,x):
return rate * x * (1 - x**3)
# Double the penalty
def logistic_eqn_power(rate,x,n):
... |
19192d74c28ae01fe96057f02fadfcc6408c1860 | jm8084/CSCI320-spoiledMilk | /application/commands/CreateAccount.py | 1,330 | 3.609375 | 4 |
from datetime import datetime
import psycopg2
class CreateAccount():
def get_inputs(self):
username = input('Username: ')
email = input('Email: ')
password = input('Password: ')
fname = input('First Name: ')
lname = input('Last Name: ')
return (username,e... |
5ea709a4d157f8c2e11934bd769d6f1e61d7a659 | nastevens/sandbox | /python/flushbot/src/hands.py | 19,946 | 3.5625 | 4 | import stacks
from card import card
def groups(cards):
'''Checks for groups of cards
Returns a list of lists with the cards grouped by rank'''
group = []
for v in range(0,13): group.append([])
for card in cards: group[card.rank()-1].append(card)
return group
def flushes(cards):
'''Chec... |
6ab1b84574e0bc25f31b50072f45e18c22be3fcb | nastevens/sandbox | /python/thinkcomplexity/RandomGraph.py | 901 | 3.515625 | 4 | import random
import string
from Graph import Graph, Vertex, Edge
class RandomGraph(Graph):
def add_random_edges(self, p=0.05):
def random_add(g, x, y):
if random.random() < p:
g.add_edge(Edge(x, y))
vs = self.vertices()
self._handshake(random_add, vs[0], vs[1:... |
6f0aec480493801db0034a40dd0c9299c10d273d | nlin1575/ROAR-Academy | /samples/perceptron.py | 2,838 | 3.53125 | 4 | ## This is course material for Introduction to Modern Artificial Intelligence
## Example code: perceptron.py
## Author: Allen Y. Yang, Intelligent Racing Inc.
##
## (c) Copyright 2020. Intelligent Racing Inc. Not permitted for commercial use
# Please make sure to conda install -c conda-forge keras
import keras
from k... |
e4c9201961e4a7ea7d4b22dfda4c032ddfc23a0d | nlin1575/ROAR-Academy | /samples/grayscale_image.py | 1,079 | 4.40625 | 4 | ## This is course material for Introduction to Python Scientific Programming
## Example code: grayscale_image.py
## Author: Allen Y. Yang
##
## (c) Copyright 2020. Intelligent Racing Inc. Not permitted for commercial use
# Please do <pip3 install matplotlib> and <pip3 install pillow> first
from matplotlib import image... |
5aa42b6953282d1709ea334fa8cb955e22b0162e | jabedkhanjb/Hackerrank | /Python/Itertools/Maximize_it.py | 1,521 | 3.796875 | 4 | """
Problem :
You are given a function f(x) = x^2. You are also given k lists. The ith list consists of Ni elements. You have to pick one element from each list so that the value from the equation below is maximized:
S = ( f(X1) + f(X2) + ......+ f(Xk))%M
Xi denotes the element picked from the ith list . Find the m... |
d7963f98a734159526a8021f123f5a67ff3913be | jabedkhanjb/Hackerrank | /Python/Itertools/Compress_the_string.py | 979 | 4 | 4 | """
# Compress the String!
# In this task, we would like for you to appreciate the usefulness of the groupby() function of itertools . To read more about this
# function, Check this out .
# You are given a string S. Suppose a character 'c' occurs consecutively X times in the string. Replace these consecutive occurren... |
6551679e5cd9d9c6feb254c8df4eaa2614a191d0 | jabedkhanjb/Hackerrank | /30-Days-of-Code/Day5:_Loops.py | 521 | 4.125 | 4 | # Day 5: Loops
# Task
# Given an integer, N, print its first 10 multiples. Each multiple N * i (where 1 <= i <= 10) should be printed on a new line in the form:
# N x i = result.
# Input Format
# A single integer, N.
# Constraints
# 2 <= N <= 20
# Output Format
# Print 10 lines of output; each line i (where 1 <= i... |
b675f0b403a87f9c133b97bf411ecdba7678c785 | jabedkhanjb/Hackerrank | /30-Days-of-Code/Day15:_Linked_List.py | 2,237 | 4.4375 | 4 | """
Objective
Today we will work with a Linked List. Check out the Tutorial tab for learning materials and an instructional video.
A Node class is provided for you in the editor. A Node object has an integer data field, , and a Node instance pointer, , pointing to another node (i.e.: the next node in the list).
A Nod... |
425ad62382ad0fc5e8308a0a5dff3f4c14242149 | jabedkhanjb/Hackerrank | /10_Days_of_Statistics/Day0/Weighted_Mean.py | 2,168 | 4.5625 | 5 | """
Objective
In the previous challenge, we calculated a mean. In this challenge, we practice calculating a weighted mean. Check out the Tutorial tab for learning materials and an instructional video!
Task
Given an array, , of integers and an array, , representing the respective weights of 's elements, calculate and ... |
dc2ce2e7c509829eb4c1a4dce90c631afd7e4cfa | jabedkhanjb/Hackerrank | /30-Days-of-Code/Day6:_Review.py | 1,851 | 4.125 | 4 | """
Objective
Today we’re expanding our knowledge of Strings and combining it with what we’ve already learned about loops. Check out the Tutorial tab for learning materials and an instructional video!
Task
Given a string, S, of length N that is indexed from 0 to N - 1, print its even-indexed and odd-indexed character... |
65ed44455b5f8080d365d169d8a3225612729efb | JohnGoure/leetcode-solutions | /imageRotation.py | 305 | 3.765625 | 4 | def rotate(image):
temp = [[0 for x in range(len(image))] for x in range(len(image))]
size = len(image)
for x in range(size):
for y in range(size):
temp[size - x - 1][y] = image[size - y - 1][x]
return temp
image = [[1,2,3,4] for x in range(4)]
print(rotate(image)) |
73cb5ce9e27de1a9ee83ab047da4b0f8d72fbf18 | fagomezm/Mechanika-Nieba | /Tutoriales Python/Operaciones Basicas.py | 3,256 | 4.03125 | 4 | # -*- coding: utf-8 -*-
"""
Editor de Spyder
Este es un archivo temporal
"""
#Definicion de Variables
a=26
b=11.3
c=5
d=3.5
#Operaciones Matematicas Basicas
print(a+b)
print(c-a)
print(d*c)
print(c**2) #Exponente
print(c/a)
print(int(c/a)) #Division Entera
print(7%3) #Modulo
#Textos
cads="Text... |
cf349373595ecf7ded3c91bab34ce3c2c48482c7 | yoginee15/Python | /venv/Add.py | 84 | 3.890625 | 4 | x=int(input("Enter 1st number"))
y=int(input("Enter 2nd number"))
z=x+y
print("z",z) |
4dff9f8d3e0430aa7f471bb366e0e526c514d402 | junaidkhan07/assignment-2 | /p#2.py | 264 | 3.859375 | 4 | numbers = [5,3,10,100,200,300,400,500,600,700,800,900,50]
max_num=numbers[0]
min_num=numbers[0]
for i in range(1,len(numbers)):
if numbers[i]>max_num:
max_num=numbers[i]
if numbers[i]<min_num:
min_num=numbers[i]
print(max_num)
print(min_num)
|
43f5770a5d86257e309fed1fa956bed9911662cc | numeoriginal/multithread_marketplace | /marketplace.py | 4,404 | 4.3125 | 4 | """
This module represents the Marketplace.
Computer Systems Architecture Course
Assignment 1
March 2021
"""
import threading
class Marketplace:
"""
Class that represents the Marketplace. It's the central part of the implementation.
The producers and consumers use its methods concurrently.
"""
de... |
3d5dd3fceb062ac3b0425121721001982984d9cf | PHILLIPEBLOOD/pythonquestions | /sequencial/quest10.py | 240 | 4.09375 | 4 | # Faça um Programa que peça a temperatura em graus Celsius,
# transforme e mostre em graus Fahrenheit.
def convertertemperatura(C):
return (C * 9) / 5 + 32
C = int(input("Celsius: "))
print(convertertemperatura(C), "farenrait")
|
f8517755e91bf286f31ba6ce13a4ea2a89b83cb5 | PHILLIPEBLOOD/pythonquestions | /decisao/questd28.py | 1,643 | 4.09375 | 4 | '''O Hipermercado Tabajara está com uma promoção de carnes que é imperdível.
Confira:
Até 5 Kg Acima de 5 Kg
File Duplo R$ 4,90 por Kg R$ 5,80 por Kg
Alcatra R$ 5,90 por Kg R$ 6,80 por Kg
Picanha R$ 6,90 por Kg R$ 7,80 por Kg
Para atender a... |
5620ac78818993d0adcef5d8b2fa4369ea2a729e | PHILLIPEBLOOD/pythonquestions | /decisao/questd23.py | 250 | 4.125 | 4 | '''Faça um Programa que peça um número e informe
se o número é inteiro ou decimal.
Dica: utilize uma função de arredondamento.'''
number = float(input("Numero: "))
tipo = "Decimal"
if(round(number) == number):
tipo = "Inteiro"
print(tipo)
|
a7f44963c76e1f878b238c84a570c8037367ed6d | PHILLIPEBLOOD/pythonquestions | /repeticao/questr14.py | 337 | 3.90625 | 4 | '''
Faça um programa que peça 10 números inteiros, calcule e mostre a
quantidade de números pares e a quantidade de números impares.
'''
par = 0
impar = 0
for n in range(1, 11):
numero = int(input("Digite: "))
if numero % 2 == 0:
par += 1
else:
impar += 1
print("Pares: ", par)
print("Impares... |
e994725d5d72f116bcc1fbe2c6fcf0c0fd8717c0 | PHILLIPEBLOOD/pythonquestions | /sequencial/quest13.py | 418 | 3.875 | 4 | #Tendo como dado de entrada a altura (h) de uma pessoa,
# construa um algoritmo que calcule seu peso ideal,
# utilizando as seguintes fórmulas:
# Para homens: (72.7*h) - 58
# Para mulheres: (62.1*h) - 44.7
h = float(input("Altura: "))
sexo = input("Sexo: ")
if (sexo == "m"):
print("Para homens:", (72.7*h) - 58)
e... |
1148c1cc4347c1e72559f151fe771fe118520670 | PHILLIPEBLOOD/pythonquestions | /repeticao/questr2.py | 436 | 4.09375 | 4 | '''Faça um programa que leia um nome de usuário e a sua senha e não aceite a
senha igual ao nome do usuário, mostrando
uma mensagem de erro e voltando a pedir as informações. '''
nome_de_usuario = input("Usuário: ")
print("Digite rápido e aperte enter, talvez ninguém veja! ")
senha = input("Senha: ")
while(nome_de_usua... |
e9a45211fc14402d255e13aa676214f0401c8048 | PHILLIPEBLOOD/pythonquestions | /funcoes/questf9.py | 374 | 4.125 | 4 | '''Reverso do número. Faça uma função que retorne o reverso de um número
inteiro informado. Por exemplo: 127 -> 721. '''
from questf8.py import tamanho
def reverso(numero):
n = tamanho(numero) - 1
numero = str(numero)
inverso = ""
while(n >= 0):
inverso += numero[n]
return inverso
numero... |
135949284c0103c7a46d90caca3f033625ac0950 | PHILLIPEBLOOD/pythonquestions | /lista/questl5.py | 517 | 3.828125 | 4 | '''Faça um Programa que leia 20 números inteiros e armazene-os num vetor.
Armazene os números pares no vetor PAR e os números IMPARES no vetor impar.
Imprima os três vetores.
'''
inteiros = []
pares = []
impares = []
for n in range(1, 21):
numero = int(input("Numero: "))
inteiros.append(numero)
if numero % ... |
3d0da9a0afc67936e62ce6ce7c2d0e4a66781bad | PHILLIPEBLOOD/pythonquestions | /decisao/questd21.py | 2,014 | 4.0625 | 4 | ''' Faça um Programa para um caixa eletrônico. O programa deverá perguntar
ao usuário a valor do saque e depois informar quantas notas de cada valor
serão fornecidas. As notas disponíveis serão as de 1, 5, 10, 50 e 100 reais.
O valor mínimo é de 10 reais e o máximo de 600 reais. O programa não deve se
preocupar com a q... |
43cefec68157edf28bd1e0f15ab92e62845ea4cc | PHILLIPEBLOOD/pythonquestions | /lista/questl10.py | 543 | 4.0625 | 4 | '''Faça um Programa que leia dois vetores com 10 elementos cada. Gere um
terceiro vetor de 20 elementos, cujos valores deverão ser compostos pelos
elementos intercalados dos dois outros vetores. '''
def intercalados(a, b):
c = []
for n in range(1, 11):
n -= 1
c.append(a[n])
c.append(b[... |
516a2b44b4e901e4d070b6f8f5109eb52c0762b1 | PHILLIPEBLOOD/pythonquestions | /decisao/questd20.py | 660 | 4.28125 | 4 | '''Faça um Programa para leitura de três notas parciais de um aluno.
O programa deve calcular a média alcançada por aluno e presentar:
A mensagem "Aprovado", se a média for maior ou igual a 7,
com a respectiva média alcançada;
A mensagem "Reprovado", se a média for menor do que 7,
com a respectiva média alcançada;
A me... |
519a3d464e211f009aeae3ba98f3e938fcffc47e | EladAssia/InterviewBit | /Tree Data Structure/Postorder_Traversal.py | 1,515 | 4.15625 | 4 | # Given a binary tree, return the postorder traversal of its nodes’ values.
# Example :
# Given binary tree
# 1
# \
# 2
# /
# 3
# return [3,2,1].
# Using recursion is not allowed.
####################################################################################################################... |
b574fcaf97b30f788c605c155c0ca8b317447d1d | EladAssia/InterviewBit | /Two Pointers Problems/Array_3_Pointers.py | 1,823 | 3.921875 | 4 | # You are given 3 arrays A, B and C. All 3 of the arrays are sorted.
# Find i, j, k such that :
# max(abs(A[i] - B[j]), abs(B[j] - C[k]), abs(C[k] - A[i])) is minimized.
# Return the minimum max(abs(A[i] - B[j]), abs(B[j] - C[k]), abs(C[k] - A[i]))
# **abs(x) is absolute value of x and is implemented in the following... |
43db5fea5b58f915ec3592c88ac635c03e96af6c | EladAssia/InterviewBit | /Tree Data Structure/Flatten_Binary_Tree_to_Linked_List.py | 1,433 | 4.3125 | 4 | # Given a binary tree, flatten it to a linked list in-place.
# Example :
# Given
# 1
# / \
# 2 5
# / \ \
# 3 4 6
# The flattened tree should look like:
# 1
# \
# 2
# \
# 3
# \
# 4
# \
# 5
# \
... |
8b2993782bb96f351a3830ed17d0f6e3ba8705b3 | EladAssia/InterviewBit | /Hashing/Substring_Concatenation.py | 1,620 | 3.6875 | 4 | # You are given a string, S, and a list of words, L, that are all of the same length.
# Find all starting indices of substring(s) in S that is a concatenation of each word in L exactly once and without any intervening
# characters.
# Example :
# S: "barfoothefoobarman"
# L: ["foo", "bar"]
# You should return the in... |
d03eccd3eb78ef222917d4619cf0393140eeeb1b | EladAssia/InterviewBit | /Hashing/Copy_List.py | 1,610 | 4.0625 | 4 | # A linked list is given such that each node contains an additional random pointer which could point to any node in the list or NULL.
# Return a deep copy of the list.
# Example
# Given list
# 1 -> 2 -> 3
# with random pointers going from
# 1 -> 3
# 2 -> 1
# 3 -> 1
# You should return a deep copy of th... |
bb626920313d1c8c8d38922644ec31f9b4c042fc | EladAssia/InterviewBit | /Arrays/Wave_Array.py | 967 | 4.09375 | 4 | # Given an array of integers, sort the array into a wave like array and return it,
# In other words, arrange the elements into a sequence such that a1 >= a2 <= a3 >= a4 <= a5.....
# Example
# Given [1, 2, 3, 4]
# One possible answer : [2, 1, 4, 3]
# Another possible answer : [4, 1, 3, 2]
# NOTE : If there are multi... |
829dd10750c405804c0d723fff91fe24d0963c27 | EladAssia/InterviewBit | /Graph Data Structure & Algorithms/Clone_Graph.py | 1,109 | 3.734375 | 4 | # Clone an undirected graph. Each node in the graph contains a label and a list of its neighbors.
########################################################################################################################################
# Definition for a undirected graph node
# class UndirectedGraphNode:
# def __i... |
4ba5a5dca19f7ec32f1c1019a3b672999d17aeac | EladAssia/InterviewBit | /Math/Grid_Unique_Paths.py | 1,183 | 4.1875 | 4 | # A robot is located at the top-left corner of an A x B grid.
# The robot can only move either down or right at any point in time. The robot is trying to reach the bottom-right corner of the grid (marked ‘Finish’ in the diagram below).
# How many possible unique paths are there?
# Note: A and B will be such that the... |
0defb0d7d4183c306bfbaae8a1a9f506e7dfd3ef | EladAssia/InterviewBit | /Backtracking/Permutations.py | 1,344 | 3.734375 | 4 | # Given a collection of numbers, return all possible permutations.
# Example:
# [1,2,3] will have the following permutations:
# [1,2,3]
# [1,3,2]
# [2,1,3]
# [2,3,1]
# [3,1,2]
# [3,2,1]
# NOTE:
# No two entries in the permutation sequence should be the same.
# For the purpose of this problem, assume that all th... |
5c94e2206f95d428a7431ad9188969fc35fdd4d0 | EladAssia/InterviewBit | /Tree Data Structure/Min_Depth_of_Binary_Tree.py | 1,398 | 4.1875 | 4 | # Given a binary tree, find its minimum depth.
# The minimum depth is the number of nodes along the shortest path from the root node down to the nearest leaf node.
# NOTE : The path has to end on a leaf node.
# Example :
# 1
# /
# 2
# min depth = 2.
#########################################... |
6f9ad5551f732234636b30416bdd0ba66cdd0e20 | EladAssia/InterviewBit | /Two Pointers Problems/Minimize_the_absolute_difference.py | 1,759 | 3.75 | 4 | # Given three sorted arrays A, B and Cof not necessarily same sizes.
# Calculate the minimum absolute difference between the maximum and minimum number from the triplet a, b, c such that a, b, c
# belongs arrays A, B, C respectively.
# i.e. minimize | max(a,b,c) - min(a,b,c) |.
# Example :
# Input:
# A : [ 1, 4, 5... |
f7cc9abfacda056ac2d3c96b49e17da5e1eeb11c | EladAssia/InterviewBit | /Tree Data Structure/Shortest_Unique_Prefix.py | 2,004 | 3.671875 | 4 | # Find shortest unique prefix to represent each word in the list.
# Example:
# Input: [zebra, dog, duck, dove]
# Output: {z, dog, du, dov}
# where we can see that
# zebra = z
# dog = dog
# duck = du
# dove = dov
# NOTE : Assume that no word is prefix of another. In other words, the representation is always possible. ... |
abc7bb6a325d3314d929e20357e284aa16b3b466 | EladAssia/InterviewBit | /Two Pointers Problems/Remove_Element_from_Array.py | 1,189 | 4.15625 | 4 | # Remove Element
# Given an array and a value, remove all the instances of that value in the array.
# Also return the number of elements left in the array after the operation.
# It does not matter what is left beyond the expected length.
# Example:
# If array A is [4, 1, 1, 2, 1, 3]
# and value elem is 1,
# then ne... |
c5ac8e282fde44c8f72d05a03246a6157f86dfc9 | EladAssia/InterviewBit | /Dynamic Programming/Unique_Paths_in_a_Grid.py | 1,377 | 4.25 | 4 | # Given a grid of size m * n, lets assume you are starting at (1,1) and your goal is to reach (m,n). At any instance, if you are on
# (x,y), you can either go to (x, y + 1) or (x + 1, y).
# Now consider if some obstacles are added to the grids. How many unique paths would there be?
# An obstacle and empty space is ma... |
256868282c8c56ffa0c28377c6f3864b94527fc8 | Sabarish241199/Mycaptain | /frequency.py | 314 | 3.875 | 4 | def most_frequent(a):
print( "in the function")
b = {}
for i in a:
if i in b:
b[i] += 1
else:
b[i] = 1
print ("Count of all characters in the string is :\n ",str(b))
return
st=input("Input the String:")
print (st)
most_frequent(st)
|
46e4cdc87202da77ee7a836cc4de884e15eb7f01 | Sandy4321/Python_Human_Resources_Program | /Associate.py | 2,824 | 3.796875 | 4 | #Product Name: Simple Sales Center (Castor Enterprise)
#Date: February 4, 2013
#Purpose: Associate class ia a subclass of an employee class, it is distinct from employee class becase of its type and the way it is paid
from Employee import *
class Associate(Employee):
#pre: all the parameters should be a string... |
7641d035f14e8b75f2cc8e2a7c3fda686fd8c04f | sush1996/Reinforcement-Learning----Monte-Carlo-Reinforce | /ValueEstimator.py | 821 | 3.625 | 4 | import numpy as np
#Estimates value
class ValueEstimator(object):
def __init__(self, num_states, num_actions):
self.num_states = num_states
self.num_actions = num_actions
#initial value estimates or weights of the value estimator are set to zero.
self.values = np.zeros((self.num_... |
c80d29f7d638092d5057e65c6c607300ccac04a4 | magickey111/Test | /11_2.py | 557 | 3.578125 | 4 |
fname=input('Enter a file name: ')
counts=dict()
try:
fh=open(fname)
except:
print('File cannot be opened:', fname)
exit()
for line in fh:
line=line.strip()
if line.startswith('From '):
words=line.split()
col_pos=words[5].find(':')
word=words[5][:col_pos]
if not wo... |
7149f131b50b0cd1014c005d518de39b667c2ee8 | magickey111/Test | /2_5.py | 64 | 3.65625 | 4 | C=input('Enter degree Celsius: ')
F=float(C)*1.8+32
print(F)
|
279a6f4d8002a1a6da9ddddbd061668f6aa83585 | magickey111/Test | /11_1.py | 511 | 3.53125 | 4 | fname=input('Enter a file name: ')
counts=dict()
try:
fh=open(fname)
except:
print('File cannot be opened:', fname)
exit()
for line in fh:
line=line.strip()
if line.startswith('From '):
words=line.split()
word=words[1]
if not word in counts:
counts[word]=1
... |
94b5bd0de34f0249fbe68cdd14be022b1d8267c3 | zk18051/ORS-PA-18-Homework05 | /task2.py | 1,023 | 4.15625 | 4 | """
=================== TASK 2 ====================
* Name: Most Frequent Letter
*
* Write a script that takes the stirng as user
* input and displays which letter has the most
* occurences and how many. If two or more letters
* have the same number of occurences print any.
*
* Note: Please describe in details poss... |
9c992e668425210b5c1a1116196a33539a0bee83 | Gocrazy/LeetCode | /415_addstrings.py | 781 | 3.890625 | 4 | import unittest
class Solution(object):
def addStrings(self, num1, num2):
"""
:type num1: str
:type num2: str
:rtype: str
"""
return str(self.addAmount(num1) + self.addAmount(num2))
def addAmount(self, numbers):
total = 0
digital = 0
fo... |
ac5476d4ed54a91e30ec875a61ca110bd5ef86c0 | Rafael-F-S/Codewars-Python | /Katas 1/2.py | 188 | 4.09375 | 4 | #Find the smallest integer in the array
def find_smallest_int(arr):
smallest = float('inf')
for x in arr:
if x < smallest:
smallest = x
return smallest |
bb3e3004646614590eccb9059a6a0c646920c4e9 | chaisdean/yellow-belt | /compare_arrays.py | 564 | 4.34375 | 4 | # Assignment: Compare Arrays
# Write a program that compares two lists and prints a message depending on if the inputs are identical or not.
#
# Your program should be able to accept and compare two lists: list_one and list_two. If both lists are identical print "The lists are the same". If they are not identical print... |
b770e24bea543e08dc4015d19ebc571c24cf953c | Jerhombus/wordgame | /guess.py | 3,076 | 4.09375 | 4 | import random
# Intro instructions
def intro():
print(':+'*50)
print(""" Welcome to Guess The Word""")
print(':+'*50)
# Splitting the letters in a word
def split(word):
return [char for char in word]
#replaces Word needed to all underscores
def make_list_underscore(w_list)... |
8fd1b3deeeea9c7dc3b27bd75c29b9bd19002c68 | carlos-lambda/Sprint-Challenge--Data-Structures-Python | /search/binary_search_tree.py | 2,217 | 3.796875 | 4 | class BinarySearchTree:
def __init__(self, value):
self.value = value
self.left = None
self.right = None
def depth_first_for_each(self, cb):
# get a ref to the left and right nodes
left = self.left
right = self.right
# return whatever cb is with the value... |
edd5d74ef341a7b6836a46a16830450663cd9b83 | lafrancef/dmqa-exploration | /code/textutil.py | 3,427 | 3.828125 | 4 | '''
Useful functions to keep around.
@author: lafrancef
'''
from nltk.stem import WordNetLemmatizer
from nltk.tokenize import sent_tokenize, word_tokenize
from nltk.corpus import stopwords
from string import digits as DIGITS
LEMMATIZER = WordNetLemmatizer()
STOPS = set(stopwords.words('english'))
def build_doc_sente... |
c5a581d0c469a8e746d3d768b7c5f0725dfbd0b7 | DavidMachineLearning/CNN_traffic_sign | /utils/utils.py | 3,677 | 3.8125 | 4 | from PIL import Image
import numpy as np
import cv2
import requests
import matplotlib.pyplot as plt
def count_unique_elements(arr):
"""
Function used to count the number of samples for each unique element in the array
Args:
arr (np.ndarray): an array of scalar values
Returns:
(dict)... |
7fd2c75011588903da47d7da5075d1270cf3d362 | ali-mhmd/ali_mahmoud_test | /ali_mahmoud_test/QA/scripts/QA.py | 1,797 | 4.40625 | 4 | # Ali Mahmoud
import argparse
import sys
def main():
'''
Most of the main function is just preprocessing and checking arguments
These should be passed in as POSITIONAL arguments, x1 x2 x3 x4
To form lines [x1, x2] and [x3, x4]
For example in the terminal: $ python3 QA.py 1 2 3 4
Here line1 is ... |
ff0be06861a117f76977aa77c887f9b6979f0512 | mohithvegi/Leetcode | /DailyChallenge/2020/March/30.py | 1,084 | 3.65625 | 4 | # https://leetcode.com/explore/challenge/card/march-leetcoding-challenge-2021/592/week-5-march-29th-march-31st/3690/
from bisect import bisect_left
class Solution(object):
def longestIncreasingSubseqLength(self, nums):
"""
return the length of longest increasing subsequence
"""
LI... |
89f7603a2926eff450901c53325ddc04a836ff4e | thazhemadam/Serious-Python | /day2/d2p2.py | 2,421 | 3.859375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Mon May 27 15:39:02 2019
@author: user
"""
# for any client server program
# you need to create a server
# The psuedo code is
# socket() - create a socket
# i.e say what ip type and what transport type
# bind() - connect the socket to an IP and port
# listen() - wa... |
e1dc2bad8720b6405fdc1c8f11929f21b37f856c | thazhemadam/Serious-Python | /day3/d3p5.py | 1,134 | 4.25 | 4 | # -*- coding: utf-8 -*-
"""
Created on Wed Jun 5 17:46:46 2019
@author: user
"""
import os
import sqlite3
# Returns a connection object when you connect
cxn=sqlite3.connect("example.db")
# as Mentioned before the connection object can commit, rollback, fetch,
# execute as functio
dir(cxn)
cur=cxn.curso... |
91f90feb8cc6aa3706a67316e1c912c082874092 | Jerpen80/Dec2Bincalculator | /binaryoperator.py | 2,481 | 3.953125 | 4 | a = 0
b = 0
def dectobin(dec):
if dec >= 128:
bin = "1"
dec -= 128
else:
bin = "0"
if dec >= 64:
bin += "1"
dec -= 64
else:
bin += "0"
if dec >= 32:
bin += "1"
dec -= 32
else:
bin += "0"
if dec >= 16:... |
f888568a079850c61c2289a616f758ea8be35fc1 | zabuchan/sort_recipe | /sort_nested_dictionary.py | 304 | 3.515625 | 4 | import json
from operator import itemgetter
filename = "room_price.json"
with open(filename, 'r') as fin:
offices = json.load(fin)
rooms = offices['office']
# for room in rooms:
# print(room.get('price'))
sorted_rooms = sorted(rooms, key=lambda x: x.get('price'), reverse=True)
print(sorted_rooms)
|
a510466581ef725799e79dc05181e768648be891 | PCBZ/AlgorithmPractise | /quickSort.py | 818 | 4.03125 | 4 | class Sort(object):
def quick_sort(self, array):
self.item_quick_sort(array, 0, len(array)-1)
return
def item_quick_sort(self, array, start, end):
if start >= end:
return
pivot = start
i, j = start, start
while i <= end:
if array[i... |
467845439641c5e5cc0d20385d0dc3552e6cdc61 | lww2020/python_study | /python_scripts/while_three_time.py | 960 | 3.875 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2019/4/23 10:44
# @Author : davie
# @Site :
# @File : while_three_time.py.py
# @Software: PyCharm
"""
用户只有三次重试机会
"""
n = int(1)
username = 'davie'
password = 'davie123'
while n <= 3:
username_input = input("第%s次,请输入用户名:> "%(n))
password_input ... |
f64bbb95e809dc89ed3ce8d70fd830dff3800102 | lww2020/python_study | /python_scripts/print_jishu.py | 191 | 3.6875 | 4 | #!/usr/bin/env python
# -*- coding:utf8 -*-
"""
输出1-100内所有的奇数
"""
n = 1
while n < 101:
if (n % 2) == 1:
print(n)
n = n + 1
print('---------- Done ----------')
|
0caee0695bdd9bfc1d7d1acaaf34f87e3a72500a | fatpat314/SPD1.4 | /interview4.py | 1,891 | 4.28125 | 4 | # Given a sorted array, remove the duplicates
"""Complexity: 0(n), loop dependent on the length of the array"""
def remove_duples(arr):
new_array = []
for i in arr:
if i not in new_array:
new_array.append(i)
return new_array
arr = [1, 2, 2, 3, 4, 4]
print(remove_duples(arr))
"""Complex... |
6b4cd80af7ad5124e37ab749c526e1bdad5050e8 | fatpat314/SPD1.4 | /HW7.py | 6,412 | 4.46875 | 4 | """Determine whether an integer is a palindrome. An integer is a palindrome when
it reads the same backward as forward."""
"""Restate question"""
# Is the input the same backward and forward?
# return bool
"""Clearifying questions"""
# Are there negitive numbers?
"""Assumptions"""
# There are negitive numbers
"""Br... |
9561b931d50aff2950ac9c036b9c65d00a83396e | etokrug/PythonProjects | /Lessons/Homework Projects/IntroGUI_Homework/src/Calculate.py | 2,020 | 3.515625 | 4 | from tkinter import *
class Application(Frame):
def __init__(self, master=None):
Frame.__init__(self, master)
self.pack()
self.createWidgets()
def createWidgets(self):
#1st frame
king_frame = Frame(self)
#king_frame objects
self.first_label = Label(k... |
25acd8bc8f3685a7e0c97ca40229d6eb15f591d6 | sonogong777/AoC | /day7_1.py | 248 | 3.765625 | 4 | #!/usr/local/bin/python3
input_file = open("day7.input")
input_text = input_file.read()
counter=0
for line in input_text:
print(line)
if 'shiny gold bags,' in line or 'shiny gold bags' in line:
counter += 1
print(counter) |
b5b180eedb391c947fe4fae47e4b6dd1e1faa3e4 | TamirTheDebugger/KeyPass | /UserClass.py | 627 | 3.65625 | 4 | class User():
def __init__(self, username, password, id):
# constructor
self._username = username
self._password = password
self._id = id
def getID(self):
"""
gets the current user's ID.
:return: id
:rtype: String
"""
return self._id
def getUser... |
c71c7577dd4b9539c7244543962e851d3fe81c90 | ZnYang2018/pythonFrom0ToProject | /PythonFromZeroToProject/src/Chapter03/skill01.py | 230 | 3.53125 | 4 | # 字符串居左,居中,居右对其
print('居左'.ljust(21, '-'))
print('居右'.rjust(21, '-'))
print('居中'.center(21, '-'))
print(format('居左', '*>20'))
print(format('居右', '*<20'))
print(format('居中', '*^20'))
|
647d8d79233f4adf4d0c1f0266cc1dfefcabc9e1 | ZnYang2018/pythonFrom0ToProject | /PythonFromZeroToProject/src/Chapter07/ex01.py | 958 | 3.71875 | 4 | # _*_ coding : UTF8 _*_
# Author : ZnYang
# Creation Time : 2021/1/13 23:00
# File Name : ex01.py
# Dev Tool : PyCharm
import re
string = '2018 Amazon Jeff Bezos 1120'
print('1' + '=' * 70)
print(string.replace('2018', ''))
print('2' + '=' * 70)
numbers = re.findall('\d', string)
print(''.join(numb... |
ef8ec0d92c05896f0c93cb87839a2c7bb25d3bcf | Chewie23/fluffy-adventure | /Largest_Palindrome/Palindrome.py | 994 | 4.3125 | 4 | """
Problem: A palindromic number reads the same both ways. The largest palindrome made from the product of two 2-digit numbers is 9009 = 91 × 99.
Find the largest palindrome made from the product of two 3-digit numbers.
"""
def is_palidrome(product):
product_string = str(product)
valid_palindrome = True
... |
b23e0b025f905be32121f39531b0f6e0b34c07f5 | rosa-yuri/Python | /day 0904_1.py | 676 | 3.515625 | 4 | a=[1,3,5,7,9,0,2,4,6,8]
print(a[::-1]) #[8, 6, 4, 2, 0, 9, 7, 5, 3, 1]
print(a[len(a)-1: :-1]) #[8, 6, 4, 2, 0, 9, 7, 5, 3, 1]
print(a[::-2]) #[8, 4, 0, 7, 3]
print(a[-2 ::-2]) #[6, 2, 9, 5, 1]
import csv
def read_car():
f=open('Data/cars.csv', 'r')
rows=[]
for row in f:
# print(row)
... |
09d2e8fed634fa07510beec6c494073bc1a5b083 | rosa-yuri/Python | /day 0906_1.py | 3,549 | 3.78125 | 4 | import numpy as np
print(np.__version__)
list1=[1,2,3,4]
print("list=",list1)
a=np.array(list1)
print("array=",a)
print(a.shape) #(4,)
print(a[2])
b=np.array([[1,2,3,],[4,5,6]])
print(b)
print(b.shape) #(2, 3)
print(b[0,0])
print(type(b)) #<class 'numpy.ndarray'>
print(type(list1)) #<class 'list'>
# 벡터화 연산
# 개념 ... |
168280e88d35418ce2c717bfbf2d6a988ff4633c | rosa-yuri/Python | /day 0806_ex.py | 909 | 3.796875 | 4 | #다음과 같이 총 5줄로 구성된 input.txt 파일이 있다.
#모든 숫자를 읽어 총합과 평균을 구하고 화면에 출력하시오.
#result.txt 파일에는 평균을 출력하시오.
#input.txt파일의 내용
# 70
# 55
# 90
# 87
# 38
f=open("input.txt", "r")
lines=f.readlines()
f.close()
print(lines)
#
# for line in lines:
# sum=sum+int(line)
# print(sum)
sum = 0
avr = 0
for line in lines:
sum=sum+i... |
db65d1e61a74170dae01f1073db93b040f91c604 | sarthak310/Python-Codes | /hailstone.py | 79 | 3.625 | 4 | n=int(input())
while(n!=1):
if(n%2==0):
n=n//2
else:
n=(n*3)+1
print(n)
|
b30b3c3b3d244ac7852827bb982a3a1a2ebd5c10 | sarthak310/Python-Codes | /sum1n35.py | 109 | 3.796875 | 4 | n=int(input())
d=3
sum=0
while(d!=n+1):
if(d%3==0 or d%5==0):
sum=sum+d
d=d+1
else:
d=d+1
print(sum)
|
3d336de651ea3b3d84c88de886319d89cf975fa1 | elizhang227/rpg-starter | /rpg-2.py | 5,185 | 3.71875 | 4 | from random import randint
class Character:
def __init__(self, name, health, power):
self.health = health
self.power = power
self.name = name
def alive(self):
if self.health > 0:
return True
else:
return False
def attack(self, enemy):
... |
8a767861d1bc9941b891a5ce5f6cf4113c71a015 | mzkang/hw | /hw6.py | 2,686 | 3.8125 | 4 |
#============??????????????????????return.....??????????????????/=============================
def count(n):
if n > 0 :
print(n)
return count(n-1)
else :
return 'zero!!'
x = count(5)
print()
print(x)
#================================================================================... |
e3f4a91ccf50482974a59b272da5fdb5ee9150b2 | Vorlogg/itmo | /machine-learning/main.py | 152 | 3.6875 | 4 | a_list = [1, 2, 3, 4, 5]
b_list = ['a', 'b', 'c', 'd', 'e']
[[print(i, j) for i in a_list] for j in b_list]
[print(j) for i in a_list for j in b_list]
|
eccea9fd754e6c9972dcbbeb617188bec859a679 | mehdinajmi/classpy | /S7h1.py | 256 | 4.09375 | 4 | # Mehdi Najmi- Thursday 14-18
# to calculate factoriel
def factorial(a):
if a==1:
print(' factoriel 1 is equal to 1')
elif a<0:
print( ' o does not have a factorial')
else:
return a*factorial(a-1)
factorial(-1)
|
8dac5abd09c2678ed10b9f76d391b334f895a25c | JamesMedeiros/Python | /Tchau.py | 387 | 3.84375 | 4 | import os
print ("Calcule o valor da conta telefonica")
t = float(input("Digite o tempo que foi utilizado pelo usuario: "))
if t < 200:
v = t * 0.2
print ("o valor da conta sera de R$ %6.2f " %v)
if t >= 200 and t <= 400:
v = t * 0.18
print ("o valor da conta sera de R$ %6.2f " %v)
if t > 400:
v = ... |
09191a84a77033fd1586cfbaf66d2bec46b4fa61 | Tweek43110/PyPractice | /Lists.py | 418 | 4.3125 | 4 | # Lists
groceryList = ['kiwi', 'chicken breast', 'bread']
print(groceryList)
groceryList.append('lunch meat')
print(groceryList)
numbers = []
strings = []
strings = ['Alex', 'Steve', 'Chuck']
print(strings)
numbers = [3, 4, 5]
print(numbers)
strings.append('John')
strings.append('Jane')
print(strings)
strings.appen... |
bd9a09532638a2f1c8746abb1d759af0a9770ce1 | Genghis77777/Item-Comparison | /Test.py | 1,281 | 4.0625 | 4 | product_details = []
product_name = ""
product_status = ""
best_value = []
worst_value = []
while product_name != "X":
product_name = input("\nPlease enter the name of the product: ")
if product_name == "X":
break
else:
product_weight = float(input("Please enter the weight/volume of the "
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.