blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
8bafc0f0dd1bb9285250b433591b05c40839a3f2 | Rafael-doctom/CC33Z | /Cursos/Introdução à Ciência da Computação/Scripts/binary_counter.py | 218 | 3.75 | 4 | """
Contador de números binários
"""
def count_binary(n):
num = 0
while n > num:
yield bin(num)
num += 1
for n in enumerate(count_binary(32)):
print(f'{n[0]:02d} -> {int(n[1][2:]):05d}') |
9d41bfdb41fc10baffec45ba11e5016f3bc71042 | itsolutionscorp/AutoStyle-Clustering | /all_data/exercism_data/python/word-count/faa1580cc8604aee8803190fecd5158f.py | 294 | 3.78125 | 4 | from collections import defaultdict
def word_count(text):
#dictionary that if queried for a nonexistent key
#initializes said key with a value of 0
res_dic = defaultdict(int)
text = text.split()
for word in text:
res_dic[word] += 1
return dict(res_dic)
|
85b48069632a302181fd61724b24fa545c026970 | jpibarra1130/algorithms | /numbers_with_given_sum/number_sum.py | 436 | 3.625 | 4 | def find_sum(number_list, s):
index1 = 0
index2 = len(number_list) - 1
result = -1
while index1 != index2:
num1 = number_list[index1]
num2 = number_list[index2]
sum = num1 + num2
if sum < s:
index1 += 1
if sum > s:
index2 -= 1
if sum == s:
print("Found!")
re... |
78a072f4a30ee58446dfc17b95160ac1cc4c6447 | Eric01752/CSCI308 | /Homework/homework1Problem1.py | 941 | 4 | 4 | #Eric Schmidt
#Homework 1: Problem 1
#Coin values
PENNY = 1
NICKEL = 5
DIME = 10
QUARTER = 25
#Get input from the user
print("Try to make exactly one dollar using pennies, nickels, dimes, and quarters.")
numPennies = int(input("Enter the number of pennies: "))
numNickels = int(input("Enter the number of n... |
f1f40e4271c4166d3e349d8f58f376f39d6b4370 | arturosilva00/ActividadesBasico | /assignments/08Caracol/src/exercise.py | 271 | 3.75 | 4 | def main():
#escribe tu código abajo de esta línea
minutos = float(input("Dame los minutos: "))
segundos = minutos * 60
milimetros = segundos*5.7
cm = milimetros/10
print("Centímentros recorridos:",cm)
if __name__ == '__main__':
main()
|
b6587e983ef671e7a67d115580b206f0938f795a | jsdelivrbot/Ylwoi | /week02/day_2/average-of-input.py | 311 | 3.921875 | 4 | __author__ = 'ylwoi'
num1 = int(input("Enter a number:"))
num2 = int(input("Enter a number:"))
num3 = int(input("Enter a number:"))
num4 = int(input("Enter a number:"))
num5 = int(input("Enter a number:"))
sums = num1 + num2 + num3 + num4 + num5
average = sums / 5
print("Sum:", sums)
print("Average:", average) |
93e8b8c7491bf4593a02ee496e6e5aa4b372165f | wann31828/leetcode_solve | /python_solution/191.py | 258 | 3.671875 | 4 | '''Write a function that takes an unsigned integer and return
the number of '1' bits it has
'''
class Solution(object):
def hammingWeight(self, n):
"""
:type n: int
:rtype: int
"""
return str(bin(n))[2:].count('1') |
b7943958f4fef7007e03c2903ec29fd311b8abbc | Tonyhao96/LeetCode_EveryDay | /53_Maximum Subarray.py | 698 | 3.703125 | 4 | #53_Maximum Subarray
#Dynamic Programming
class Solution:
def maxSubArray(self, nums: List[int]) -> int:
listsum=[0]*len(nums)
listsum[0]=nums[0]
for i in range(1,len(nums)):
listsum[i]=max(nums[i],nums[i]+listsum[i-1])
return max(listsum)
#Dynamic Prog... |
561642c831df5e74086f6e1604c524c2b7763821 | devchannel/DevLang | /DevLang/tokens.py | 1,304 | 3.53125 | 4 | from enum import Enum
# not sure what I should have called this
class Symbol(Enum):
Add = '+'
Subtract = '-'
Multiply = '*'
Divide = '/'
And = "&&"
Or = "||"
Not = "!"
Lt = "<"
Lte = "<="
Gt = ">"
Gte = ">="
Eq = "=="
Neq = "!="
FunctionOneLine = '='
Argumen... |
01a205566889bdf1cb0560b2efa4cf923c0d6d88 | lightucha/Text-Mining | /amazon/utils.py | 1,283 | 3.703125 | 4 | from random import gammavariate
from random import random
import numpy as np
"""
Samples from a Dirichlet distribution with parameter @alpha using a Gamma distribution
Reference:
http://en.wikipedia.org/wiki/Dirichlet_distribution
http://stackoverflow.com/questions/3028571/non-uniform-distributed-random-array... |
b1f4f99dc5111ee732ed9d6ec6551bb15412894a | jurcimat/B3B33KUI | /HW02/agent.py | 6,810 | 3.6875 | 4 | #!/usr/bin/python3
# Homework solution of HW03 - state space search from subject B3B33KUI - Kybernetika a umělá inteligence
# at FEL CTU in Prague
# @author: Matej Jurčík
# @contact: jurcimat@fel.cvut.cz
import time
import kuimaze
import os
from Node import Node as Node # Import custom made file containing objec... |
dbfedf4b899f5680b8b187c300486d855e99d34d | The-Ineffable-Alias/ProgrammingDigitalHumanitiesBook | /Ch7 - Dirty Hands 1/Code/7.11_corporaopener.py | 1,282 | 3.53125 | 4 | # Overcommented for explanatory reasons
import webbrowser
with open("urllist.txt") as file_with_urls:
# Build a list of all the links and find length
links = file_with_urls.readlines()
length = len(links)
# Ask how many pages to open
# remember int conversion
views = int(input('How man... |
62d869d744c431d9a25e3644bd897ee58d69b7f8 | sanjkm/ProjectEuler | /p84/monopoly_alt.py | 16,046 | 3.953125 | 4 | # monopoly_alt.py
# Calculate the odds of landing on any given monopoly square
# Final answer is concatenating the square numbers of the 3 most likely
# landing squares if using 2 4-sided dice
import sys
# This maps the square number (e.g. 00, 11, ...) to its square type on the board
def init_square_dict (filename):
... |
7bf42ccd123f4346201abddc9d843568938c21bf | Sarumathikitty/guvi | /codekata/Array/check_sum_dig_palindrome.py | 240 | 3.625 | 4 | #check sum of digits is palindrome
n=int(input())
sum=0
rev=0
while(n!=0):
dig=n%10
sum=sum+dig
n=n/10
temp=sum
while(sum!=0):
dig=sum%10
rev=rev*10+dig
sum=sum/10
if(temp!=rev):
print("yes")
else:
print("NO")
|
d72d2ac492a377a3a97262f2ad28d17c6f8f8dd0 | JorgeR3nteria/30DAYSOFPYTHON | /Day5/Exercise_2.py | 188 | 3.609375 | 4 |
ages = [19, 22, 19, 24, 20, 25, 26, 24, 25, 24]
maximo=max(ages)
minimo=min(ages)
ages.__le__//2
print("Point 1\n""Highest age is:",maximo)
print("Point 2\n""Minimum age is:",minimo)
|
6277dc427f0f218fa840bcbd2257c37a43960003 | RonRan123/AOC | /2020/Day2/day2.py | 1,168 | 3.671875 | 4 | def findCount(arr):
tmp = list()
for a in arr:
char = a[1][0]
word = a[2]
c = word.count(char)
tmp.append(c)
return tmp
def countValids(num, arr):
total = 0
size = len(num)
for i in range(size):
lower, upper = arr[i][0].split("-")
lower = int(lowe... |
c99416d3ecc3b791a6b7c9fefb8c7d374b227e40 | blockchain99/pythonlecture | /test109slicing.py | 852 | 3.921875 | 4 | ## slicing list: list[start:end:step] #end is not included.
test_list = list(range(1,10))
print(test_list)
sliced_list = test_list[2:5]
print(sliced_list)
sliced_list2 = test_list[1:6:2]
print(sliced_list2)
print("----------------")
first_list = list(range(1, 9)) # 1 ~ 8
print(first_list)
print(first_list[1:])
print(f... |
78b722f153e6643f172d86e246245f83e050189c | feldmatias/TeoriaDeAlgoritmos-FlujoMaximo-CorteMinimo | /bfs.py | 682 | 3.828125 | 4 | def bfs(vertices, start):
# Initialization
for vertex in vertices:
vertex.bfs_visited = False
vertex.bfs_parent = None
vertices_to_visit = [start]
start.bfs_visited = True
index = 0
# BFS algorithm
while index < len(vertices_to_visit):
vertex = vertices_to_visit[ind... |
3501e080752561d0df7f1db35fe91959e89bd549 | Saswati08/Data-Structures-and-Algorithms | /BST/find_whether_pair_exists_in_BST_having_given_target.py | 1,606 | 3.84375 | 4 | class Node:
def __init__(self, data, left=None, right=None):
self.data = data
self.left = left
self.right = right
def insert(root, key):
# if the root is None, create a node and return it
if root is None:
return Node(key)
# if given key is less than the root node, recur for left subtree
if key < root.dat... |
28101d8694d45f567de898b4d10f3899dda5f7eb | lauradebella/treinamentoPython | /zumbi6.py | 227 | 3.8125 | 4 | #problema da operadora - calcula conta
min = int(raw_input('Insira os minutos utilizados: '))
if min<200:
p=0.2*min
elif min<400:
p=0.18*min
elif min>800:
p=0.08*min
else:
p=0.15*min
print('Valor da conta : R$%.2f' %p ) |
fbc8be7df5a7fb7b1e69910cf119771d6481e25e | eyallin/aoc2018 | /day_02.py | 1,340 | 3.578125 | 4 | # https://adventofcode.com/2018/day/2
import collections
def analyze_entry(entry):
counts = collections.Counter(entry)
return (2 in counts.values(), 3 in counts.values())
def day2a(data):
overall = [0, 0]
for entry in data.split():
tmp = analyze_entry(entry)
overall[0] += tmp[0]
... |
0840b207324358562de5b070430e540b8d38038c | Frederick-S/Introduction-to-Algorithms-Notes | /src/chapter_10/singly_linked_list.py | 1,699 | 3.796875 | 4 | class SinglyLinkedNode(object):
def __init__(self, key, value=None):
self.key = key
self.value = value
self.next = None
class SinglyLinkedList(object):
def __init__(self):
self.head = None
self.tail = None
def is_empty(self):
return self.head is None
d... |
41808c633403ee5ec116021795d4aceda7d5100f | shreyasrye/Premier-Soccer-Leaderboard-Tracker | /league.py | 1,826 | 3.65625 | 4 | import random
import string
import sqlite3
from sqlite3 import Error
class User:
_name = ""
def __init__(self, name):
self.name = name
def name(self):
return self._name
class Team:
sport = ""
_score = 0
team = [] # team list of players (containing string ... |
b7ab43be59a4f5c2c5513d1611a1ee44e8afae30 | unitedideas/pcc_intro_programming_logic | /lab6/ShaneCheekLab6.py | 7,466 | 4.21875 | 4 | __author__ = "Shane Cheek"
# Description:
# This program will represent a dog park. It will allow
# dogs to come and go in and out of the dog park. New
# dogs can be added and removed from the dog park. The
# dogs will have different levels of obedience. This may
# lead to dog fights!!!
# Input
#... |
61a3fff5a3ea1bef8c7cec154c8a0fab0035467c | jaypalweb/python_crud_tkinter | /deleterecord.py | 2,781 | 3.640625 | 4 | from tkinter import Tk, Frame, Button, Label, Entry
import connect
import operateaccount
class Delete :
def __init__(self, root, msg):
self.root = root
self.msg = msg
self.root.title("Delete Record")
self.root.geometry("700x600")
self.head = Label(self.root, text="Delete Acc... |
093ab23e7c2cde53d78cd9f93d0d9dd760b6b03e | GokulAB17/-Basic-Python-Codes- | /tuples (1).py | 3,786 | 4.25 | 4 | # Tuples #
# creating tuples
# a) python tuple packing
# b) pyhton tuple unpacking
# c) creating tuple with a single item.
# creating tuple
totalages = (40,39,12)
print(type(totalages))
simple= ('python','program','value')
print(type(simple))
number = ['python','java','coding']
print(type(number)... |
e49e26b0c01caad7d6bf43a1078d698d42b72925 | jangmyounhoon/python | /day4/rectangle.py | 1,204 | 3.96875 | 4 | #-*- coding: utf-8 -*-
class Rectangle:
count = 0 # 클래스 변수
# 초기자(initializer)
def __init__(self, width, height):
# self.* : 인스턴스변수
self.width = width
self.height = height
Rectangle.count += 1
# 메서드
def calcArea(self):
area = self.width * self.height
... |
62716f9bebf0c7b0bf587a90eb8745509b9c31d8 | edwrx02/TheVirusGame | /game/bullet.py | 516 | 3.5625 | 4 | import pygame
class Bullet(pygame.sprite.Sprite):
""" This class represents the bullet . """
def __init__(self):
# Call the parent class (Sprite) constructor
super().__init__()
self.image = pygame.image.load("Gunfire_rockets.png")
self.rect = self.image.get_rect()
eff... |
2b9a52f19672c4f6626f2f25d22369e5af3a53c3 | PoojaShirwaikar/Learn-Python | /Project-Python/bittu_test.py | 93 | 3.84375 | 4 | n=5
fact=1
i=5
while(i>=1):
fact=fact*i
i-=1
print("factorial is",fact)
|
0e8ccee7d932b3a356eeb3c9e4dac052a2f84012 | miskaknapek/dustmin_to_csv__various_code | /sequentially_make_24_hrs_data.py | 2,496 | 3.640625 | 4 | import pandas as pd
import time
import os
print( "\n ---------- Hellow (world) there!\n ------------ " )
### ----- make some dates…
def makedates( start_timestamp, how_many_days_dates_to_produce ):
# make a timestamp starting at midnight
start_day_at_midnight = pd.Timestamp( start_timestamp.year, start_times... |
0a6afb88e751ae5bacb3dde200548ac95d3e2c2e | KIDJourney/algorithm | /leetcode/algorithm/binary-tree-zigzag-level-order-traversal.py | 894 | 3.6875 | 4 | class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
import time
class Solution(object):
def zigzagLevelOrder(self, root):
"""
:type root: TreeNode
:rtype: List[List[int]]
"""
if root is None :
... |
e1f8292c46171c086c81da2d45888e2f287e00c1 | Nicodemos234/Solving-problems-with-python | /questao08.py | 429 | 3.703125 | 4 |
qtdMercadorias = int(input("Insira o total de mercadorias: "))
aux = 1
somaMercadoria = 0
while aux <= qtdMercadorias:
somaMercadoria = somaMercadoria + float(input("insira o valor da "+ str(aux)+"ª mercadoria: "))
aux = aux+1
mediaValMerc = somaMercadoria/qtdMercadorias
print("o valor total em est... |
1eef126f59169febdc5547ebda907bbdbf3b1ec6 | bmoretz/Python-Playground | /src/DoingMathInPython/ch_02/challenge/fib_golden.py | 551 | 3.859375 | 4 | '''
Fibonacci Sequence & Golden Ratio
'''
from matplotlib import pyplot as plt
import math
def fibo( n ):
if n == 1:
return [1]
if n == 2:
return [1, 1 ]
a = 1
b = 1
series = [ a, b ]
for i in range( n ):
c = a + b
series.append( c )
a = b
b = c
return series
def plot_points( x_vals, y_vals )... |
fcbf02122b7ec567b28facd130fb6359e6254e47 | eep0x10/Pyton-Basics | /5/py3.py | 179 | 3.984375 | 4 | #Faça um programa, com uma função que necessite de três argumentos, e que forneça a soma desses três argumentos
def soma(n1,n2,n3):
n=n1+n2+n3
print(n)
soma(1,2,3)
|
11834ab419d51049b21ab3707e8a1f511c103212 | ankile/ITGK-TDT4110 | /Øving 9/øving_9_5.py | 766 | 3.71875 | 4 | # a)
def write_to_file(data):
f = open('my_file.txt', 'a')
f.write(data + '\n')
f.close()
# b)
def read_from_file(filename):
f = open(filename, 'r')
print(f.read())
# c)
def main():
while True:
try:
answer = input('Vil du lese eller skrive? (r/w): ')
if answer... |
180664c51d6f971b80c4616d847b45bcd7de6bba | Ben-Baert/Exercism | /python/queen-attack/queen_attack.py | 759 | 3.65625 | 4 | def board(white, black):
check_positions(white, black)
return [''.join("W"
if (row, column) == white else ("B" if (row, column) == black else "_")
for column in range(8)) for row in range(8)]
def can_attack(white, black):
check_positions(white, black)
white_x, black_x = white
white_... |
522931c41fc447f4e578937a454923ca6de8fa83 | MaesterPycoder/Python_Programming_Language | /oops/QuickSort.py | 793 | 3.890625 | 4 | # worst case time complexity = O(n2)
# Best case time complexity(i.e,pivot is always middle of array) = O(nlogn)
# Space Complexity is O(logn) for best case and O(n) for worst case
def partition(A,l,h):
pivot=A[h]
i=l-1
j=h
while(i<j):
while A[i]<=pivot:
i+=1
wh... |
4e5adb7bc37c880ac89fd1e9023ea146fc6c2f07 | JaiyeA/Solar-System | /SolarSystem.py | 1,860 | 3.921875 | 4 | import turtle
import random
#function that creates and postions the sun and planets
def planet(speed,r,g,b,xcor,ycor,circle_size):
name=turtle.Turtle()
name.speed(speed)
name.hideturtle()
name.color(r,g,b)
name.penup()
name.setpos(xcor,ycor)
name.pendown()
name.begin_fill()
name.circle(circle_size)
... |
5dfdb640d43afc609197f4f5eaa7855cb0ff234d | henrytxz/my_python_repo | /code_wars/alphabetic_anagrams.py | 1,285 | 3.734375 | 4 | from itertools import permutations
import time
def my_generator(s):
"""
make it into a generator to save space
"""
ps = permutations(s)
for p in ps:
yield ''.join(p)
def listPosition(s):
sorted_s = ''.join(sorted(s))
gen = my_generator(sorted_s)
set_values = set()
c = 1
... |
d7440c00c217e4e1329cd86ed678cb02a5b9d726 | jayashelan/python-workbook | /src/chapter09/division_calculator.py | 419 | 4.09375 | 4 | print("Give me 2 numbers i will divide them")
print("Enter 'q' to quit")
while True:
first_number = input("\First Number:: ")
if first_number == 'q':
break
second_number = input("\n Second Number ::")
if second_number =='q':
break
try:
answer = int(first_number)/int(second_number)
except Exception as e:... |
07e1b86b07db2bacdc6d770bc349d8a6d5b99524 | jesuslz/AIPy | /labelEncoding-p2.py | 1,388 | 4.25 | 4 | '''
In the real world, labels are in the form of words, because words are human readable. We
label our training data with words so that the mapping can be tracked. To convert word
labels into numbers, we need to use a label encoder. Label encoding refers to the process of
transforming the word labels into numerical for... |
06a922d816e676175ac62ea101f0b6bb4d4d77d6 | dkallen78/OSSU_Computer_Science | /MITx6.00.1x/Week 2/numberGuess.py | 800 | 3.6875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Wed Feb 26 19:23:13 2020
@author: espeg
"""
userInput = ""
validInput = "hlc"
highNumber = 100
lowNumber = 0
print("Please think of a number between 0 and 100!")
while True:
guess = (highNumber + lowNumber)//2
print("Is your secret number " + str(guess) +... |
35c83ea8ea970ba9bf078e0d21d321d741a3f9ba | Jack-HFK/hfklswn | /pychzrm course/journey_two/day5_PM/exercise_server_side.py | 1,108 | 3.53125 | 4 | """
1.将一个文件从客户端发到服务端,要求文件类型随意
2. tcp两个程序和函数熟练
"""
"""
tcp套接字编程 : 服务端流程
思路:逐步骤完成操作
重点代码
"""
import socket
sockfd = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sockfd.bind(("172.40.74.151", 4444))
# 设置监听
sockfd.listen(6666)
while True:
try:
# 等待处理客户端连接请求
connfd, addr = sockfd.acce... |
d5b5e4f7f3b92153fac592b555d3c69d774e967e | hz336/Algorithm | /LeetCode/DP/! H Best Time to Buy and Sell Stock IV.py | 3,841 | 3.828125 | 4 | """
Say you have an array for which the ith element is the price of a given stock on day i.
Design an algorithm to find the maximum profit. You may complete at most k transactions.
Note:
You may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).
Example 1:
Input... |
6a9edb66698197ce1f9f9a137d1c3061c2e6cebe | wisdomtohe/CompetitiveProgramming | /Forks/uvapy-master/ad-hoc/p12289.py | 476 | 3.734375 | 4 | num_tests = int(input())
for test in range(num_tests):
letter = str(input())
if len(letter) == 5:
print("3")
else:
sim_1 = 0
sim_2 = 0
if letter[0] == 'o':
sim_1 += 1
if letter[1] == 'n':
sim_1 += 1
if letter[2] == 'e':
sim_1 += 1
if letter[0] == 't':
sim_2 ... |
d58d373014de6702dad40f21dc93153548338e9f | yunussevin/Python | /Hesap Makinesi.py | 1,293 | 3.84375 | 4 | seçenek1 = "(1) topla"
seçenek2 = "(2) çıkar"
seçenek3 = "(3) çarp"
seçenek4 = "(4) böl"
seçenek5 = "(5) karesini hesapla"
seçenek6 = "(6) karekök hesapla"
print(seçenek1, seçenek2, seçenek3, seçenek4, seçenek5, seçenek6, sep="\n")
soru = input("Yapmak istediğiniz işlemin kodunu giriniz.\n")
if soru == "1":
sayı... |
2e99448743b82e4f9c1864b28584de503e527dcf | papagalo/pythonPractice | /hello.py | 573 | 3.609375 | 4 | from openpyxl.workbook import Workbook
from openpyxl import load_workbook
# Create a workbook object
wb = Workbook()
# load existing spreadsheet
wb = load_workbook('PythonPractice.xlsx')
# Create an active worksheet
ws = wb.active
# Set a variable
#name = ws["A2"].value
# Print something from our spreadsheet
#prin... |
de1e6454960497f7fe8d53d3875e590dcd62ec7c | wanglinjie/coding | /leetcode/227.py | 1,919 | 4.03125 | 4 | #!/usr/bin/env python
# -*- coding:utf-8 -*-
# date:20160826
import collections
class Solution(object):
def calculate(self, s):
"""
:type s: str
:rtype: int
Implement a basic calculator to evaluate a simple expression string.
The expression string contains only non-negative integers, +, ... |
e8ed215c4eadb0fc7fc2e5b21eae00587bcc8d7d | IgorOGuimaraes/python-521 | /aula_4/mask.py | 450 | 3.671875 | 4 |
import sys
import hashlib
if len(sys.argv) != 3:
print('Número de argumentos inválidos')
sys.exit(1)
operation, filename = sys.argv[1:]
csv = []
with open(filename, 'r') as f:
for line in f.readlines():
csv.append( line.split(';') )
if operation == 'encode':
for n in range(len(csv) - 1):
csv[n+1][0] = has... |
220ccad7d3acbd9dfced884e0f77812435ca3930 | daniel-reich/turbo-robot | /4AzBbuPLxKfJd7aeG_5.py | 1,170 | 4.3125 | 4 | """
Create a function that takes an encryption key (a string with an even number
of characters) and a message to encrypt. Group the letters of the key by two:
"gaderypoluki" -> "ga de ry po lu ki"
Now take the message for encryption. If the message character appears in the
key, replace it with an adjacent char... |
0ea79349c2a4eef526e8564825b62443a852c5a9 | MingduDing/A-plan | /leetcode/数组Array/exam004.py | 1,060 | 3.953125 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time: 2019/8/15 17:02
# @Author: Domi
# @File: exam004.py
# @Software: PyCharm
"""
004.《寻找两个有序数组的中位数》(easy)
题目:给定两个大小为m和n的有序数组nums1和nums2。请你找出这两个有序数组的中位数,
并且要求算法的时间复杂度为O(log(m+n))。可以假设nums1和nums2不会同时为空
思路:同88合并两个有序数组,然后分情况讨论中位数
"""
def find_median_sorted_a... |
6127732ef430c620c2c725f233ae569effb0bd77 | l0gOut/Hangman | /main.py | 2,144 | 3.96875 | 4 | import random
import string
words = ["python", "java", "kotlin", "javascript"]
english_symbol_check = string.ascii_lowercase
print("H A N G M A N")
while True:
chose = input("Type \"play\" to play the game, \"exit\" to quit: ")
if chose == "play":
count = 0
random_word = random.choice(words)
... |
0a20981dbf3fe6593d6ab238c316c1772567358f | Shu-HowTing/LeetCode | /L4.py | 487 | 3.9375 | 4 | # -*- coding: utf-8 -*-
# Author: 小狼狗
'''
反转整数:
给定一个 32 位有符号整数,将整数中的数字进行反转
'''
class Solution():
def reverse(self,x):
rev = 0
flag = 1 if x>0 else -1
x = abs(x)
while x != 0:
res = x % 10
x //= 10
rev = rev * 10 + res
return flag*rev
i... |
289fd5341d84678daddd5a2b8ad28b219772bcad | rctorresn/Mision-Tic-2021 | /Dato.py | 219 | 3.90625 | 4 | suma = 0
dato = int(input("Ingrese un número: "))
while dato != 0:
if dato > 0:
suma += dato
dato = int(input("Ingrese otro número: "))
print("La suma total es: ", suma)
|
574a8eeab72f273ae0a8d108605942cfc7f25826 | chonlasitwichainpan/Python | /work3.3.py | 259 | 3.90625 | 4 | print("Input your fav food or type exit to exit program")
i = 1
a = 0
food = []
while(i) :
a = input("Your fav food No. "+str(i)+" is : ")
food.append(a)
i+=1
if a=="exit" :
print("Your fav food is :")
print(food)
break |
7404053d9ef492d4fa8cd51e671c1c4c17aad4ba | colinfrankb/py10000 | /Algorithms/selection_sort.py | 773 | 3.84375 | 4 | #!/usr/bin/env python
from unittest import TestCase, main
def swap(array, this_index, that_index):
array[this_index], array[that_index] = array[that_index], array[this_index]
def find_min_index(array, start_index):
min_index, min_value = start_index, array[start_index]
for i in range(start_index, len(a... |
be8fc6bab59597cfb5954e69ffb56be5f2dd2cbf | beatriznonato/tempo-digitacao | /tempoDigitacao.py | 611 | 3.84375 | 4 | import time as t
import matplotlib.pyplot as plt
tempos = []
vezes = []
legenda = []
vez = 1
repeat = 5
print('Este programa marcará o tempo gasto para digitar a palavra PROGRAMAÇÃO. É necessário que você digite essa palavra '+str(repeat)+ ' vezes.')
input('Aperte a tecla enter para começar.')
while vez <= repeat:
... |
b5eeb2d9a5ab7a7848950b85421f0c8e17f156e6 | LucianErick/p1-2018.2 | /Questões/encontra_menores/encontra_menores.py | 570 | 4.03125 | 4 | # coding: utf-8
# Universidade Federal de Campina Grande
# Ciência da Computação
# Programação I | 2018.2
# Aluno: Luciano Erick Sousa Figueiredo Filho
# Matrícula: 118110400
# Problema: Encontra Menores
def encontra_menores(numero, lista):
lista_menores = []
for valor in lista:
if valor < numero:
... |
1bf976280ad9f5ef8374d58825e0908a424f0b49 | nmarriotti/Tutorials | /python/ReplaceString.py | 356 | 4.15625 | 4 | # Searching for something in a string
import re
def main():
source = "Learning how to use Python"
# sub will replaces all matches with the string or character specified
# Replace all letter o's with a ? in the source variable
result = re.sub('o', '?', source)
print(result)
if _... |
441fcbafabf299c4963e318faad01ed877d8c3e3 | carlosaugus1o/Python-Exercicios | /aula10(condicionais).py | 394 | 4.21875 | 4 | tempo = int(input('Há quantos anos você comprou o seu carro? '))
if tempo <= 3:
print('Seu carro é novo!')
else:
print('Seu carro é velho!')
print('--FIM--')
#print('carro novo' if tempo <= 3 else 'carro velho') <---- forma alternativa
nome = str(input('Qual é seu nome? '))
if nome == 'Carlos':
... |
08a8ef1322ae9f78fbd9dcea6f14993afa4a2ce7 | Zein-4/School | /Computing/12_grams.py | 200 | 3.984375 | 4 | import time
kg = input('Enter the amount of kilograms you would like to convert to grams:')
g = int(kg) / 1000
time.sleep(2)
print('Calculating')
time.sleep(2)
print(kg , 'kg is equal to' , g)
|
9356745d7cfe0446a8ae4a5e2e6a7c62b654f825 | x89846394/280201032 | /lab5/example1.py | 107 | 3.890625 | 4 | a = int(input("Enter an integer: "))
for i in range(1, 11):
print(str(a) + "x" + str(i) + "=" + str(i*a)) |
c0529faa8749167865e32cd192af2015e5589ac6 | romanfh1998i/UdacityCs101 | /p3-2.py | 295 | 3.734375 | 4 | def bigger(a,b):
if a > b:
return a
else:
return b
def biggest(a,b,c):
return bigger(a,bigger(b,c))
def median(a,b,c):
big =biggest(a,b,c)
if big ==a:
return bigger (b,c)
if big ==b:
return bigger (c,a)
else:
return bigger (b,a)
|
285590e30e1cff0aa4ae5ed8d8d5ca6640cc5eb2 | zomux/utils | /count-line-by-length.py | 366 | 3.6875 | 4 | #!python
import os, sys
if __name__ == '__main__':
if len(sys.argv) < 3:
print "python count-line-by-length.py [file] [min-length]"
raise SystemExit
_, filename, minLength = sys.argv
minLength = int(minLength)
counter = 0
for line in open(filename).xreadlines():
if line.strip().count(" ") + 1 >= ... |
1b26c4ac1c6722a0eec7520c723be04916df9833 | pqnguyen/CompetitiveProgramming | /platforms/leetcode/SearchInsertPosition.py | 490 | 3.71875 | 4 | # https://leetcode.com/problems/search-insert-position/
class Solution:
def searchInsert(self, nums: List[int], target: int) -> int:
first, last = 0, len(nums) - 1
res = -1
while first <= last:
mid = (first + last) // 2
if nums[mid] == target:
return m... |
5677c18a8d19839e7619c0d5d43b00111fe40ec5 | pragatirahul123/Function | /Function_Ques20.py | 468 | 4.15625 | 4 | def showNumbers(limit):
index=0
while index<=3:
if index%2==0:
print(index,"EVEN")
else:
print(index,"ODD")
index=index+1
showNumbers(3)
###########################################################################################
def showNumbers(limit):
index... |
f1b7ff42171e3dd268c6cf212a3ffc61a3d9204b | samkossey/proj_1_672 | /hill.py | 3,538 | 3.796875 | 4 | import operator
import itertools
#READING IN FILE
def readCipher(filename):
ch = file(filename,'r')
cipher = ch.read()
onlyletters = filter(lambda x: x.isalpha(), cipher)
cipher = onlyletters.lower()
ch.close()
return cipher
#SUM FREQ SQUARED
def findFreq(cipher):
frequency = {}
fo... |
855d1bd1eff404e0d4ffc265a3e66ab5c1a7572c | Paulo-Felipe-96/guppe | /exercicios/seção 4/ex03.py | 168 | 3.765625 | 4 | n1 = int(input('Primeiro número: '))
n2 = int(input('Segundo número: '))
n3 = int(input('Terceiro número: '))
print(f'A soma de {n1, n2, n3} é {n1 + n2 + n3}')
|
b94c91418b5573fe21a35d4d4ae5a82145262efe | rameshrvr/HackerRank | /Algorithms/Implementaion/acm_icpc_team.py | 938 | 3.921875 | 4 |
def calc_max_no_of_topics(details, attendees):
"""
Method to calculate max number of topics known
by any two people in the ACM ICPC final
Args:
details: Details Array
attendees: attendees count
Return:
None
"""
result_array = []
for index1 in xrange... |
31cef335b5919ecafff1c365d7f84749f7aedb91 | gurram444/narendr | /dictionary.py | 646 | 3.734375 | 4 | x={'java':80,'python':90,'aws':70,'devops':75}
print(x)
print(x.get('aws'))
print(x['python'])
x['aws']=85
x['hadoop']=82
print(x)
for p in x:
print(p,x[p])
k=x.keys()
for p in k:
print(p)
v=x.values()
for q in v:
print(q)
kv=x.items()
for k,v in kv:
print(k,v)
for i in kv:
print(i[0],i[1])
... |
f8f427deeb0e25cffa518def74da6c479ec650b3 | gitter-badger/Printing-Pattern-Programs | /Python Pattern Programs/Alphabetic Patterns/Pattern 87.py | 161 | 3.8125 | 4 | n=5
for x in range(0, n):
for y in range(0, x+1):
for z in range(0, y + 1):
print(chr(z+65), end="")
print()
print()
"""
65 > ASCII of 'A'
""" |
0ad0b25985fff3f8d2a7a302e63a367642088237 | modimore/Fundamentals | /Source/Algorithms/Sorting/insertion_sort.py | 959 | 4.125 | 4 | """
Fundamentals :: Algorithms :: Sorting Algorithms
Author: Quinn Mortimer
This file contains an implementation of the insertion sort algorithm.
It is intended as a reference for those looking to brush up on important
algorithms.
"""
def insertion_sort(a):
"""An insertion sort implementation.
The proces... |
1a6f4eb8ee50e9761b19cc103710d40ec03a07c9 | asperaa/programming_problems | /array/merge_sort.py | 905 | 4.0625 | 4 | """Merge sort in an array"""
def merge(arr, l, mid, r):
size_l = mid - l + 1
size_r = r - mid
L = [0]*size_l
R = [0]*size_r
for i in range(0, size_l):
L[i] = arr[l+i]
for j in range(0, size_r):
R[j] = arr[mid+1+j]
i, j, k = 0, 0, l
while i < size_l and j < size_r:
... |
7b8b143197a4610785789ceb311c9a5efe475576 | shankar7791/MI-10-DevOps | /Personel/Jeet/Python/3march/prog1.py | 269 | 4.09375 | 4 | #Python Program to add two matrices using nested for loop.
m1 = [[1,2,3], [4,5,6], [7,8,9]]
m2 = [[9,8,7], [6,5,4], [3,2,1]]
res = [[0,0,0], [0,0,0], [0,0,0]]
for i in range(len(m1)):
for j in range(len(m1[0])):
res[i][j] = m1[i][j] + m2[i][j]
print(res)
|
907efe6d18bc1743e7ba3f0dfc19964ed912f1b7 | deepika-13-alt/Python-Assignment | /assignment4/merge.py | 1,540 | 4.25 | 4 | '''
Program: Write a program to merge two sorted array in another sorted array.
'''
def mergeSortedArray():
sizeM = int(input("Enter the size of array 1: "))
sizeN = int(input("Enter the size of array 2: "))
arr1 = []; arr2 = []; res = []
print("Taking input for ARRAY 1\n")
for i in range(sizeM):
... |
e76fb1148774da677bd1ff482265bb254ba638b5 | trigodeepak/Programming | /Sort_according_frequency.py | 345 | 3.921875 | 4 | #program to sort an array according to frequency
a = [2, 3, 2, 4, 5, 12, 2, 3, 3, 3, 12]
#creating dictionary
dict = {}
for i in a:
if dict.has_key(i):
dict[i]+=1
else:
dict[i]=1
b = []
for i in dict:
b.append((i,dict[i]))
b = sorted(b,key=lambda x: x[1],reverse=True)
a = []
for i in b:
... |
03678a0b92063fdf4b798d7ab8ff7dac87acb26f | somzs/Elso_Telusko3 | /Number_system_conversion.py | 162 | 3.609375 | 4 | # from decimal to binary
bin(25)
print(bin(25)) # 11001
print(bin(5)) # 0101
# from octal to hexadecimal
print(0b0101) #5
print(oct(25))
print(hex(25)) |
7ad1aed383ce06b98158cc80f754ce97af5f0f17 | MahmoudElrabee/codingbat-python | /List-2/sum67.py | 173 | 3.734375 | 4 | def sum67(nums):
six = False
sum = 0
for i in nums:
if(six):
if(i==7):
six=False
elif(i==6):
six=True
else:
sum+=i
return sum
|
2b16469fa0140bfe1a69033636e65721a47c0a4b | dragon434/untitled | /python学习/面向对象学习/class_属性.py | 1,070 | 3.59375 | 4 | #!/usr/bin/env python
# -*- coding:utf-8 -*-
# Author : @jiawenlong
# Date :2018-03-22
__author__ = '@jiawenlong'
# 属性的写法之一
# class province:
# def __init__(self):
# self.L = ['jiawenlong']
# # 属性
# @property # 用于执行 obj.per
# def per(self):
# return self.L
#
# @per.setter
# ... |
4ddd966230a9552db58349cecb137dd8ffaaafab | thejeffchen/holbertonschool-python-camp | /0x02-python_if_else_loops_functions/3-print_alphabt.py~ | 166 | 3.625 | 4 | #!/usr/bin/python
store = ''
for each in range(97, 123):
a = chr(each)
if a == 'q' or a == 'e':
pass
else:
store = store + a
print(store)
|
0b6f7cc9d930356028df227785c9e3510565b77a | delopezm86/simple_factory_pattern_example | /factory_pattern/models/classes/business_classes.py | 1,038 | 3.5 | 4 | from ..base.base import BaseRunnable
class ARunnable(BaseRunnable):
def __init__(self, name='', age=0):
self.name = name
self.age = age
def run(self):
print(f"Running {self.__class__.__name__} with {','.join(self.__dict__.keys())} properties")
class BRunnable(BaseRunnable):
def... |
e06ca6482d1c204d5d63969e2741756c002ae264 | run-fourest-run/python-cookbook | /Iterators/Iterables.py | 1,245 | 4.375 | 4 | '''
Iterable:
* any object from which the iter built-in function can obtain an iterator: Objects implementing an __iter__ method returning an iterator are iterable
* sequences are always iterable
* as are objects using the __getitem__ method that takes a zero based index
* Python obtains iterators from iterables
It... |
b39437488d26328a2362b5708cca1c4091893bff | DangKhoa253/Statistic | /Pearson Correlation Coefficient I.py | 368 | 3.625 | 4 | import math
from statistics import mean,stdev
n=int(input())
X=list(map(float,input().split()))
Y=list(map(float,input().split()))
def cov(X,Y):
x=mean(X)
y=mean(Y)
sum=0
for i in range(0,n):
sum += (X[i] - x ) * (Y[i] - y )
return sum/(n-1)
sigmaX=stdev(X)
sigmaY=stdev(Y)
result=co... |
1ac2906368e129e8f698b3c80f46dca950192920 | SardorPyDev/python-lessons | /3-dars/3_dars.py | 1,308 | 4 | 4 | # # FOR taxrorlash operatori
# mehmonlar = ['Ali','Vali','Hasan','Husan','Olim']
# for mehmon in mehmonlar:
# print(f"Xurmatli{mehmon} sizni 20 sentyabr kuni naxorgi oshimizga taklif qilamiz")
# print("Hurmat bilan palonchiyevlar olilasi")
# sonlar = list(range(1,11))
# for son in sonlar:
# print(f"{son} ning kvadr... |
749cd7074faf69d38e1bd7ca9e7e1235e7f63e7b | Erinzzhang/OOP_python | /HW1_Function/triangle_area.py | 781 | 4.09375 | 4 | import math
class Point():
def __init__(self,x,y):
self.x = x
self.y = y
def getLength(p1,p2):
length = math.sqrt((p1.x-p2.x)**2 + (p1.y-p2.y)**2)
return length
def getArea(p1,p2,p3):
p1_p2 = getLength(p1,p2)
p2_p3 = getLength(p2,p3)
p3_p1 = getLength(p3,p1)
... |
4e5e868789f64df8a785d039a414d65e53b9812c | ky822/Data_Bootcamp | /Code/Python/intro_control.py | 1,135 | 4.5625 | 5 | """
Python language basics
# assignments: x=7, x='foo', 7*5, 'foo'*2, 7**2, multiples, but no log/exp/sqrt
print and strings
lists: examples, type, element numbering
**slicing
loops
list comprehensions
if/then..
References
* https://docs.python.org/3/tutorial/introduction.html
*
Written by Dave Backus @ NYU, Aug... |
c85c3c9818cbf4e4bec1bd2747190660e5a592c1 | wfeng1991/learnpy | /py/leetcode/31.py | 697 | 3.609375 | 4 | class Solution:
def nextPermutation(self, nums):
"""
:type nums: List[int]
:rtype: void Do not return anything, modify nums in-place instead.
"""
if len(nums)<2:
return
i=len(nums)-1
while i>0 and nums[i-1]>=nums[i]:
i-=1
if i==... |
bd1466d08279e1acf7d5a15dabf74c0a683ccf1b | DesignisOrion/DIO-Tkinter-Notes | /gui1.py | 267 | 4.375 | 4 | from tkinter import *
root = Tk()
# create a label
label1 = Label(root, text="Hello world")
# add label to window
label1.pack()
# make the window wait until we close it
root.mainloop()
# app populates a small window that states Hello World!
|
1338b43966d0cb74ac87a69ee629889f0eb63152 | archiesgallery/archiesgallery | /.vscode/python60/validation.py | 286 | 3.921875 | 4 | def anagram(word1, word2):
word1 = word1.lower()
word2 = word2.lower()
return sorted(word1) == sorted(word2)
print(anagram("cinema", "iceman"))
print(anagram("Archana", "naarcha"))
print(anagram(("men"), "nem"))
print(anagram("cool", "loco"))
print(anagram("car", "bike"))
|
eec67013380da63c1aacd10fccb2c460e46aba2b | historybuffjb/leetcode | /tests/test_longest_word_in_dictionary.py | 1,053 | 3.90625 | 4 | from problems.longest_word_in_dictionary import longest_word
def test_longest_word_in_dictionary_1():
words = ["w", "wo", "wor", "worl", "world"]
expected = "world"
actual = longest_word(words)
assert actual == expected
def test_longest_word_in_dictionary_2():
words = ["a", "banana", "app", "app... |
2e7ec751954390ac073201fcfa7d11bb90daa85f | diastSF/Fundamental_Python | /strtoint.py | 202 | 3.734375 | 4 | angka1 = input('Masukkan Angka 1 :')
angka2 = input('Masukkan Angka 2 :')
print(angka1 + angka2)
print(int(angka1) + int(angka2))
angka1 = float(angka1)
angka2 = float(angka2)
print(angka1 + angka2)
|
742525f8ddf860f8e91908d94a14734bf83b736f | SachinMadhukar09/100-Days-Of-Code | /Array/Day 4/17-July_13_Rotate_an_Array_HELP_15m+10m+15m.py | 1,989 | 4.25 | 4 | # Link https://practice.geeksforgeeks.org/problems/rotate-array-by-n-elements-1587115621/1/?track=DS-Python-Arrays&batchId=273
# 16-July 11:05AM-11:20AM 15min Not Completed on Online Compiler
# 19-July 07:25AM-07:35AM 10min Not Completed on Online Compiler
# 19-July 07:43AM-07:58AM 15min Completed By Help Of Ashish
... |
817efb2c4a0ba9a48f8a990c64f8ef60adf77f6a | franpe1/starting_with_python_ver2 | /chap6_3.py | 557 | 4.0625 | 4 | def main():
a = int(input("enter value for a: "))
b = int(input("enter value for b: "))
correct = False
while correct == False:
if a == b:
print("values can't be the same")
a = int(input("enter value for a: "))
b = int(input("enter value for b: "))
e... |
81c84e3a11e9077f2a218f9e7032e509d50bf5ae | charluz/cyPython | /cv2_create_image/cv2_createImage.py | 937 | 3.828125 | 4 | #!/usr/bin/python
'''
Reference : https://stackoverflow.com/questions/9710520/opencv-createimage-function-isnt-working
'''
import cv2 # Not actually necessary if you just want to create an image.
import numpy as np
def create_blank(width, height, rgb_color=(0, 0, 0)):
"""Create new image(numpy array) filled wit... |
946c3e361e7042f8623c723f821c493eb5af3f9b | IngAlarcon/Python-Django-y-JS-PoloTic-2021 | /Clase4PrecticaChangoDev/teoriaDeLaClase04.py | 922 | 4.0625 | 4 | """
Tratamiento de Excepciones
try ...
except ...
"""
import sys
try:
numero1 = int(input("Ingrese primer numero: "))
numero2 = int(input("Ingrese segundo numero: "))
except ValueError:
print("Error: Valor no valido.")
#Salir del programa
sys.exit(1)
try:
resultado = numero1 / numero2... |
965b33f1917ca078495d70d9c7ad849569b53fcf | SegFault2017/Leetcode2020 | /516.longest-palindromic-subsequence.py | 811 | 3.609375 | 4 | #
# @lc app=leetcode id=516 lang=python3
#
# [516] Longest Palindromic Subsequence
#
# @lc code=start
class Solution:
def longestPalindromeSubseq(self, s: str) -> int:
"""Strategy 1: Dynamic Programming
Runtime: O(n^2), where n is the length of s
Space:O(n^2)
Args:
s (s... |
f063806a53ddc211295a7adc308bcc18a6ce81e7 | kangsm0903/Algorithm | /B_10000~/B_10799.py | 314 | 3.5625 | 4 | T=list(input())
stack=[]
count=0
for i in range(len(T)):
if T[i]=='(':
stack.append(T[i])
elif T[i]==')' and T[i-1]=='(': # razor
stack.pop()
count+=(len(stack))
elif T[i]==')' and T[i-1]==')': # 쇠막대기 표현
stack.pop()
count+=1
print(count) |
2ce9c051eb63a9b9dcce48485ca9ef206df4bd7b | emmanavarro/holbertonschool-machine_learning | /supervised_learning/0x03-optimization/8-RMSProp.py | 849 | 3.734375 | 4 | #!/usr/bin/env python3
"""
RMSProp
"""
import tensorflow as tf
def create_RMSProp_op(loss, alpha, beta2, epsilon):
"""
Updates a variable using the RMSProp optimization algorithm:
Args:
loss is the loss of the network
alpha: is the learning rate
beta2: is the RMSProp weigh... |
33c6de009ff5fcb43a49dc67431216637f2db6c5 | HasanIjaz-HB/D-Hondt-method-II | /code2.py | 2,079 | 3.53125 | 4 | from elections_2002 import *
from matplotlib.pyplot import *
lowerBound = int(input("Please enter a lower bound for the threshold (barrage): "))
upperBound = int(input("Please enter an upper bound for the threshold (barrage): "))
chartResults = [0] * len(range(lowerBound,upperBound+1))
chartIndex = -1
for threshold i... |
a949cab73eed36616eed9f8b873df4c54fcf74e0 | laurenchow/algorithms | /reverse_linked_list.py | 659 | 4.3125 | 4 | #reverse linked list
class Node:
def __init__(self, data):
self.data = None
self.next = None
# class LinkedList:
#step through or traverse the linked list
#for each node, create a new pointer going backwards pointing to previous node .last
#return a linked list such that node.next is node.last
def reverse(node... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.