blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
8640fe3e47c775f3a9fc1c6a6678d4cc8fede0a3 | Kittyuzu1207/Leecode | /LCCI/0420M求和路径.py | 5,773 | 3.734375 | 4 | #给定一棵二叉树,其中每个节点都含有一个整数数值(该值或正或负)。
#设计一个算法,打印节点数值总和等于某个给定值的所有路径的数量。
#注意,路径不一定非得从二叉树的根节点或叶节点开始或结束,但是其方向必须向下(只能从父节点指向子节点方向)。
#My:
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def pathS... |
f2a189d329b00fd8e8a3cfd89a8d8df1fcd2d9f7 | banana-galaxy/challenges | /challenge9(dominos&chess)/Stilton.py | 921 | 3.6875 | 4 | def fill(matrix):
missing = []
for index, row in enumerate(matrix, 1):
for indexs, square in enumerate(row, 1):
if square == 1:
missing.append((index, indexs))
if ((len(matrix) * len(matrix[0]) - len(missing)) % 2) != 0:
return False
if ((len(matrix) * len(m... |
dfe03e22a941e97da58e4b4f4044e788e7908507 | JMagnoJunior/ppj | /ppj/util.py | 545 | 3.578125 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Modulo que contem classes e funções utilitarias"""
from datetime import date
def enum(**enums):
"""Simula um enum Java
"""
return type('Enum', (), enums)
def formata_data(data_nascimento):
"""formata data de nascimento para o tipo date
"""
resul... |
288875e421ed8d64c5ea6081e3dd3eee57c2e148 | Gttz/Python-03-Curso-em-Video | /Curso de Python 3 - Guanabara/Mundo 03 - Estruturas Compostas/Aula 17 - Listas (Parte 1)/079 - Valores_únicos.py | 991 | 4.15625 | 4 | # Exercício Python 079: Crie um programa onde o usuário possa digitar vários valores numéricos e cadastre-os em uma
# lista. Caso o número já exista lá dentro, ele não será adicionado. No final, serão exibidos todos os valores únicos
# digitados, em ordem crescente.
lista = list()
while True:
n = int(input("... |
fa25f8fff65115e22d91a846af0c60c3800b868d | edu-athensoft/stem1401python_student | /py200622_python2/day20_py200829_final/final_submission/neilson/stem1402python2_p2_Neilson.py | 3,969 | 3.765625 | 4 | """
Final exam p2
"""
# Problem 1
article = "Natural language processing (NLP) is a subfield of linguistics, computer science, information engineering, " \
"and artificial intelligence concerned with the interactions between computers and human (natural) languages, " \
"in particular how to progra... |
b37a2312bff856207b5d5f6cba6298c112b1f001 | alec-deason/ihme-python-course | /basic_python_exercises/topics/01_basic_syntax/01_arithmetic/test_B.py | 434 | 3.59375 | 4 | import math
from itertools import product
from B import quadratic
def test_quadratic():
for a, b, c in product(range(0, 10), range(0, 10), range(0, 10)):
if a == 0 or b*b - 4*a*c < 0:
assert quadratic(a, b, c) == 'roots undefined'
else:
x1 = (-b+math.sqrt(b*b - 4*a*c))/(2*... |
e0767b91a71f5976ddc6d1c99e67e9ffadf794ea | tanvinaminul/Python | /Extra/anik.py | 171 | 3.640625 | 4 | Numbers= set()
while True:
Anik =int(input())
if Anik== -1:
break
Numbers.add(Anik)
Numbers = list(Numbers)
Numbers.sort(reverse=True)
print(Numbers)
|
5ec942c30a6fddf24b25d21851a6a85f9e5058ac | nghoiwa/python | /sorting/quicksort.py | 836 | 3.546875 | 4 | import random
data = [89, 34, 23, 78, 67, 100, 66, 29, 79, 55, 78, 88, 92, 96, 96, 23]
data2 = [4, 2, 3, 6, 9, 5, 7]
def quicksort(data, left, right):
if left >= right:
return
pivot = random.randint(left, right)
pivotNewposition = partition(data, left, right, pivot)
quicksort(data, left, pivot... |
a78df13c01d8a169ffdac77fd31a55d61733541a | ashishu8888/5th-Sem | /LabExam - Scripting/Question3/B/3b.py | 1,937 | 4.28125 | 4 | import os
from functools import reduce
import sys
#If the argument length os not equal to 2, we will exit.
if(len(sys.argv) != 2):
print("The argument list is not proper")
sys.exit()
#If the specified file does not exist, we will exit
if(not(os.path.exists(sys.argv[1]))):
print("The specified file does no... |
505c964f4eeda06f51c5d4b9f04f9ffefdae173e | 1021546/test_pytorch | /pytorch_lstm/test_lstm.py | 951 | 3.703125 | 4 | # Author: Robert Guthrie
# 作者:Robert Guthrie
import torch
import torch.autograd as autograd # torch中自动计算梯度模块
import torch.nn as nn # 神经网络模块
import torch.nn.functional as F # 神经网络模块中的常用功能
import torch.optim as optim # 模型优化器模块
torch.manual_seed(1)
# lstm单元输入和输出维度都是3
lstm = nn.LSTM(3,... |
f9ced163a5852a00fde9f5e80d4470e0a3de6bdf | wan-catherine/Leetcode | /problems/MultiplyStrings.py | 555 | 3.515625 | 4 | class Solution:
def multiply(self, num1, num2):
"""
:type num1: str
:type num2: str
:rtype: str
"""
# n1 = int(num1)
# n2 = int(num2)
# return str(n1*n2)
if num1 == "0" * len(num1) or num2 == "0" * len(num2):
return "0"
res... |
3f7a4db729b8e83f9cc372e013ec010d4b9a10b5 | NicholasAKovacs/SkillsWorkshop2018 | /Week01/Problem05/bpeng_05.py | 580 | 3.765625 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Jul 12 12:38:16 2018
@author: baijiepeng
"""
class Solution:
## DP approach
def smallMul(self,num):
dp = [0 for i in range(num+1)]
dp[1]=1
for currentNum in range(2, num+1):
for j in range(1,currentN... |
d43b5af266e2a467d9573b6ea3d7d9c9097610b4 | Jiklopo/web-dev | /lab7-python/level3/while/3060.py | 111 | 3.546875 | 4 | x = int(input())
n = 1
while n <= x:
if(x == n):
print('YES')
exit()
n *= 2
print('NO') |
208016db55d5a6f155c9dc24fca325163cdaf809 | maiconsaraiva/estudos_python | /objetos/heranca/polimorfismo.py | 1,711 | 4.5625 | 5 | """"
Polimorfismo
Poli -> Mitas
Morfis -> Formas
Polimorfismo são objetos que podem possuir/assumir muitas formas.
No exemplo abaixo, as classes herdam todas da super classe Animal, mas as classes Cachorro() e Gato() fazem a
reimplementação do método falar(), já que eles falam de forma diferente (um late e o outro m... |
b270e8099284b9a50d37d5e26882bd295e3ac6c4 | disulfiram/SoftUni-PythonProgramming | /04 Exceptions, Debugging, Text Files/Demos/Catch.py | 473 | 4.03125 | 4 | people = [{'name': "Мария", 'gender': "female", }, {'name': "Калоян", 'gender': "male", }, ]
def print_person(person: dict):
print("{} ({}) is interested in {}".format(
person['name'],
person['age'],
', '.join(person['interests'])
))
def print_people(people: list):
for person in ... |
e7c7d13264f1e9c73ef6702c228594e27ec71f79 | ponickkhan/CodeSignal | /interview/firstNotRepeatingCharacter.py | 272 | 3.75 | 4 | def firstNotRepeatingCharacter(my_string):
chars = {}
for i in my_string:
if chars.get(i):
chars[i] += 1
else:
chars[i] = 1
for i in my_string:
if chars[i] == 1:
return i
return "_"
s = "abacabad"
print(firstNotRepeatingCharacter(s)) |
eb3d4a14a56fd77cf9cdaa9a20412531c0198e87 | SergioRodas/Curso-Python | /parte09/ex9.19_estadisticas_basicas.py | 464 | 3.875 | 4 | # Ejercicio 9.10: Realizar cálculos de estadísticas básicos: media, mínimo, máximo.
numeros = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
suma = 0
for n in numeros:
suma += n
print('Suma:', suma)
media = suma / len(numeros)
print('Media:', media)
minimo = numeros[0]
for n in numeros:
if n < minimo:
minim... |
63e1f1008273f5dcd65fd12e22b47886a6be3bec | lautaroGonzalez97/practica2 | /ejercicio3.py | 262 | 3.796875 | 4 | texto="Tres tristes tigres, tragaban trigo en un trigal, en tres tristes trastos, tragaban trigo tres tristes tigres."
letra = input("ingrese una letra")
lista= texto.lower().replace(",","").split()
for ele in lista:
if ele[0] == letra:
print(ele) |
ce680cbdd72d2b01a0b3909fbd807c00faa93d47 | thaisom/ppwa | /exe2q18.py | 360 | 4.03125 | 4 | # Recebe dois valores para as variáveis A e B, efetuar a troca dos valores de forma que a variável A passe a ter o valor de B e
# que a variável B passe a ter o valor de A. Mostrar na tela os valores trocados.
def trocar(a,b):
a,b=b,a
return a,b
a= int(input("Digite um valor de a:"))
b= int(input("Digite ... |
3e84ac2b3a32cd065725c4693032ad4490043544 | rafaelperazzo/programacao-web | /moodledata/vpl_data/438/usersdata/346/98083/submittedfiles/pico.py | 715 | 3.78125 | 4 | # -*- coding: utf-8 -*-
lista= []
def pico(lista):
#CONTINUE...
anterior= int(input('Digite um num: '))
atual= int(input('Digite um num: '))
no_picos= 0
no_vales= 0
i=2
while i<n:
prox= int(input('Digite um num: '))
if anterior < atual > prox:
no_picos +... |
f1e893bc9a10d9d33e7fefa6f073aac29d1ca7cf | NithinSethumadhavan/CS621_Assignments | /assignment2/part1/task1.py | 2,360 | 4.09375 | 4 |
def housing_mat_run():
'''Linear Regression with SKLearn
Task to do :
Use the training data to train a model using Linear Regression. Use cross validation and select the best model.
Using the Linear Regression model selected above, predict the labels for the test set (test_X).
Using these predicted labels, calcul... |
6c90289449e1396ff4dc733585555969f4b45509 | UrlBin/Lessons-10 | /Область на плоскости.py | 1,007 | 3.671875 | 4 | # Заданные уравнения
# y = x
# x**2 - 4*x + 3
my_list = list()
output_dictionary = dict([])
out_list = list()
N = int(input('Введите натуральное число количества точек: '))
for i in range(0, N):
x_coordinate_of_point = float(input('Введите значение, это будет координата "x" очередной точки: '))
y_c... |
d9910eb3deaa08b03c3d5ee6b1aac7ee2a8b5f49 | RuchikDama24/IUB_CSCI_B551_EAI | /Assignment 2/part2/SebastianAutoPlayer.py | 7,877 | 3.859375 | 4 | # Automatic Sebastian game player
# B551 Fall 2020
# PUT YOUR NAME AND USER ID HERE!
#
# Based on skeleton code by D. Crandall
#
#
# This is the file you should modify to create your new smart player.
# The main program calls this program three times for each turn.
# 1. First it calls first_roll, passing in a Dice o... |
b28d4a5f8c66bf48f67cb35dd1b6139dd3404efd | sidamarnath/CSE-231-Labs | /lab08a.py | 2,627 | 4.375 | 4 | ###############################
# lab08a.py
# Algorithm
# Finds unique words and prints count of them for specified data file
# Prints from most frequent to least frequent
# If words have same count, print those words alphabetically
###############################
import string
from operator import itemgett... |
3716b728a9b4af7aaa0bbe68fe53a9a95a536135 | imklever/pay | /other/digui+zhan+duilie/digui01.py | 712 | 4.1875 | 4 | #coding:utf-8
'''
递归调用:一个函数调用了自身,称为递归调用
递归函数:一个会调用自身的函数称为递归函数
凡是循环能干的事,递归都能干
'''
'''
方式:
1、写出临界条件
2、找这一次和上一次的关系
3、假设当前函数已经能用,调用自身计算上一次的结果,再求出本次的结果
'''
#输入一个数(大于等于1),求1+2+3+...+n的和
def sum1(n):
sum = 0
for x in range(1,n+1):
sum += x
return sum
'''
1+2+3+4+5
sum2(1)+0=sum2(1)
sum2(1)+2=sum2(2)... |
65bedffc531355b174d55f7c80d0e9d28f060835 | Aasthaengg/IBMdataset | /Python_codes/p02712/s461518951.py | 204 | 3.546875 | 4 | n=int(input())
ans=0
for i in range(n):
if (i+1)%3==0 and (i+1)%5==0:
continue
elif (i+1)%3==0:
continue
elif (i+1)%5==0:
continue
else:
ans+=i+1
print(ans) |
565235b3040dc63037bb855313d77f18c00993e0 | yunyusha/xunxibiji | /month1/week1/Python_class1/homework.py | 1,056 | 3.625 | 4 | # 第一题
num = input("请输入\n")
print(num)
# 第二题
money = input("请输入金额")
money = int(money)
i100 = money//100
money = money - i100 * 100
i50 = money // 50
money = money - i50*50
i10 = money // 10
money = money - i10*10
i5 = money // 5
money = money - i5*5
i1 = money // 1
print("共需要100元%d张,50元%d张,10元%d张,5元%d张,1元%d张" % (i100... |
abc6499a4b4312fdaa07c836fafbbeed7267881b | LingXii/number-recognition | /training.py | 3,717 | 3.5625 | 4 | import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
import cv2
import numpy
from image_resize import *
# test recognition
img=cv2.imread("0.jpg",0)# 读入灰度图片
img = img_resize(img)
mnist_img = numpy.zeros((28,28))
for i in range(28):
for j in range(28):
mnist_img[i,j] = img[i,j]... |
a7d28d56f9d497304176ad09db4e6945c0bb20e0 | ChaitanyaAmbegaonkar/CodingChallenge | /LRU.py | 1,450 | 3.625 | 4 | class Node(object):
def __init__(self, value):
self.value = value
self.next = None
self.prev = None
class LRUCache(object):
def __init__(self, capacity):
self.capacity = capacity
self.dic = {}
self.head = Node(0)
self.tail = Node(0)
self.head.nex... |
356e573301bad05108d17aa7bea882f001c26df3 | ChildofFire/CodingStuff | /HackerRank/cracking the interview/primality.py | 358 | 3.984375 | 4 | for _ in range(int(input())):
n=int(input())
if n==1:
print("Not prime")
elif n==2 or n==3:
print("Prime")
else:
mod=n%6
if mod==1 or mod==5:
flag=1
for i in range(2,int(n**0.5)+1):
if not n%i:
flag-=1
break
if not flag:
print("Not prime")
else:
print ("P... |
bafb99655933ce15c088efe521940f841e33d598 | jacocloeteHU/TICT-V1PROG-15 | /les 03/oefeningRevStr.py | 153 | 3.90625 | 4 | print(reversed('hallo'))
def rev(str):
s = ''
for i in range(len(str)-1,-1,-1):
print(i)
s += str[i]
print(s)
rev('jaco')
|
252de07512dcf5adf108ebe802b544c7b7872ca6 | maaaaaaaax/coding-dojo-python | /W1 | Fundamentals, OOP, Flask/Fundamentals/stars.py | 1,917 | 4.15625 | 4 | # Create a function called draw_stars() that takes a list of numbers and prints out *.
# x = [4, 6, 1, 3, 5, 7, 25]
# draw_stars(x) should print the following when invoked:
# ****
# ******
# *
# ***
# *****
# *******
# *************************
# lst = [4, 6, 1, 3, 5, 7, 25]
#
# def draw_stars(lst):
# # store the... |
7672d8c51082e1548d9fae810eb79998f8a919ea | bharathmc92/python-coding | /tuples_2.py | 1,034 | 3.984375 | 4 | # Given the tuple below that represents the Imelda May album "More Mayhem", write
# code to print the album details, followed by a listing of all the tracks in the album.
#
# Indent the tracks by a single tab stop when printing them (remember that you can pass
# more than one item to the print function, separating ... |
522ad8a3e6bfd81317e3e4030df5854a9048788e | oxhead/CodingYourWay | /src/lt_214.py | 2,158 | 4.25 | 4 | """
https://leetcode.com/problems/shortest-palindrome
Related:
- lt_5_longest-palindromic-substring
- lt_28_implement-strstr
- lt_336_palindrome-pairs
"""
"""
Given a string s, you are allowed to convert it to a palindrome by adding characters in front of it. Find and return the shortest palindrome you can find... |
33bffb04a99f62e401686ada23fa6854f941c5a7 | tuxnotes/python_gktrain | /week3/1process/p15_pool.py | 1,504 | 3.59375 | 4 | # Pool类表示一个工作进程池
# 如果要启动大量的子进程,可以用进程池的方式批量创建子进程
from multiprocessing.pool import Pool
from time import sleep, time
import random
import os
def run(name):
print('%s子进程开始, 进程ID: %d' % (name, os.getpid()))
start = time()
sleep(random.choice([1,2,3,4]))
end = time()
print('%s子进程结束, 进程ID: %d。耗时0.2%f' %... |
a67c05ed54d0bc8a4aa444bff112b4d35a844a25 | Nathan-Walk/code_py_book_data_structures_and_algo | /chap07_graphs/dijkstra.py | 5,359 | 4.34375 | 4 | # Ref: https://dev.to/mxl/dijkstras-algorithm-in-python-algorithms-for-beginners-dkc
from data import edges_with_weights as edges
from collections import deque, namedtuple
from math import inf
Edge = namedtuple(typename="Edge", field_names=["start", "end", "cost"])
def make_edge(start, end, cost=1):
return Edge... |
689c2a26871c075c124d20513ed0a731a32a4e3e | golfnut1400/kalacademy | /Hwk2_9 Science: wind-chill temperature.py | 844 | 4.53125 | 5 | '''
Introduction to Programming
Homework 2
Created by: Stan Corpuz
Jan 21, 2018
#Homework 2 9 Science: wind-chill temperature
'''
#Python's program to calculate the Wind Chill Index (WCI)
#CONSTANT
WINDCHILL_OFFSET = 35.74
WINDCHILL_FACTOR1 = 0.6215
WINDCHILL_FACTOR2 = 35.75
WINDCHILL_FACTOR3 = 0.4275
WIND... |
613072e9bf2cce332c859dde2361707fec950376 | Kaplun-Alex/Beetroot_Courses | /2021_03_20/Kit_Pes.py | 680 | 3.828125 | 4 | class Animal:
def __init__(self, an):
self.animal = an
def __str__(self):
return self.animal
def talk(self, say='Сыш? сюда иди!'):
return self.animal + say
class Dog(Animal):
def __init__(self):
Animal.__init__(self, an)
self.dog = 'Dog'
def __str__(self)... |
93224cc646edc62df7b08decf4bc371da413a269 | mming-liu/python | /exercise/letCode/数组中有重复的元素.py | 860 | 3.8125 | 4 | from typing import List
class Solution:
def containsDuplicate(self, nums: List[int]) -> bool:
# count = 0
# for num in nums:
# if nums.count(num) > 1:
# count = 1
# break
# else :
# pass
# for num in nums:
... |
42793fc8fee095457302a14dccb821a2cb9857fb | GusGus6148/Crash_Course_2019 | /CH_7_user_input_while_loops/dream_vacation.py | 383 | 4.125 | 4 | locations = []
while True:
location = input("if you could visit one place in the world, where would you go?"
+ "(type 'quit to exit): ")
if location == 'quit':
break
else:
locations.append(location)
print("\nHere is a list of the locations people would like to visit ... |
4931434781577023e5fed645e797fd8599fc7d69 | Zer0xPoint/LeetCode | /Recursion II/1.Divide and Conquer/Merge Sort an Array.py | 655 | 3.5625 | 4 | from typing import List
class Solution:
def sortArray(self, nums: List[int]) -> List[int]:
if len(nums) < 2:
return nums
mid = len(nums) // 2
sorted_nums = []
left_nums = self.sortArray(nums[:mid])
right_nums = self.sortArray(nums[mid:])
while left_nums... |
4fb6f96d10b7083913359e9ffe318e008c303480 | COW-edu/Study-21-1-codingTest | /MinJung/1주차/10828_스택.py | 673 | 3.5 | 4 | import sys
stack = []
def push(X):
stack.append(X)
def pop():
if stack == []:
return -1
return stack.pop()
def size():
return len(stack)
def empty():
if stack==[]:
return 1
else:
return 0
def top():
if stack ==[]:
return(-1)
return int(stack[len(stack)-... |
9957916597d1080b3093b941efa1f5c4962d143e | cpeixin/leetcode-bbbbrent | /array/sub-sort-lcci.py | 1,537 | 3.734375 | 4 | # coding: utf-8
# Author:Brent
# Date :2020/7/29 10:35 PM
# Tool :PyCharm
# Describe :给定一个整数数组,编写一个函数,找出索引m和n,只要将索引区间[m,n]的元素排好序,整个数组就是有序的。注意:n-m尽量最小,也就是说,找出符合条件的最短序列。函数返回值为[m,n],若不存在这样的m和n(例如整个数组是有序的),请返回[-1,-1]。
#
# 示例:
#
# 输入: [1,2,4,7,10,11,7,12,6,7,16,18,19]
# 输出: [3,9]
#
# 来源:力扣(LeetCode)
# 链接:https://leetcode-cn... |
9ad5ac087b2bc2bfda37433ab9f2c3b66203881d | Hammad214508/Quarantine-Coding | /30-Day-LeetCoding-Challenge/May/Week1/5-FirstNewCharString.py | 579 | 3.90625 | 4 | """
Given a string, find the first non-repeating character in it and return it's index.
If it doesn't exist, return -1.
Examples:
s = "leetcode"
return 0.
s = "loveleetcode",
return 2.
"""
class Solution:
def firstUniqChar(self, s: str) -> int:
# build hash map : character and how often it appears
... |
a87e66f2f72ba6ad4ce757d39ed70fb2b0b49558 | zziri/study | /ps/Programmers/다리를 지나는 트럭.py | 1,440 | 3.765625 | 4 |
class Truck:
def __init__(self, weight=0, dist=0):
self.weight = weight
self.dist = dist
def to_string(self):
return '''({}, {})'''.format(self.weight, self.dist)
class Bridge:
def __init__(self, weight=0, length=0, limit=0):
self.q = []
self.total_weight = weight... |
04fad98db209c75d4ec38471b36a7584fa8d2532 | venkatadri123/Python_Programs | /Sample_programs/4prod.py | 154 | 4.34375 | 4 | #To find product of given two numbers.
x=int(input('enter first no:'))
y=int(input('enter second no:'))
product=x*y
print("product of two no is:",product) |
a456842ecf7914a8835aff41a552f42359ecd8bc | milenafbn/python.Exercises | /ex044.py | 769 | 3.703125 | 4 | print('{:+^40}'.format('LOJAS AMERICANAS'))
v = float(input('Preço das compras: R$ '))
print('\033[1;4;40mFormas de pagamento\033[m')
print('''\033[1;30m( 1 ) À vista dinheiro/cheque
( 2 ) À vista cartão
( 3 ) 2x no cartão
( 4 ) 3x ou mais no cartão\033[m ''')
o = int(input('Qual a opção? '))
if o == 1:
p... |
423f461002a85f72374837d04d4db1911a130ea5 | anil8055/sachin_codes_pycharm | /path finding algorithm.py | 3,522 | 3.703125 | 4 | import pygame
from math import sqrt
pygame.init()
win_size = 600
win = pygame.display.set_mode((win_size, win_size))
pygame.display.set_caption('path finding algorithm')
row = 50
gap = win_size // row
stop = False
paint = False
start_end = []
start_path_finding = False
path_found = False
clock = pygame.time.Clock()
bl... |
0782bf423337248a8efb43387c75d3e048da470e | DikranHachikyan/CPYT210215 | /ex58.py | 440 | 4.15625 | 4 | # 1. дефиниция на класа
class Point:
# Конструктор на класа
def __init__(self):
#данни на класа
self.x = 10
self.y = 20
if __name__ == '__main__':
# 2. създаване на обект от тип Point
p1 = Point()
p2 = Point()
print(f'p1:({p1.x}, {p1.y})')
p1.x = 1
print(f'p1:... |
6f38b7962669124a712ef4adc27761d8c2c29fbc | haowei-zhang/lintcode | /156_merge_intervals.py | 607 | 3.625 | 4 | class Solution:
"""
@param: intervals: interval list.
@return: A new interval list.
"""
def merge(self, intervals):
# write your code here
if not intervals:
return intervals
intervals = sorted(intervals, key=lambda interval: interval.start)
result = [inte... |
c760dbe3b92e0dcf3a8553a365826886b2ca7748 | jusaviin/adventOfCode2020 | /day14/dockingEmulator.py | 5,505 | 4.15625 | 4 | #!/usr/local/bin/python3
# Advent of code puzzle 14-1
# Calculate the sum of memory registers after docking program has run
# Advent of code puzzle 14-2
# Calculate the sum of memory registers after docking program has run using ruleset 2
# Get the bit in bitIndex of an integer
def checkBit(integerValue, bitIndex):
... |
3bd5f5ff74c9a4d43a9a4ec64621f5ac51f4d265 | shivamnegi1705/Competitive-Programming | /Codeforces/(Div. 3) Round 677/E. Two Round Dances.py | 153 | 3.890625 | 4 | # Question Link:- https://codeforces.com/contest/1433/problem/E
from math import factorial
n = int(input())
x = factorial(n)*2
x = (x)//(n**2)
print(x)
|
b5f1fafdb32f0e71f0dac69c93abae40bd9872d9 | 82seongkyum/python_lecture | /basic/if_elif_2.py | 616 | 3.875 | 4 | select, answer, numStr, num1, num2=0, 0, "", 0, 0
select = int(input("1. 입력한 수식 계산 2. 두 수 사이의 합계 :"))
if select == 1 :
numStr = input("100//3+5")
answer = eval(numStr)
print("%s 결과는 %5.1f입니다. " %(numStr, answer))
elif select == 2 :
num1 = int(input("소수점 첫 번째 숫자를 입력하세요 : "))
num2 = int(input("소수점 두... |
1aebbff56a00e9e35c8bab9700e2f06481693853 | chris-malloy/9-17immersive-unit1-python | /day1_python/celcius_to_fahrenheit.py | 179 | 3.96875 | 4 | # covert celcius to fahrenheit
cel_temp = float(raw_input("What is the temperature? (in Celcius) >"))
print "In fahrenheit, that temperature would be %d." % (cel_temp * 1.8 + 32) |
8709ffde0f6b2c17c6e1c16714daf5bb9d8ed5ab | stephenthoma/prisoners | /prisonersdilemma.py | 3,481 | 3.640625 | 4 | class PrisonerBattle(object):
def __init__(self):
self.grid = [[(1, 1), (5, 0)], [(0, 5), (2, 2)]]
self.score_one = 0
self.score_two = 0
def score(self, move_one, move_two):
print move_one, move_two,
score = self.grid[move_one][move_two]
print score
retur... |
63df42e2ed8078a8a68102c38d9c4626205d8fd6 | jackLove5/Stratego | /board.py | 9,441 | 3.765625 | 4 | from pieces import *
from board_configuration import BoardConfiguration
from constants import Constants
"""
Construct a piece object given its rank and team
"""
def get_piece_from_rank(rank, team):
if (rank == 'S'):
ret = Spy(team)
elif (rank == '8'):
ret = Miner(team)
elif(rank.isdigit()):
ret = Mov... |
244c31099d3b65bd44805abb7ab1115a3728f0c5 | DarkAlexWang/leetcode | /laioffer/438.find-all-anagrams-in-a-string.py | 1,056 | 3.5 | 4 | #
# @lc app=leetcode id=438 lang=python3
#
# [438] Find All Anagrams in a String
#
# @lc code=start
class Solution:
def findAnagrams(self, s: str, p: str) -> List[int]:
if len(s) < len(p):
return []
res = []
slow, fast = 0, 0
d = collections.defaultdict()
s_list ... |
cf3410d186ecc5e2b3f692554b8910ba00cccdf5 | ethanlow23/leetcode_algorithms | /top-interview-questions/easy-collection/Array/05-intersection_two_arrays_ii.py | 279 | 3.5 | 4 | # Intersection of Two Arrays II
def intersect(nums1, nums2):
res = []
count = {}
for n in nums1:
if n in count:
count[n] += 1
else:
count[n] = 1
for n in nums2:
if n in count and count[n] > 0:
res.append(n)
count[n] -= 1
return res
|
b5668a7c11cc0c154518145f32df146b561147f7 | tkaleas/python-sandbox | /problems/permutations.py | 1,192 | 3.640625 | 4 | def swap(s, i, j):
lst = list(s)
lst[i], lst[j] = lst[j], lst[i]
return ''.join(lst)
def getPermutations(inputStr):
# Base Case
if len(inputStr) < 2:
return [inputStr]
total = []
#for c in inputStr:
for i in range(0,len(inputStr)):
c = inputStr[i]
permInput... |
53420224adf3d8b138029a083253c83f82e92dd1 | JaviCeRodriguez/Tkinter | /widgets/labels.py | 504 | 3.828125 | 4 | from tkinter import *
root = Tk()
root.title("Soy un título")
root.geometry("400x500")
label = Label(root, text="Hola mundo") # Creo la etiqueta label
label.pack() # Coloco la etiqueta label en la ventana root
# Otra forma de crear una etiqueta
var = StringVar() # Creo una variable de tipo string
label2 = Label(root... |
3dd6a6745f707d3b9df3909ac398d554daabdf5b | ahmadshaik1106/first-repo | /plant.py | 312 | 3.796875 | 4 | def growing_plant(upSpeed, downSpeed, desiredHeight):
us=upSpeed
ds=downSpeed
dh=desiredHeight
s=0
i=1
print(dh)
while True:
s+=us
print('After day ',i,' --> ',s)
s-=ds
if s>=dh-1: break
print('After night',i,' --> ',s)
i+=1
growing_plant(10,1,91)
|
a10beaabe7b9d0460a462bdbe5c50f437bfc6a36 | sancopanco/leetcode-solutions | /leetcode.py | 26,367 | 3.96875 | 4 |
#!/usr/bin/python
# -*- coding: utf-8 -*-
# q.169
# Given an array of size n, find the majority element.
# The majority element is the element that appears more than [n/2] times.
# You may assume that the array is non-empty and the majority element always exist in the array
# @param num, a list of integers
# @return... |
a2b113ce3204aa1a7c0d812b3a7a884e99d43123 | Cloudxtreme/optimal_cdn | /placement.py | 1,700 | 3.640625 | 4 | class PlacementManager(object):
"""
Manages client placement into servers.
"""
def __init__(self, servers_):
"""
Initialized from a list of servers and no clients.
"""
self.servers = servers_
# Each client maps to a list of tuples (servers, multiplicative_factor... |
912cf7b4512add88052d236413256163b822b77a | ssw1991/Python-Practice | /Module 6 - Shilo Wilson/Level 6.1/6.1.2/game.py | 1,707 | 3.8125 | 4 | import random
class player(object):
def __init__(self, strategy):
"""
Strategy is 1 of player switches, else 0
:param strategy:
"""
self._strat = strategy
self._choice = None
@property
def strat(self):
return self._strat
@property
def cho... |
acfbe3d456e9315dde82e270cb6d8092c7c98266 | peterbarla/AlgoExpertExercises | /ArraysCategory/MonotonicArray/solution_1.py | 239 | 3.625 | 4 | def isMonotonic(array):
inc = True
dec = True
for index in range(1, len(array)):
if array[index] < array[index - 1]:
inc = False
if array[index] > array[index - 1]:
dec = False
return inc or dec
|
246178e79a1259f51ec0587b73cbc0626b124089 | giuper/teaching | /OldClasses/ALGO19/14-BST/BST.py | 2,458 | 3.6875 | 4 | class NODE:
def __init__(self,k,v):
self.key=k
self.val=v
self.left=None
self.right=None
def __str__(self):
return str(self.key)+","+str(self.val)
class BST:
def __init__(self):
self.root=None
def __ins(self,node,k,v):
if node is None:
... |
ddbcb7ccf07ca61906eb649900a7cdc1811b77e1 | kemtay/tipp-aai-flags_classification | /ml_plot.py | 8,033 | 3.6875 | 4 | """
Machine Learning plots
"""
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
def plot_hist(df, x_col, x_labels):
""" To plot histogram for frequency counts """
print("Plotting histogram for %s..." %x_col)
print("Total counts:", len(df))
uniq_labels = sort... |
c34e85c8c2a0b989982401865ca9b7d4c7a4be0a | anvesh2502/Hackerrank | /Maximizing_xor/Maximizing_xor.py | 279 | 3.5625 | 4 | #!/bin/python
# Complete the function below.
def maxXor( l, r):
m=0
for i in range(l,r+1) :
for j in range(l,r+1) :
res=i^j
if res>m :
m=res
return m
_l = int(raw_input());
_r = int(raw_input());
res = maxXor(_l, _r);
print(res)
|
708195a60f18fc79c5ed14c9dc6191a93a918cc7 | TomsenTan/Based-algorithm | /select_sort.py | 1,001 | 4 | 4 | #-*-coding:utf8-*-
#选择排序
#算法要点:
#1.每次循环假定循环比较的数据的第一个数为最小值,
#将后面的数与其比较找到最小值,并将最小值与第一个数比较
#2.下一次循环就可以在range(len-i-1)即前一次冒泡比较次数基础上减一
# (即减去已经排好的前面数据的个数)
#总结来说每次都选择一个最小的数放在最前面
#平均时间复杂度为O(n2);空间复杂度为O(n),实际为O(n+1)
#算法实现:
import random
def select_sort(seq):
n = len(seq)
for i in range(n-1):
min_idx = i
... |
86ff918f77d0815a2068279beac1fefd2116ac79 | yangtao0304/hands-on-programming-exercise | /one-problem-per-day/10.01.py | 575 | 3.671875 | 4 | class Solution:
def merge(self, A: List[int], m: int, B: List[int], n: int) -> None:
"""
Do not return anything, modify A in-place instead.
"""
pos = m+n-1
a = m-1
b = n-1
while pos >= 0:
if a < 0:
A[pos] = B[b]
b -=... |
126bcb14a35a27e26c8407314e63143048ab5afc | mickey0524/leetcode | /273.Integer-to-English-Words.py | 1,706 | 3.609375 | 4 | # https://leetcode.com/problems/missing-number/
#
# algorithms
# Easy (24.49%)
# Total Accepted: 106,816
# Total Submissions: 436,070
from collections import OrderedDict
class Solution(object):
def numberToWords(self, num):
"""
:type num: int
:rtype: str
"""
if num == 0... |
a1ce1b74d47fb416e7203bb571536d08e390f2bc | CosmicTomato/ProjectEuler | /eul71.py | 1,718 | 3.953125 | 4 | #Ordered fractions
#Consider the fraction, n/d, where n and d are positive integers. If n<d and HCF(n,d)=1, it is called a reduced proper fraction.
#If we list the set of reduced proper fractions for d ≤ 8 in ascending order of size, we get:
#1/8, 1/7, 1/6, 1/5, 1/4, 2/7, 1/3, 3/8, 2/5, 3/7, 1/2, 4/7, 3/5, 5/8, 2/3,... |
e757d6f7c31cf89b4a7f9206f554a6336d3669ba | Mayank627/Daily_Python | /Swap two numbers.py | 181 | 4.03125 | 4 | a = int(input('Enter the first number: '))
b = int(input('Enter the second number: '))
a = a + b
b = a - b
a = a - b
print('The value of a is', a, 'and the value of b is', b)
|
e72214b68145f30c8c0995b00043784ced936cfe | wikilele/ml-neural-network | /neuralnetwork/neuron.py | 2,367 | 3.734375 | 4 | class InputNeuron:
def __init__(self):
pass
def compute_output(self, input):
return input
class Neuron(InputNeuron):
def __init__(self, bias, weights, activation_function):
# self.bias = bias
self.weights = [bias] + weights
self.activation_function = ac... |
d4d408dcc96f63f03ea883a64af90f555f05a609 | rin129/ENGSCI_263_OR_Project_Team_3 | /linearProgramSat.py | 3,974 | 3.984375 | 4 | # ENGSCI 263
# OR Project, Team 03
# This file contains the formulation and execution of a linear program which solves a Vehicle Routing Problem,
# so as to help advise Woolworths NZ in their finding of a least-cost routing schedule for their truck fleet.
import numpy as np
import pandas as pd
from pulp import *
#... |
b93f0aa83acb3bb127792aecf217b0b01d409411 | brasqo/pythoncrashcourse | /cars.py | 500 | 4.03125 | 4 | #cars
cars = ['bmw', 'audi', 'toyota', 'subaru']
cars1 = ['bmw', 'audi', 'toyota', 'subaru']
cars2 = ['bmw', 'audi', 'toyota', 'subaru']
dots = "..."
cars.sort(reverse=True)
print(cars)
print(dots)
print("Here's the original list:")
print(cars1)
print("\nHere is the sorted list:")
print(sorted(cars1))
print("\nHer... |
2f18e49f0b409cb9271d99a6fd1d4fb711eb4214 | vishalb007/Python-Machine-Learning | /Assignment2_1_2.py | 193 | 3.546875 | 4 | from Assignment2_1_1 import *
def main():
num1=int(input())
num2=int(input())
add(num1,num2)
sub(num1,num2)
mul(num1,num2)
div(num1,num2)
if (__name__=="__main__"):
main()
|
0f71091ebe4c7b847587dbc96715c5952c5de7ae | lrana-227/RBootCamp | /hw/03-Python/Instructions/PyPoll/main.py | 2,145 | 3.671875 | 4 | import os
import csv
# Path to collect data from the Resources folder
poll_csv = os.path.join('Resources', 'election_data.csv')
#Initilize Variable
count = 0
vote_count = []
candidate = []
percent = []
with open(poll_csv, 'r') as csvfile:
# Split the data on commas
csvreader = csv.reader(csvfile, delimite... |
37e32d7553905d6125ef4be777e86aa18734086f | voron521/geekbrains_osnovy_python | /task_5.py | 1,509 | 4 | 4 | #5. Запросите у пользователя значения выручки и издержек фирмы. Определите, с каким финансовым результатом работает фирма
#(прибыль — выручка больше издержек, или убыток — издержки больше выручки). Выведите соответствующее сообщение.
#Если фирма отработала с прибылью, вычислите рентабельность выручки (соотношение прибы... |
5cb1eec881d084f160e48029ee9199529034f874 | shoshanadick/echo_game | /echo_game.py | 91 | 3.5 | 4 | while True:
print("Hi. Say something!")
user_input = input()
print(user_input)
|
c47dabe1f8e56dc368af80e1c0bfde23cd357066 | Reiko1337/grokking-algorithms | /main.py | 4,718 | 3.984375 | 4 | def binary_search(arr: list, item: int) -> int:
"""
Бинарный поиск ГЛАВА #1
"""
low = 0
high = len(arr) - 1
while low <= high:
mid = (low + high) // 2
guess = arr[mid]
if guess == item:
return mid
if guess > item:
high = mid - 1
el... |
0a70cb64f2632a60b8015da8261b821210cdedc7 | rayturner677/polishing_skills | /26_April/magazine_note.py | 562 | 3.90625 | 4 | from collections import Counter
def make_ranson():
magazine = input("Magazine equal: ")
user_side_input = input("Note equal: ")
note = []
counter = Counter(magazine)
for char in user_side_input:
if char in counter:
counter[char] -= 1
note.append(counter[char])
... |
1e2ea00b37d89d7763805e8a7a0a57c2f1da7d3d | Socialclimber/Python | /Assesment/untitled.py | 1,684 | 4.1875 | 4 | def encryption():
print("Encription Function")
print("Message can only be lower or uppercase letters")
msg = input("Enter message:")
key = int(input("Eneter key(0-25): "))
encrypted_text = ""
for i in range(len(msg)):
if ord(msg[i]) == 32: #check if char is a space
encrypted_text += chr(ord(msg[i])) # cocnca... |
db0a857034a1665fb878181432dbf5c122a2837e | skconan/hackerrank | /binary_tree.py | 1,176 | 3.921875 | 4 | #!/usr/bin/env python
class BSTreeNode:
def __init__(self, node_value):
self.value = node_value
self.left = self.right = None
def _insert_node_into_binarysearchtree(node, data):
if node == None:
node = BSTreeNode(data)
print(node.value)
else:
if (data <= node.valu... |
5c86694e4ea928b7940e12e9e2dea47957892b74 | alvinalmodal/codewars | /tests/test_vowel_changer.py | 904 | 3.734375 | 4 | import unittest
from src.vowel_changer import change_vowels
class TestVowelChanger(unittest.TestCase):
def test_change_vowels(self):
self.assertEqual('hinnih hinnih bi-binnih binini finni fi-finnih fii, fy, mi-minnih. hinnih!', change_vowels("hannah hannah bo-bannah banana fanna fo-fannah fee, fy, mo-mann... |
97993f37205f64cdfd9f910f6a71cc35ddf57b2c | logan-j/Practice | /examples/ProjEuler/Fibonacci.py | 238 | 3.546875 | 4 | def fib():
a, b = 1, 1
while True:
yield a
a, b = b, a + b
def main():
count = 1
for x in fib():
print count, len(str(x))
if len(str(x)) > 999:
break
count += 1
main()
|
4022b7abc9b1f260d29171adf803d1a3c12c86a0 | paul0920/leetcode | /question_leetcode/120_2.py | 483 | 3.734375 | 4 | # DFS: divide & conquer. TLE
# Time complexity: O(2^n), n: triangle layer counts
def minimumTotal(triangle):
"""
:type triangle: List[List[int]]
:rtype: int
"""
return dfs(triangle, 0, 0)
def dfs(triangle, x, y):
if x == len(triangle):
return 0
left = dfs(triangle, x + 1, y)
... |
e83fbe1f40ee28ef4d7b84b70e5965b34d0d1ed1 | love554468/leetcode | /solution/752_Open_the_Lock.py | 1,488 | 3.609375 | 4 | from collections import deque
class Solution:
def openLock(self, deadends: List[str], target: str) -> int:
start = "0000"
#We will use Set, instead of List to check if an item is contained within it "x in s"
deadends, visited = set(deadends), set(start)
if start in deadend... |
5b9ddf83bad7618b0a340165115b98804ec5aacb | manjusha18119/manju18119python | /python/assign2b.py | 91 | 3.546875 | 4 | n=1
for i in range (0,4):
for j in range (i+1):
print (n,end="")
n=n+1
print("")
|
90bdfa1d55db037aea14121a620617fc75f40314 | ShehabSunny/coding-challenges | /python/reverse_integer.py | 913 | 3.796875 | 4 | """
Website: Leetcode
URL: https://leetcode.com/problems/reverse-integer/
Problem statement:
Given a 32-bit signed integer, reverse digits of an integer.
Example 1:
Input: 123
Output: 321
Example 2:
Input: -123
Output: -321
Example 3:
Input: 120
Output: 21
Note:
Assume we are dealing with an environment which cou... |
36b8dc06d16dc866756eed17f53c293fe1c4ec36 | fishjawzrex/Algorithms-and-Data-Structures-in-Python | /node.py | 629 | 4 | 4 | '''THIS SCRIPT IS INTENDED TO TEST
AND IMPLEMENT A LINKED LIST DATA STRUCTURE'''
class Node: #create Node class and initialize parameters
def __init__(self, dataval): #class accepts one parameter
self.dataval = dataval
self.nextval = None #pointer to next node... |
61b908311b683fc4c97ce81c668026d0dbb87a1b | Jose0Cicero1Ribeiro0Junior/Curso_em_Videos | /Python_3/Modulo 2/2_Repetições em Python (for)/Exercício_054_Grupo_da_Maioridade_v0.py | 569 | 4 | 4 | #Exercício Python 54: Crie um programa que leia o ano de nascimento de sete pessoas. No final, mostre quantas pessoas ainda não atingiram a maioridade e quantas já são maiores.
from datetime import date
date = date.today().year
maior = menor = 0
for c in range(1, 8):
ano = int(input(f'Data de nacimento da {c}° pes... |
79b1e7769f0392d2053818270d7703fb3d6e0c65 | DuskTillDwan/Intro-To-Python | /Assignment 3/csc242-901hw3.py | 4,130 | 4.15625 | 4 | # CSC 242-901
# Assignment 3 template
# Put your name here
# List your collaborator(s) here (no more than two other people
# either directly or indirectly)
# Add a comment in this file with a clear and detailed explanation
# of the contributions of each collaborator
# If you did not collaborate with anyone, say that... |
7b8794a9d7c41e81421e27ae21648369b876ffaa | bgonzalo/progcomp | /bgonzalo_prob1001.py | 629 | 4.0625 | 4 | #http://acm.timus.ru/help.aspx?topic=python
import sys, math
nums = [] #crea una lista vacia llamada nums
for line in sys.stdin: #a cada elemento en la lista introducida atravez de stdin
for word in line.split(): #los separa en cada espacio y a acada elemento de las nuevas ... |
6972be64ea5f6b498d07ed68e39a663ee607f802 | gbrough/LeetCode | /Python/Split a String in Balanced Strings.py | 328 | 3.53125 | 4 | class Solution:
def balancedStringSplit(self, s: str) -> int:
match = 0
character = 0
for letter in s:
if letter == 'R':
character +=1
if letter == 'L':
character -=1
if character == 0:
match +=1
retu... |
59c836e18152aa25dbc9701b67299f3d2d3243db | sunday-mayweather/img2txt_server | /img2txt.py | 3,143 | 3.59375 | 4 | from PIL import Image
def generate_grayscale_for_image(pixels, width, height, bgcolor):
# grayscale
color = "MNHQ$OC?7>!:-;. "
string = ""
# first go through the height, otherwise will rotate
for h in range(height):
for w in range(width):
rgba = pixels[w, h]
# ... |
78472dcc9b4cd4c735be2fd0c001b2b328a9fe0a | pantlavanya/tic_tac_toe_game | /src/template.py | 1,718 | 3.609375 | 4 | GAME_DESCRIPTION = """\n\n\t\tChoose Game Type :\n
Game 1: Enter 1 for Pattern (X, O) based game\n
Game 2: Enter 2 for Number (ODD, EVEN) based game\n
1st player will be X or ODD always\n\n
Choose Pla... |
2c4ba0d0c00e8e4b451aee0814b0dec7da50ee52 | darumada/alghoritms | /data structures/tree.py | 683 | 3.8125 | 4 | class Tree:
class _Node:
def __init__(self, e, parent=None):
self.element = e
self.parent = parent
self.children = []
def __init__(self):
self.root = None
self._size = 0
def is_empty(self):
return self._size == 0
def __len__(self):
... |
cfb027e8469962bc4bcd3e88150aece417d23a52 | danielaahlin/EDAF05-labs-public | /1stablemarriage/stable.py | 2,599 | 3.5 | 4 | import sys
import operator
def sort_data(std_in):
women = []
men = []
# with open(path, 'r') as file:
i = 0
for f in std_in:
data = f.split()
if len(data) == 1:
N = int(data[0])
# print(N)
else:
if i >= N * 2:
break
... |
3f184feba5fd023a1a170411d0a4328d5208849e | crane-ium/daily-coding-problems | /dcp1-77/dcp8/unival_checker.py | 1,390 | 3.984375 | 4 | from collections import deque
class Node(object):
"""
Node object for a binary tree
"""
def __init__(self, val, left=None, right=None):
self.val = val
self.left = left
self.right = right
def __str__(self):
return str(self.val)
class BinaryTree(object):
def ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.