blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
423efa88a1f82048f7ca53999a5afb695a946a49 | Luciferochka/Colokvium | /19.py | 616 | 3.953125 | 4 | #Знайти суму всіх елементів масиву цілих чисел що задовольняють умові: остача від ділення на 2 дорівнює 3. Розмірність масиву - 20. Заповнення масиву здійснити випадковими числами від 200 до 300.
import numpy as np
import random
n = 20
a = np.zeros((n),dtype=int)
sum = 0
for i in range(n):
a[i] = random.randint(20... |
9b8e57889bb7379646823306c183ee29b2295288 | fanser123/The-courseware | /day7/d5.py | 247 | 3.59375 | 4 | #-*-coding:utf-8 -*-
#!/usr/bin/python3
# @Author:liulang
'''
可变对象,调用函数的时候,传地址,不可变,传值
'''
def change_list(list1):
list1.append("1")
test_data = [1,2,3]
change_list(test_data)
print(test_data)
|
8dbaa03ffa9bf8ff6892278be38e5bd2175f95e0 | rauladolfotecgda/Python-Exercises | /WSQ12 - Word counter.py | 292 | 3.671875 | 4 | #Raúl Adolfo Torres Vargas
#A01400187
#WSQ12
fs= "We have flowers and flowersflowers. Four FlOwErs in fact "
count= 0
fs = fs.lower()
w= "FlOwErs"
w= w.lower()
lf = fs.find(w)
while(lf >= 0):
print("Found flower at ", lf)
count = count + 1
lf = fs.find(w, lf + 1)
print("I found ", count,"of", w) |
733ac4b00990994a2c9d0b3458fd817eaa0a4e32 | AlexeySergeychuk/AlexeySergeychukPython | /testt.py | 1,250 | 3.59375 | 4 | class Sklad:
list = []
@staticmethod
def counts():
print(f'На складе содержится следующая продукция: {Sklad.list}')
class Equipment:
def __init__(self, mark, name, year):
self.mark = mark
self.name = name
self.year = year
def addsklad(self):
... |
d94e0125e48f4b71c5df363da5e76673e9129f15 | Roshan84ya/data-structure-with-python | /segmenttree/segment_tree sum update.py | 3,118 | 3.71875 | 4 | #building the segmenttree for the given array
"""
for building the segment tree we need to build the tree till we reach at the base condition that is when end ==start i.e the case when in out segment tree has only one element and that is
equal to the element at index i so in this manner we are firstly filling the el... |
27dfa83501276d2594a82baa702753f448a2530c | jotanice/JDev | /Python/GGuanabara/ex3.py | 162 | 3.890625 | 4 | # -*- coding: utf-8 -*-
n1 = input('Digite um número: ')
n2 = input('Digite outro número: ')
#n11 = int(n1)
#n21 = int(n2)
print('A soma é ',int(n1)+int(n2)) |
7d60bd6fda2d94da3cebbf66d07b9564591dd089 | rajputarun/machine_learning_intern | /keras_bottleneck_multiclass.py | 6,828 | 3.578125 | 4 | '''
Using Bottleneck Features for Multi-Class Classification in Keras
We use this technique to build powerful (high accuracy without overfitting) Image Classification systems with small
amount of training data.
The full tutorial to get this code working can be found at the "Codes of Interest" Blog at the following li... |
fda771a7d5f235a09c8d526714626c9e2e06fc1e | cosmosZhou/sympy | /axiom/algebra/lt/lt/imply/lt/abs/mul.py | 531 | 3.65625 | 4 | from util import *
@apply
def apply(x_less_than_a, y_less_than_b):
abs_x, a = x_less_than_a.of(Less)
abs_y, b = y_less_than_b.of(Less)
x = abs_x.of(Abs)
y = abs_y.of(Abs)
return Less(abs(x * y), a * b)
@prove
def prove(Eq):
from axiom import algebra
x, y, a, b = Symbol(real=True)
... |
3da216050ff4d76013231ef9477a1ddddae9f853 | TardC/books | /Python编程:从入门到实践/code/chapter-11/test_employee.py | 673 | 3.609375 | 4 | import unittest
from employee import Employee
class EmployeeTestCase(unittest.TestCase):
"""Test Employee.py"""
def setUp(self):
"""Create a Employee object."""
self.my_employee = Employee('tard', 'c', 150000)
def test_give_default_raise(self):
"""Test the default arg... |
cf9aebff417467535b257489bd2329121a467800 | Israelgd85/Pycharm | /excript/app-comerciais-kivy/Python(Udemy-Claudio Rogerio/Exe_lista_4/exe-4.py | 353 | 3.8125 | 4 | # 4) Escreva um algoritmo contendo uma função que necessite de três argumentos.
# Em seguida, imprima na tela os argumentos em ordem ascendente e,
# por fim, imprima a média aritmética:
arg = [23,13,12]
def ascendente (x,y,z):
media = (x + y + z) / 3
print(arg)
print("A média caculada é :", media)
arg.... |
193876b6601a74e75efe0e12241dcf1ee61cd0e1 | muhsayd/panenthe | /shared/drivers/attrdict.py | 2,868 | 3.609375 | 4 | #!/usr/bin/env python
# Panenthe: attrdict.py
# Defines a class that converts a dictionary input into attributes
##
class attrdict(object):
def __init__(self, dict):
for attr in dict:
exec("self.%s = dict[attr]" % attr)
self.dict = dict
# return dict
def get_dict(self):
return self.dict
# require attr... |
8223fc48bc510ee049bebfa52d36df4fa4475290 | Elanakova/python-programming-stepik | /total_sleep.py | 194 | 3.71875 | 4 | #Tim sleeps X hours at night and Y minutes in the afternoon.
#Count how many minutes Tim sleeps per day.
#Input:
#7
#30
#Output:
#450
X = int(input())
Y = int(input())
print(X*60 + Y) |
8d782f3d4b9fdd9c85c7cdb83d0f1db01feb2a3d | crl0636/Python | /code/Search2DMatrix.py | 683 | 3.609375 | 4 | class Solution(object):
def searchMatrix(self, matrix, target):
"""
:type matrix: List[List[int]]
:type target: int
:rtype: bool
"""
if not matrix:
return False
start = 0
end = len(matrix) - 1
while start <= end:
mid =... |
0bb1e6666940e5b3c715b333b20986a732e859f2 | hrishitelang/Python-For-Everybody | /Programming for Everybody (Getting Started with Python)/Week 6/Assignment4.6.py | 230 | 3.8125 | 4 | def computepay(h,r):
if h<=40:
return h*r
elif h>40:
return (h*r + (h-40)*0.5*r)
hrs = float(input("Enter Hours:"))
rph = float(input("Enter Rate per hour:"))
p = computepay(hrs,rph)
print("Pay",p)
|
f828fe9d26ba2e7be02793d901da603ceb96475c | JianxiangWang/LeetCode | /6 ZigZag Conversion/solution.py | 624 | 3.6875 | 4 | #!/usr/bin/env python
#encoding: utf-8
import sys
import operator
reload(sys)
sys.setdefaultencoding('utf-8')
class Solution(object):
def convert(self, s, numRows):
if numRows < 2 or numRows >= len(s):
return s
zigzag = [[] for _ in range(numRows)]
row, step = 0, 1
f... |
4d2973e2c6894654773a9da9985625dbaf9ad81f | xinxinboss/PythonDemo | /oop_demo/test02.py | 743 | 4.03125 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Date : 2017-11-30 11:26:38
# @Author : TaoYuan (1876665310@qq.com)
# @Link : http://blog.csdn.net/lftaoyuan Python互助学习qq群:315857408
# @Version : $Id$
# 继承和多态
class Animal(object):
def run(self):
print('Animal is running...')
class Dog(Animal):
... |
60862d8b0787ffa6e257df54ae25189befa09927 | RizaZNisa/basic-python-b4-c | /Day 2/input.py | 544 | 4.21875 | 4 | #That means we are able to ask the user for input as a STRING.
# cara 1
name = input("Masukkan nama kamu : ")
umur = input("Masukkan umur kamu : ")
#perlu spasi jika menggunakan + dan hanya untuk type data STRING
print("Nama saya adalah " + name + " sedangkan umur saya adalah " + umur + " tahun")
# tidak... |
d46a7ef37dd2b009606bfb88ea08be9919a6ebf9 | davidknoppers/holbertonschool-higher_level_programming | /0x03-python-data_structures/4-new_in_list.py | 226 | 3.5 | 4 | #!/usr/bin/python3
def new_in_list(mylist, idx, element):
if mylist is None:
return (None)
copy = mylist[:]
if idx < 0 or idx >= len(copy):
return (mylist)
copy[idx] = element
return (copy)
|
53e6c367c4828e9dbd5ebbce4720ba2b0c24ee13 | sreyansb/Python_Mini_Compiler | /FINAL/Code_Optimization/dead_code_elimination.py | 1,598 | 3.53125 | 4 | '''
Code logic:
Loop through all the lines in the quads (i.e. while flag is True) at every iteration and for
every such line-see if there is no line where the result of the first line is used.
'''
import csv
import copy
PATH_TO_CSV = r"./non_optimized/show.tsv"
PATH_TO_OUTPUT_1 = r"./optimized/showDCE.tsv"
file_inp... |
08390f2e175b2a457f6238ee0d373648260a0faa | suvgerlop142/Ch.03_Input_Output | /pratice.py | 205 | 4.21875 | 4 | print("WELCOME, to the MPG calculator\n")
miles=float(input("Please enter miles traveled: "))
gal=float(input("How many gallons of gas did you use: "))
mpg=miles/gal
print("Your gas mileage is",mpg,"mpg")
|
856e9a12c6d4e0866b164b67448332687e529640 | itsolutionscorp/AutoStyle-Clustering | /all_data/exercism_data/python/difference-of-squares/9023a422b83f4d26a7d57e154eb8afbb.py | 462 | 4 | 4 | def sum_of_squares(number,summation = 0):
if number == 0:
return summation
else:
summation += number**2
return sum_of_squares(number-1,summation)
def square_of_sum(number, summation = 0):
if number == 0:
return summation**2
else:
summation += nu... |
5bc2bfc9d39478a8ed23a914b2562e11f101f7fa | MegaMotion/SVR_Blender_Automation_Plugin | /fake_bpy_modules_2.82-20200514/bpy/utils/units.py | 2,150 | 4.0625 | 4 | import sys
import typing
def to_string(unit_system: str,
unit_category: str,
value: float,
precision: int = 3,
split_unit: bool = False,
compatible_unit: bool = False) -> str:
'''Convert a given input float value into a string with units.
... |
98d5ea2964946106a5ce430c4e7e30ba75d4461b | nvincenthill/python-sandbox | /loops.py | 272 | 3.890625 | 4 | knights = {'gallahad': 'the pure', 'robin': 'the brave'}
# use items() to access each key/value pair in dictionary
for k, v in knights.items():
print(k, v)
# enumerate over list to access each value/index
for i, v in enumerate(['tic', 'tac', 'toe']):
print(i, v)
|
d4345ce95afd2b4d1a54f00a43a75af49197de0d | MartinLesser/Procedural-distribution-of-vegetation | /intern/src/python/Gui/new_vegetation_type_window.py | 2,982 | 3.734375 | 4 | import tkinter as tk
from intern.src.python.Data.vegetation import Vegetation
from intern.src.python.Gui.vegetation_window import VegetationWindow
class NewVegetationWindow(tk.Frame):
"""
Window for creating new vegetation.
"""
def __init__(self, parent, main_window, controller):
tk.Frame.__... |
7d92cba565129f9d0c9433aa7b7311c26d2b40cc | sanjay1313/Python-practice | /list_tuple.py | 216 | 4.21875 | 4 | def change_string(string):
list1 = string.split(',')
tuple1 = tuple(list1)
print("List : ",list1)
print("Tuple : ",tuple1)
string = input("Enter numbers separated by comma : ")
change_string(string) |
7d738f2fcc3aad537338dfe6f40b4b999c001617 | vibhubhatia007/AllAboutML | /MultipleLinearRegression/Multiple_linear_regression2.py | 1,766 | 3.5625 | 4 | #import the libraries
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
#import the dataset
dataset = pd.read_csv('50_Startups.csv')
X = dataset.iloc[:, :-1].values
y = dataset.iloc[:, 4].values
#encoding the catgorical values into discreet values
from sklearn.preprocessing import LabelEncoder, O... |
c08f9d023b6116f2f899ab1a935b8504ecfeaf90 | adrian-calugaru/fullonpython | /classes.py | 1,894 | 3.6875 | 4 | import random
class Vehicle:
def __init__(self, make, model, year, weight, needsMaintenance = False, tripsSinceMaintenance = 0):
self.make = make
self.model = model
self.year = year
self.weight = weight
self.needsMaintenance = needsMaintenance
self.tripsSinceMaintena... |
0a282e473d9b08c8e849efbb3dfe8f4ef616e562 | benwei/Learnings | /pySamples/numbrOperate.py | 303 | 3.609375 | 4 | #!/usr/bin/env python
from decimal import Decimal
## http://stackoverflow.com/questions/4643991/python-converting-string-into-decimal-number
A1 = [' "29.0" ',' "65.2" ',' "75.2" ']
result = [float(x.strip(' "')) for x in A1]
print result
result = [Decimal(x.strip(' "')) for x in A1]
print result
|
3d23ba1a4945b36ad43c50c02b00717783cd9f13 | kmlporto/Algoritmo | /Python/Usando vetor e listas/8.py | 847 | 4.09375 | 4 | #pegar todos os estados
estados=[]
for i in range(0,3,1):
nome = input("ESTADO: ")
estados.append(nome)
votos=[]
#pegar todos os votos
v = input("Melhor estado: ")
while (v in estados):
votos.append(v)
v = input("Melhor estado: ")
#variavel para comparar o estado mais votado, e quant de votos que o mais vota... |
4253ff097f680765522ef99dfba0a1a4a7453eef | eronekogin/leetcode | /2019/permutations_ii.py | 1,291 | 3.734375 | 4 | """
https://leetcode.com/problems/permutations-ii/
"""
from typing import List
class Solution:
def permuteUnique(self, nums: List[int]) -> List[List[int]]:
"""
Insert to next number to any of the position of the pre permutations.
When the next number is found in the pre permutation, skip... |
c90831803ddcce0a3ba05a872d16d0c3f4f15433 | santigp258/MisionTic2022 | /NotasDeClase/problemas.py | 998 | 4.21875 | 4 | '''
Desarrollar un algoritmo que reciba dos cadenas de caracteres y
determine si la primera está incluida en la segunda.
Se dice que una cadena está incluida en otra si todos los caracteres
con repeticiones de la cadena esta en la segunda cadena sin tener en cuenta
el orden de los caracteres.
Ejemplo:
-"prosa" es... |
3ad70e93005671ac6a79ede40191f42867ed7655 | CabraKill/transposed_matrix | /src/util/read_var.py | 268 | 3.984375 | 4 | def read_number(text: str, integer: bool = False):
try:
value = float(input("{}".format(text)))
return int(value) if integer else value
except:
print("Insira um número válido!!!")
raise Exception("Insira um número válido!")
|
c2f9baa91ef0468f3d913b189f0ce84bd3a88d76 | fstakem/PMuniX | /src/collectMuniData/Route.py | 1,694 | 3.734375 | 4 | # -----------------------------------------------------------------------------
#
# Route.py
# By: Fred Stakem
# Created: 12.13.11
# Last Modified: 12.13.11
#
# Purpose: This is the route class which is the main class for a bus
# route.
#
# ----------------------------------------------------------... |
6cb5520587ef700781ccbdd4f146b15efa27683a | Mostofa-Najmus-Sakib/Applied-Algorithm | /Leetcode/Python Solutions/Linked List/copyListwithRandomPointer.py | 1,650 | 3.515625 | 4 | """
LeetCode Problem: 138. Copy List with Random Pointer
Link: https://leetcode.com/problems/copy-list-with-random-pointer/
Language: Python
Written by: Mostofa Adib Shakib
"""
# Time Complexity: O(n)
# Space Complexity: O(n)
class Solution:
def copyRandomList(self, head: 'Node') -> 'Node':
if head is Non... |
4ef373e91493f52c1ccb578ff29c48bad7d37a7b | lplade/sea_battle | /player_io.py | 3,431 | 4 | 4 | from constants import *
def msg(string):
"""
This just wraps print()
:param string:
:return:
"""
print(string)
def get_input(prompt):
"""
This just wraps input()
:param prompt:
:return:
"""
return input(prompt)
def interactive_get_placement_coord(ship):
"""
... |
1c292785fe64422067cbc000aa20434e37ed4b23 | PaulGood247/CloudComputing | /lab3.py | 371 | 3.734375 | 4 | #Lab 3
x= raw_input("Enter string: ") #Take in input
result= x[::-1] #[::-1] reverses string and stores in result
if (result ==x ):
print 'true'
else:
print 'false'
# I wrote the program first without any commits as my commits would not work, after i got help in lab i committed whole program. I understand the 4 c... |
ee9ad09d56da4c283502c95b8d93496b86535c7c | adrija24/languages_learning | /Python/Day 1/To reverse a number.py | 147 | 4.3125 | 4 | """To reverse a number"""
n=int(input("Enter the number: "))
s=0
while n!=0:
m = n%10
n=n//10
s=s*10+m
print("The reversed number: ",s) |
d8d1576ea84457e28e17e29cf98ba824779e838b | Ben-Rapha/Python-HWS | /my final project.py | 2,267 | 4.15625 | 4 | # CSI_31_KINGSLEY_OTTO_FINAL_PROJECT.PY
# THIS PROGRAM CHECKS A USER'S ID AND PASSWORD AGAINST A FILE.
import sys
# Introduction to the user
def intro():
print("This program asks the user for his/her user-ID and password and runs ")
print("it against a file of user-ID's and passwords.The user has only t... |
f79f080efbd43437b956556694302c3b346b4d56 | killstyles/my_love | /GUI.py | 411 | 3.59375 | 4 | from tkinter import *
class Application(Frame):
def __init__(self,master=None):
Frame.__init__(self,master)
self.pack()
self.createWidgets()
def createWidgets(self):
self.helloLabel = Label1(self,text='Hello, world!')
self.helloLabel.pack()
self.quitButtom = Button(self, text='Quit', command=self.quit)
... |
d7415d0451b8c69b21dbc017a35d3c8b2e526f1b | abdibogor/The-Bad-Tutorial | /05_Python/22_The Continue Statement/continue.py | 281 | 4.03125 | 4 | """
for var in range(1,16):
print(var)
"""
"""
for var in range(1,16):
if(var in range(9,14)):
continue
else:
print(var)
"""
print("Enter a string:")
var=input()
for letter in var:
if(letter==' '):
continue
else:
print(letter)
|
21eae74e12ec987cea69f6be9494e5f92c0dbd6a | eric496/leetcode.py | /hash_table/1189.maximum_number_of_balloons.py | 854 | 4.125 | 4 | """
Given a string text, you want to use the characters of text to form as many instances of the word "balloon" as possible.
You can use each character in text at most once. Return the maximum number of instances that can be formed.
Example 1:
Input: text = "nlaebolko"
Output: 1
Example 2:
Input: text = "loonbalxball... |
e08d6ded70fe91e5ed59697b782093049c75ba41 | SuperAllenYao/pythonCode | /chapter_class/homework/Vehicle.py | 2,213 | 4.0625 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
class Vehicle(object):
# 自定义Vehicle类属性
def __init__(self, speed: int, size: tuple, trans_type='SUV'):
# 自定义实例的初始化方法
self.trans_type = trans_type
self.speed = speed
self.size = size
# 自定义实例方法show_info,打印实例的速度和体积
def show_in... |
ee9b5cf5959aa845d5b23d3bf00da67729184906 | Javaman1138/adventofcode | /day9.py | 3,496 | 3.59375 | 4 | test_data = ["London to Dublin = 464",
"London to Belfast = 518",
"Dublin to Belfast = 141",
"NY to Belfast = 100",
"NY to London = 200",
"NY to Dublin = 300"]
#test_data = ["London to Dublin = 464",
# "London to Belfast = 518",
# "Dublin to Belfast = 141"]
distances = {}
start_points = []
f1 = open('day... |
b7b9724183b9f38d3e4b1e86a0958bc8b0c6aba5 | Lan-Yang/Modern-Search-Engine | /query_answer.py | 3,618 | 3.671875 | 4 | import json
import urllib
# User input question in the format "Who created [X]?"
question_str = raw_input('Input your question like "Who created [X]?", X is a book name or a company name: ')
question = question_str.split()
length = len(question)
result_list = []
# Check input question's format
if (question[0].lower()... |
c8f0b3780e5811836c5247e517a402566c3d3468 | imsudheerkumar/Python-Programming | /sudheer_python_2/lower.py | 217 | 3.890625 | 4 | str=input("enter string")
count=0
count2=0
for i in str:
if(i.islower()):
count=count+1
elif (i.isupper()):
count2=count2+1
print("lower case :",count)
print("upper case :",count2)
|
1654f86e23d3aee828e722a1ac81923a01df2606 | manon2012/python | /work/leetcode/countprime.py | 420 | 3.609375 | 4 | def countPrimes( n):
"""
:type n: int
:rtype: int
"""
for i in range(2, n):
if n % i == 0:
# print ("not p")
# return False
break
else:
return True
# b = list(filter(countPrimes, range(2, 10)))
# print (b)
def getsum(n):
# a=[]
b = l... |
8cbf620b8bbd1dbe2785a44ba0ba5217e4ef21a7 | tytyman5264/pdsnd_github | /bikeshare.py | 7,437 | 4.03125 | 4 | import time as t
import numpy as np
import pandas as pd
CITY_DATA = { 'chicago': 'chicago.csv',
'nyc': 'new_york_city.csv',
'washington': 'washington.csv' }
def get_filters(city, month, day):
print ('Hello! Let\'s explore major US bikeshare data!')
print ('')
t.sleep(1)
whi... |
fef2bea17ffb60458cf22821fc4503494914b2ea | esselstyn/Homework_1 | /prime.Factor.py | 690 | 3.671875 | 4 | #!/usr/bin/env python
max = int(raw_input('Select the maximum value: '))
max = max + 1
#Make a list of all prime numbers between 1 and max
primes = []
for i in range(1, max):
x = 0
if i < 4:
primes.append(i)
else:
for j in range(2, i-1):
if i % j == 0:
x = 1
if x == 0:
primes.append(i)
##reduce th... |
ffd942f4497eb0eee211598e8fbb11c9c0954d8e | nishanthnandakumar/Artificial-Intelligence---Classes | /DepthFirstSearch.py | 4,678 | 3.859375 | 4 | #! /usr/bin/env python
import numpy as np
import time
#Define the start state
start_state = np.array([[1,2,3],[4,5,0],[7,8,6]])
#Define the goal state
goal = np.array([[1,2,3],[4,5,6],[7,8,0]])
#Define predecessor for start_state
base = (np.array([0]*9)).reshape(3,3) #creates a 3x3 array of zeros
#My input to the ... |
ed1c05fe519969bec206b609b99388c8ed1c5d7c | pedrohenriquebraga/Curso-Python | /Mundo 2/Exercícios/ex_042.py | 487 | 4.09375 | 4 | # DIZ QUAL TIPO DE TRIÂNGULO SE FORMARÁ
r1 = float(input("Digite a 1° reta: "))
r2 = float(input("Digite a 2° reta: "))
r3 = float(input("Digite a 3° reta: "))
if r1 + r2 > r3 and r1 + r3 > r2 and r2 + r3 > r1:
print("Essas retas podem FORMAR um triângulo", end=" ")
if r1 == r2 == r3:
print("EQUILÁTER... |
6a5a75a3e3f0d05d0dc4a487ef5f56836b8d40a7 | Sasha2508/Python-Codes | /Others/Date_time_scraper.py | 2,413 | 3.671875 | 4 | # extracting time and date from the below website
# https://www.timeanddate.com/
"""Python Program to Quickly fetch date and time from https://www.timeanddate.com/ and copy it to clipboard"""
from bs4 import BeautifulSoup
import requests
import re
import time
from _datetime import datetime
import pyperclip as pc
def ... |
bb433f82a9722876ebf6656cd9021a1122951e14 | ca-sousa/py-guanabara | /exercicio/ex083.py | 333 | 3.75 | 4 | exp = input('Digite a expressao: ')
lista = []
for simb in exp:
if simb == '(':
lista.append('(')
elif simb == ')':
if len(lista) > 0:
lista.pop()
else:
lista.append(')')
if len(lista) == 0:
print('Sua expressao esta valida!')
else:
print('Sua expressao e... |
e8e659384627ab0094cd3c613309e807c1f4bd53 | liuyiquanGoodCoder/dataStructure | /2.二维数组中的查找.py | 523 | 3.5625 | 4 | class Solution:
def Find(self,target,array):
rows = len(array)
cols = len(array[0])
if rows > 0 and cols > 0:
row = 0
col = cols - 1
while row < rows and col >= 0:
if target == array[row][col]:
return True
... |
00bcb3370287c3a39d2b7e2cd5aeb15bed68a095 | Aasthaengg/IBMdataset | /Python_codes/p02722/s721857909.py | 420 | 3.609375 | 4 | def main():
n = int(input())
count = 2
sqrt = int(n ** (1/2))
for i in range(2,sqrt + 1):
if n % i == 1:
count += 2
elif n % i == 0:
ins = n
while ins % i == 0:
ins = ins // i
if ins % i == 1:
count += 1
... |
f0e85dfb641bcb7822e9d18ac9f555a33869cbb5 | Hehwang/Leetcode-Python | /code/098 Validate Binary Search Tree.py | 968 | 3.9375 | 4 | # Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def __init__(self):
self.flag=True
def helper(self,root,max_num,min_num):
if root.left:
if root.left... |
8286af2a6376ff3340ca8d0d6c82f78bfb42033b | romirmoza/advent-of-code-2019 | /advent-of-code-2019/day1_rocket_equation.py | 579 | 3.984375 | 4 | def calculate_fuel_req(module):
return (module // 3) - 2
def calculate_fuel_req_recursive(module):
req = (module // 3) - 2
if req > 0:
return req + calculate_fuel_req_recursive(req)
return 0
if __name__ == '__main__':
file = open('day1_input.txt', 'r')
modules = list(map(int, file.read... |
aea69a498caab1fe218aa0df397d93e9e5a937d7 | alexanch/Data-Structures-implementation-in-Python | /BST.py | 2,038 | 4.28125 | 4 | """ Binary Search Tree Implementation: search, insert, print methods. """
class Node(object):
def __init__(self, value):
self.value = value
self.left = None
self.right = None
class BST(object):
def __init__(self, root):
self.root = Node(root)
def insert(self, new_val):
... |
a3652f393a0b4f52495d868c041f1b029b3370c7 | Dmarchand97/practicepython-practice | /rockPaper.py | 937 | 3.953125 | 4 | #Rock paper scissors
#Make a two-player Rock-Paper-Scissors game
#Rock beats scissors
#Scissors beats paper
#Paper beats rock
player1 = input("rock, paper, or scissors?... ")
player2 = input("rock, paper, or scissors?... ")
def winner(u1, u2):
if u1 == u2:
return("Its a tie! Try again!")
e... |
1871cfbc1dac1761365d1666bc0436413883caf9 | shinkai-tester/python_beginner | /Lesson10/tree.py | 540 | 3.5625 | 4 | N = int(input())
d = dict()
for i in range(N):
info = input().split()
parent = info[0]
childs = info[1:]
for child in childs:
d[child] = parent
if parent not in d:
d[parent] = None
N = int(input())
for i in range(N):
zapros = input().split()
parent = zapros[0]
child = z... |
695c94bd3e989a63be1202ffedc6dbb8e52ce9ca | pawdon/python_course | /week05_day02/egz_zad3.py | 1,674 | 3.5 | 4 | import tkinter as tk
def run():
main_window = tk.Tk()
main_window.title("Klawisz")
main_window.geometry('700x700')
panel_width = 500
panel_height = 500
label_width = 100
label_height = 25
available_width = panel_width - label_width
available_height = panel_height - label_height
... |
cb2b5d569fadd2f4cf207a0067e18d3a216aca8d | pillowfication/ECS-32B | /Homework6/hw6_tools.py | 6,325 | 3.8125 | 4 |
#### Functions and classes to help with Homework 6
#### You should not make any changes to the functions and classes in this file,
#### but you should understand what they do and how they work.
import sys
### This function will be re-defined in hw6.py. However, it is needed for ExpTree,
### so it is redefin... |
9b358371cc16a6c33a925269a6858e35db8475b5 | raffivar/NextPy | /unit_3/blog.py | 3,583 | 3.65625 | 4 | import string
class UsernameTooShort(Exception):
def __init__(self, username):
self._username = username
def __str__(self):
return "Username too short."
class UsernameContainsIllegalCharacter(Exception):
def __init__(self, username):
self._username = username
def __str__(se... |
08d8388793de65be7842ec1a6c5dd8274de3c033 | gowthamgoli/Leetcode | /contains_duplicate_217.py | 153 | 3.71875 | 4 | def containsDuplicate(nums):
num_map = {}
for num in nums:
if num in num_map: return True
else: num_map[num] = 1
return False |
6cd18013674944cba983235dd590bacc5fc1e726 | Bellroute/algorithm | /python/book_python_algorithm_interview/ch14/balanced_binary_tree.py | 1,269 | 3.859375 | 4 | # 리트코드 110. Balanced Binary Tree
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
class Solution:
# 내 풀이
def isBalanced_mySolution(self, root: TreeNode) -> bool:
def get_height(root):
if not ro... |
c3b8f9c060b465cf9534dd219f206cb551c3ff4a | gwahak/Pygame | /Lesson07/GomokuClient/ChessboardClient.py | 2,186 | 3.5625 | 4 | import pygame
from Lesson07.Chessboard import Chessboard
class ChessboardClient(Chessboard):
def __init__(self):
super().__init__()
self.grid_size = 26
self.start_x, self.start_y = 30, 50
self.edge_size = self.grid_size / 2
def is_in_area(self, x, y):
return self.st... |
5995d1228a9708410a822c5d17c6508f5b8c0de1 | callrua/spotipyutils | /src/genre_to_playlist.py | 3,174 | 3.546875 | 4 | """This script generates a spotify playlist of up to 100 songs based on given genres"""
import argparse
import spotipy
import spotipy.util as util
import os
import datetime
from pprint import pprint
import sys
parser = argparse.ArgumentParser(description='Args')
parser.add_argument('--genres', '-g', dest='genres', req... |
d7c0b8eb61709701ecd31442aed1043934caca1e | b-franka/after-advanced-algorithms | /python/binary_search.py | 532 | 3.90625 | 4 | import math
def search(num, array):
lowerIndex = 0
higherIndex = len(array) - 1
while lowerIndex <= higherIndex:
med = math.floor((lowerIndex + higherIndex) / 2)
pivot = array[med]
if pivot == num:
return med
elif num < pivot:
higherIndex = med-1
... |
cc65a22ca924be9ff56650d485514e527970a3ff | mooksys/Python_Algorithms | /Chapter27/file_27_4c.py | 150 | 3.59375 | 4 | s = "I have a dream"
letter = input("검색할 영문자를 입력하여라: ")
if letter in s:
print("문자", letter, "를 찾았습니다.")
|
f56d40127957476bfba201659b8d491cefb518aa | khangtran123/Yaml_to_JSON_Converter | /Dictionary_Orion.py | 3,960 | 3.546875 | 4 | #!/usr/bin/python3
'''
Author: Khang Tran
Date: September 4, 2020
Parameters:
yamlFile: Please replace current param with the actual location of yaml file
jsonFile: Please replace current location of where the json file is stored
What I want to do is create a for loop that iterates t... |
4e9be8c38712a92dba7971af7614bbe171573a41 | rafaelrbnet/curso-completo-de-python | /Aulas/02-Estruturas de Decisão/laco3.py | 362 | 3.796875 | 4 | servidores = ["dns", "database", "webserver", "voip", "mongodb"]
# O comando continue é usado para trabalhar com exeção de uma lista.
for s in servidores:
if s == "webserver":
print("O servidor {} não pode estar na lista".format(s))
break
else:
print("Todos os servidores estão atualizad... |
de6325423e09e5e27e063e8e7d4fb9ce66315afe | farahzuot/data-structures-and-algorithms-python | /data_structures_and_algorithms/challenges/tree/tree.py | 4,540 | 3.796875 | 4 | class Node:
def __init__(self,value):
self.value = value
self.next = None
class Queue:
def __init__(self):
self.front = None
self.rear = None
def enqueue(self,data): # 1 -> 2 -> none
node = Node(data)
if self.front == None:
self.front = node # 1 ... |
13943bc0b69d29a1ec34733febc67ad7f01d45e9 | sipspatidar/whatsapp_data_extractor | /remove_duplicate_and_sort.py | 436 | 3.703125 | 4 | import os
def list_Remove_Duplicates(x):
return sorted(set(x))
def Main():
os.chdir("links")
inputfn = input("enter the file name without extension : ")
po = open(inputfn+".txt","r")
line = "esf"
link = []
while(line!=""):
line = po.readline()
link.append(line)
result = sorted(set(link))
... |
f586b6e358a7ecc0219539285af09a4ac3d0ff33 | safkat33/Python-Sorting | /ProblemSolve/TwoSums.py | 1,033 | 3.953125 | 4 | from typing import List
"""
Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target.
You may assume that each input would have exactly one solution, and you may not use the same element twice.
You can return the answer in any order.
"""
class Solution... |
d2b28cdd593f3a421083bc94fcec41723fe43279 | JohannesBuchner/pystrict3 | /tests/expect-fail23/recipe-576783.py | 2,694 | 3.71875 | 4 | # State Capitals Game
import random
def main():
state_capitals={"Washington":"Olympia","Oregon":"Salem",\
"California":"Sacramento","Ohio":"Columbus",\
"Nebraska":"Lincoln","Colorado":"Denver",\
"Michigan":"Lansing","Massachusetts":"Boston",\
... |
e34c7a67ba5d39975e24df84d1dd069cf9cd4a91 | ElenaVasyltseva/Beetroot-Homework | /lesson_6/task_1.py | 1,003 | 3.984375 | 4 | # Task 1
# Make a program that has some sentence (a string) on input
# and returns a dict containing all unique words as keys
# and the number of occurrences as values.
while True:
user_text = input('Please, enter a text:').replace(',', ' ').replace('.', ' ').replace('!', ' ').replace('?', ' ')
us... |
62d919185d19df039cc4f67b2f1f8a747fc77e14 | sunnyyeti/Leetcode-solutions | /56 Merge Intervals.py | 1,092 | 3.890625 | 4 | # Given an array of intervals where intervals[i] = [starti, endi], merge all overlapping intervals, and return an array of the non-overlapping intervals that cover all the intervals in the input.
# Example 1:
# Input: intervals = [[1,3],[2,6],[8,10],[15,18]]
# Output: [[1,6],[8,10],[15,18]]
# Explanation: Since in... |
726dfec7abfdab70fba752b76ca6823fdc3c1757 | Surapee/batavia | /testserver/code.py | 314 | 4.09375 | 4 |
class Point:
def __init__(self, firstPoint, secondPoint):
self.firstPoint = firstPoint
self.secondPoint = secondPoint
def distance(self):
return self.firstPoint ** self.firstPoint + self.secondPoint ** self.secondPoint
point = Point(2, 3)
print('Distance is', point.distance())
|
294c9db3d1b02af3e5ef9e9a5d6390ab24a64781 | Vanshika-RJIT/python-programs | /perfect square number.py | 120 | 3.65625 | 4 | import math
for i in range(1,501):
x=math.sqrt(i)
if(x==math.floor(x)):
print(i,end=' ')
|
e2f62108ce61c0d4a7b4c0b2372fbf88b92096ef | mohibul2000/MY_PROJECTS | /assignments.py/Q10.py | 151 | 4.3125 | 4 | # Tuples
"""
10. Write a Python program to reverse all the elements in a tuple without using the tuple
function.
"""
tp=(1,2,3,4)
print(tp[::-1]) |
4c51784ada56ce32ed511c64c36236b60f77a6a5 | NSLeung/Educational-Programs | /Python Scripts/test_script.py | 136 | 3.625 | 4 | import numpy as np
# print(np.exp(2))
x = [1, 2, 3, 4, 5, 6, 7]
y = np.zeros(2*len(x) - 1)
print("hello", x)
y[::2] = x
print(y)
|
682dc7e3b6a8782908224cd6968fa8bf48534b89 | AbdulkarimF/Python | /Day13.py | 842 | 4.59375 | 5 | # Python Lists
# create a List
print('Example 1')
s = []
print(s)
print('Example 2')
Numbers = [1, 2, 3, 4, 5]
print(Numbers)
print('Example 3')
thislist = ['apple', 'banana', 'cherry']
print(thislist)
print('Example 4')
thislist = ['apple', 'banana', 'cherry', 1, 2, 3]
print(thislist)
# Access Items
pri... |
73a72cd68be817536ada156e1070f3fe3dfdf890 | AlphaGarden/LeetCodeProblems | /Easy/121_Best_Time_To_Buy_and_Sell_Stock.py | 1,034 | 3.890625 | 4 | """
Say you have an array for which the ith element is the price of a given stock on day i.
If you were only permitted to complete at most one transaction (ie, buy one and sell one share of the stock), design an algorithm to find the maximum profit.
Example 1:
Input: [7, 1, 5, 3, 6, 4]
Output: 5
max. difference = 6-... |
78da8486dfa4e992c6f90b2c501c47aab40bf22d | rupesh7399/rupesh | /Rupesh/python/continue.py | 234 | 4.125 | 4 | while True:
n = int(input("Please enter an Integer: "))
if n < 0:
continue # this will take the execution back to the starting of the loop
elif n == 0:
break
print("Square is ", n ** 2)
print("Goodbye") |
9bdeb46faf365b5f60527029029b5cc90fa761f8 | rafaelperazzo/programacao-web | /moodledata/vpl_data/51/usersdata/128/19883/submittedfiles/listas.py | 446 | 3.765625 | 4 | # -*- coding: utf-8 -*-
from __future__ import division
def maiorDegrau(l):
maiorD=0
for i in range(0,(len(l)-1),1):
degrau=l[i]-l[i+1]
if degrau<0:
degrau=degrau*(-1)
if degrau>maiorD:
maiorD=degrau
return maiorD
n=input('Qua... |
8d4d046b5e48a5fffac4fd596b063b9942a29259 | tathagata218/All-Projects | /Algorithms/Selection Sort/sort.py | 300 | 3.6875 | 4 | a = [6,43,32,1,23,4,8,7]
def selectionSort (a):
for i in range(0,len(a)):
testValue = a[i]
for x in range(i+1,len(a)):
if(testValue > a[x]):
testValue = a[x]
a[x] = a[i]
a[i] = testValue
print(a)
selectionSort(a) |
e3d64ad8c6ef798f5b08068d200ca708b3d1d36d | Raiugami/Exercicios_Python-n2 | /exe065.py | 539 | 3.9375 | 4 | cont = media = maior = menor = 0
resp = 'S'
while resp == 'S':
num = int(input("Informe um numero: "))
media = media + num
cont += 1
if cont == 1:
menor = maior = num
else:
if num > maior:
maior = num
if num < menor:
menor = num
resp =... |
f727ee2d5e1894a22cfc8cef79514faf19aacbcf | duochen/Python-Beginner | /Lecture05/Labs/user.py | 1,041 | 3.828125 | 4 | class User:
def __init__(self, first_name, last_name):
self.first_name = first_name
self.last_name = last_name
def describe_user(self):
print(self.first_name, self.last_name)
def greet_user(self):
print("Hello " + self.first_name + "," + self.last_name)
use... |
db193f6cb88fe7a741fc6ea574d799076f2d0bf1 | LeeSangYooon/Gomoku_AI | /game/Game.py | 1,583 | 3.609375 | 4 | from game.Board import Board
class Game:
def __init__(self):
self.board = Board()
self.turn = 1
self.result = 0
def move(self, pos):
self.board.board[pos[1]][pos[0]] = self.turn
self.result = self.get_result(pos)
self.turn = 3 - self.turn
def get_result(sel... |
1a2ac4656d8e27d5f1f6ab802a18257ab1347737 | Tuhgtuhgtuhg/PythonLabs | /lab05/lab5_1.py | 1,601 | 4.03125 | 4 | class Book:
def __init__(self, name = " ", year = 0, genre = " "):
if name != " " and 0<year<=2021 and genre != " ":
self.name = name
self.genre = genre
self.year = year
else:
print("Помилка додавання книги!")
class Lib:
def __init__(self):
... |
641e13220384ed9502d098559c8a90fed267d7e0 | Lucas-Guimaraes/Reddit-Daily-Programmer | /Easy Problems/21-30/21easy.py | 361 | 4.15625 | 4 | #https://www.reddit.com/r/dailyprogrammer/comments/qp3ub/392012_challenge_21_easy/
def higher_num(num):
count = num+1
while True:
if str(num) in str(count):
False
return count
else:
count = count+1
num_test = int(raw_input("Put in a number!: "))
... |
cf374ba41e7638727c8762e294e0210ea2af87b2 | Skylow369/Matrix-Operations | /MatrixClass.py | 5,415 | 3.765625 | 4 | import copy
import random
class Matrix:
def __init__(self, matrix=None, numrows=0, numcols=0):
self.numrows = numrows
self.numcols = numcols
self.rows = []
self.columns = []
self.setvals(matrix)
def printmatrix(self):
print("Matrix:")
for ... |
8ea103c88ebfdc8947a8236fa1f00c86341c385e | sukmin-ddabong/megait_python_20201020 | /03_loop/quiz02/quiz02_3.py | 237 | 3.703125 | 4 | for i in range(1, 51): # 1 ~ 50, 1씩 증가
if i % 3 == 0: # i를 3으로 나누어 떨어지면 3의 배수
print(i, end=" ")
# 다른 방법
for i in range(3, 51, 3): # 3 ~ 50, 3씩 증가
print(i, end=" ")
|
96e8e30db9b28b4da52b771030578e3c0fae4f43 | jparng/Guess_Num | /GuessNum.py | 365 | 4.0625 | 4 | import random
x = random.randrange(1,20)
y = int(input('Choose a number between 1 and 20 '))
while y != x:
if y > x:
print('Too high. Try again')
y = int(input('Choose a number between 1 and 20 '))
else:
print('Too low. Try again.')
y = int(input('Choose a number between 1 and... |
9d39e2403c8f08b561a0665eed2e64767d822b94 | pravinmaske/TorontoPython | /indices_over_two_objects.py | 842 | 3.90625 | 4 | def count_matches(s1,s2):
"""
Return the number of positions in s1 that contains the same character
at the corresponding position of s2.
Precondition: len(s1) == len(s2)
>>>count_matches('ate','ape')
2
>>>count_matches('head','hard')
2
"""
count_match=0
for i in range(len(s1)):
if s1[i] == s2[i]:
coun... |
3b0ab4a6cdf808cb9661b728581e4593b4503673 | ValentynaGorbachenko/cd2 | /ltcd/moveZeroes.py | 604 | 4.09375 | 4 | '''
Given an array nums, write a function to move all 0's to the end of it while maintaining the relative order of the non-zero elements.
Example:
Input: [0,1,0,3,12]
Output: [1,3,12,0,0]
Note:
You must do this in-place without making a copy of the array.
Minimize the total number of operations.
'''
def moveZeroes(... |
577767a7554a67aeb99dcec9cfbe577a506ed9b6 | parag2005/acadgild_Hyd_Assignments | /Python Assignment/Problem_Statement1_Python2_5_2.py | 913 | 3.734375 | 4 | from pip._vendor.distlib.compat import raw_input
subjects_of_sentence = raw_input('Please enter a set of words to define the subject words ? ')
""" The first set of words includes ["American","Indians"] """
verbs_of_sentence = raw_input('Please enter a set of words to define the verb words ? ')
""" The second set o... |
88002c182c9e8adea863cc44bf816dba504241ab | supermavster/Platzi-Master-Python | /2-basics/25-listComprehension.py | 1,264 | 4.09375 | 4 | # Secuencia existente en una nueva existencia
# Dictionary comprehension - list comprehension
# Dictionary comprehension y list comprehension nos permite
# escribir listas o diccionarios de forma más sencilla.
## LISTAS
# Números pares
pares = []
for num in range(1,31):
if num % 2 == 0:
pare... |
e71baf43131650cd2eed7a9087eab5ba1061d15a | evamwangi/Andela_bootcamp_vii | /day_3/args_kwargs.py | 1,055 | 4.09375 | 4 | #unpacking
def hallo(name, age, class_=""):
"""
explanation on what it does
"""
if class_ != "":
return "i am {}, and i am {}, and {} class".format(name, age, class_)
return "i am {}, and i am {}".format(name,age)
people = [
("jane",23,'high'),
("joe" , 25,'low'),
("brian", 60),
("betty", 45)
]
''... |
af221caf598132140302174b1bf827cad528f221 | kvswim/kv_jhu_cv | /HW2/ssift_descriptor.py | 750 | 3.625 | 4 | import cv2
import numpy
import matplotlib.pyplot as plt
def ssift_descriptor(feature_coords,image):
"""
DO NOT DO - not required for 461
Computer Vision 600.461/661 Assignment 2
Args:
feature_coords (list of tuples): list of (row,col) tuple feature coordinates from image
image (numpy.nd... |
1cf8c07e53d1d97a0cad05e3a888647df33b5b23 | DrRuisseau/fp_train | /python/lec4/main/Reduce.py | 170 | 3.671875 | 4 | product = 1
x = [1, 2, 3, 4]
for num in x:
product = product * num
from functools import reduce
product = reduce((lambda x, y: x * y),[1, 2, 3, 4])
print(product)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.