blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
09808de9320eb363d10a549d3e22c777a2618e99 | shareef-sanaullah/Batch6_PY_Day12 | /Batch6_PY_Day12.py | 901 | 3.90625 | 4 | #!/usr/bin/env python
# coding: utf-8
# In[1]:
class fruits:
def _init_(self):
print('this is a constructor')
print('this is also prints')
def mango(self):
print('this is in yellow')
def grape(self):
print('this is in green')
# In[2]:
fo... |
7dd9d79bb8de403d21f4db17ffc6c507f627cc65 | villafanezgd/programacion_python | /practica_6.py | 404 | 3.671875 | 4 | #Leer A y B, enteros. Calcular C = A x B mediante sumas sucesivas e imprimir el
#resultado.
valor_A = int(input("Ingrese el valor de A:"))
valor_B = int(input("Ingrese el valor de B:"))
sumas_sucesivas = 0
contador = 0
while (valor_A != contador):
contador = contador + 1
sumas_sucesivas = sumas_sucesivas + va... |
ebb99f919715886e99d9906cd393b77468bb242d | alzbetasrutkova/AiB_projects | /Project4/rfdist.py | 3,084 | 3.96875 | 4 | import sys
from ete3 import Tree
#We are using the ete3 package to work with trees
#The steps in this implementation correspond to the algorithm steps as presented in slides "Tree_comparison.pdf" (23-27)
#function which returns a list of all the node names in a given tree
def get_node_list(t):
node_list =... |
02b119162b52a05bf193290b9499819660b424be | L-xbin2020/PythonStudy | /PythonStudy/Python编程从入门到实践/函数.py | 576 | 3.8125 | 4 | # def make_shirt(size,t_name = "I love Python"):
# print("衬衫的尺码是{},衬衫的上的文字是{}".format(size,t_name))
# pass
#
#
# make_shirt("m",)
#
#
# def city_country(city,country):
# print("{},{}".format(city.title(),country.title()))
# pass
#
#
# city_country("guangzhou","guangdong")
# def make_album(singler,zhua... |
6fdfd96471de5824dd4572b2879719788a052df3 | LYblogs/python | /Python1808/第一阶段/day12-json和异常捕获/04-抛出异常.py | 445 | 4.0625 | 4 | """
抛出异常:主动让程序出现异常
语法:
raise 错误类型 - 程序执行到raise类型语句的时候直接抛出异常
注意:错误类型必须是一个类,并且这个类是exception的子类
"""
# print([1,2,3][2])
# raise IndexError
#练习:输入年龄,如果输入的年龄的范围不在0~100,程序就崩溃
age1= int(input("请输入年龄(0~100):"))
if age1 >100 or age1<0:
raise ValueError |
3217ca88df53c7c68af2dc2321c9b83fe3513d74 | mahimadubey/leetcode-python | /pascals_triangle/solution.py | 958 | 4.0625 | 4 | """
Given numRows, generate the first numRows of Pascal's triangle.
For example, given numRows = 5,
Return
[
[1],
[1,1],
[1,2,1],
[1,3,3,1],
[1,4,6,4,1]
]
"""
class Solution(object):
def generate(self, numRows):
"""
:type numRows: int
:rtype: List[List[int]]
"""
... |
fda625ea7fb5b0602a9a2ad51685484d5c655f26 | silicn/python-test | /people.py | 274 | 3.640625 | 4 | #!/usr/bin/python
# -*- coding: UTF-8 -*-
class People():
sender = ""
def __init__(self,name):
self.name = name
People.sender = "男"
def disPlayName(self):
print self.name
def disPlaySend(self):
print People.sender
|
d5027fd09b5c2688db4ffbb06143c31d67aff056 | super-magnet/start_crawler | /python_learning/test3.py | 1,205 | 3.75 | 4 | def file_view(file_name,line_number):
if line_number.strip() == ':': #字符串strip()函数的作用,删除前后空格,即判断输如为‘:’
begin = '1'
end = '-1'
(begin,end) = line_number.split(':') #字符串split()函数的作用
if begin == '':
begin = '1'
if end == '':
end = '-1'
if begin == '1' and end ==... |
69d5cdc7b45c1cc5f4a2ff5b9e2a77ca57709437 | danmccabe00/CA117 | /lab_072/geometry_072.py | 871 | 3.796875 | 4 | class Point(object):
def __init__(self, x=0, y=0):
self.x = x
self.y = y
def distance(self, other):
return (((self.x - other.x) ** 2) + ((self.y - other.y) ** 2)) ** (1 / 2)
def __str__(self):
return "({}, {})".format(str(float(self.x)), str(float(self.y)))
class Segment(object):
... |
72a6f8d990edba66f4bb24287cf09d92e65a139b | vincentwenxuan/playgroud | /Python_Crash_Course/alien_invasion/alien.py | 2,114 | 3.640625 | 4 | import pygame
from pygame.sprite import Sprite
class Alien(Sprite):
"""docstring for Alien"""
def __init__(self, screen, settings):
super(Alien, self).__init__()
self.screen = screen
self.settings = settings
#Load the alien image
self.image = pygame.image.load('... |
03940a45235518ab322fd96417d672922432db6d | nnugmanovaa/ICT | /task2.py | 3,257 | 3.734375 | 4 | #ex 1
#x1 = int(input())
#y1 = int(input())
#x2 = int(input())
#y2 = int(input())
#if x1 == x2 or y1 == y2:
# print("YES")
#else:
# print("NO")
#ex 2
#x1 = int(input())
#y1 = int(input())
#x2 = int(input())
#y2 = int(input())
#if abs(x1 - x2 == 1) or abs(y1 - y2 == 1):
# print("YES")
#else:
# print("NO")
... |
a57b76fc9d8baf37a7bf4767f960f997ffeb4e86 | Acidcreature/05-Python-Programming | /homeclasswork/classes/petclasstest.py | 486 | 3.96875 | 4 | # tests PetClass
import petclass as pc
def main():
# get info
name = input('enter the name ')
animal_type = input('What type of pet do you have ')
age = input('enter the age ')
# creates instance
pet = pc.PetClass(name, animal_type, age)
# display the data that was entered
print('Her... |
89af48fa572e887873de6c9bf64920bf95ac9958 | StitchSizzler/PythonProjects | /test.py | 2,195 | 3.640625 | 4 |
import random
import webbrowser
def main():
valid = False
while valid == False:
user = input("Enter a number: ")
try:
user = int(user)
valid = True
except:
pass
#webbrowser.open("https://en.wikipedia.org/wiki/Main_Page")
""... |
ec55e0999c7df3315f10c49b316588e8508e0cf4 | dr-dos-ok/Code_Jam_Webscraper | /solutions_python/Problem_203/659.py | 2,238 | 3.546875 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Apr 14 22:36:35 2017
@author: xijiaqi1997
"""
def cake(mat):
ca = mat
for j in range(len(mat[0])):
if all(mat[i][j] == '?' for i in range(len(mat))):
pass
elif all(mat[i][j] != '?' for i in range(len(mat))):
... |
a258062b557e43c399512ec0409e37c3c944a030 | xiao-bo/leetcode | /easy/houseRobber.py | 1,480 | 3.515625 | 4 | class Solution(object):
def rob(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
## recursion method
## time limit exceeded
length = len(nums)
if not nums:
return 0
'''
if length == 1:
return nums... |
d61c5af970bbab0564b6158b9f7c95a14d7987b1 | benjimortal/face_recognition | /first/toturial/dictionaries.py | 389 | 3.953125 | 4 | student = {'name': 'Jawid', 'age': 25, 'courses': ['Math', 'CompSci']}
# print(student)
# print(student['name'])
# print(student.get('phone', 'Not Found'))
# del student['courses']
# print(student)
# print(len(student))
# print(student)
# print(student.keys())
# print(student.values())
# print(student.items())
"""lo... |
ffec00ecffc48f1c907a43d0865b4c77727809b6 | zzy1120716/my-nine-chapter | /ch08/0642-moving-average-from-data-stream.py | 1,015 | 4.03125 | 4 | """
642. Moving Average from Data Stream
给出一串整数流和窗口大小,计算滑动窗口中所有整数的平均值。
样例
MovingAverage m = new MovingAverage(3);
m.next(1) = 1 // 返回 1.00000
m.next(10) = (1 + 10) / 2 // 返回 5.50000
m.next(3) = (1 + 10 + 3) / 3 // 返回 4.66667
m.next(5) = (10 + 3 + 5) / 3 // 返回 6.00000
"""
class MovingAverage:
"""
@param: size: ... |
3e3969758d7d23bfdcb8c128a3e6f705ad043d1b | karanalang/technology | /Code/DataStructures/python/leetcode_graph/FlowerPlantingWithNoAdj_lc1042_1.py | 1,125 | 3.828125 | 4 | from typing import List
from collections import defaultdict
class FlowerPlantingWithNoAdj:
def gardenNoAdj(self, N, paths: List[List[int]]) -> List[int]:
ans = [0 for i in range(N)]
print(" Number of Gardens is ", N, " ans -> ", ans)
graph = defaultdict(list)
for u, v in paths:... |
e64361b2728771103f89415a47453264aaf44ee3 | finianoneill/python-challenge | /PyPoll/main.py | 2,418 | 3.71875 | 4 | # module declarations
import os
import csv
# Path to collect data from the Resources folder
election_data_csv = os.path.join('Resources', 'election_data.csv')
# create function that will check list for value
def check_list(checked_list, checked_value):
final_truth = False
for element in checked_list:
if element[0... |
f85f89d07de9f394d7f95646c0a490232bc3b7bc | whoismaruf/usermanager | /app.py | 2,605 | 4.15625 | 4 | from scripts.user import User
print('\nWelcome to user management CLI application')
user_list = {}
def create_account():
name = input('\nSay your name: ')
while True:
email = input('\nEnter email: ')
if '@' in email:
temp = [i for i in email[email.find('@'):]]
if... |
369e6dcf2cea0f43795f89fb48923f2828c68d11 | ronaldaoH/scraper-llegamos-a-tu-casa | /scraper-llegamosatucasa.py | 1,969 | 3.5625 | 4 | import requests
from bs4 import BeautifulSoup
from lxml import html, etree
def scrapear():
page = requests.get("https://llegamosatucasa.com/list/lima")
tree = html.fromstring(page.content)
empresas = tree.xpath("//li[contains(@class,'w-full')]")[0]
#NOMBRE
print("NOMBRE")
titulos = empresas.xpath("//h3[contains... |
0322c4c5699cb6b94e57467a2b2fe9ed12a4ac7a | anilized/HackerRank-ProblemSolving | /picking-numbers.py | 511 | 3.640625 | 4 | #
# Complete the 'pickingNumbers' function below.
#
# The function is expected to return an INTEGER.
# The function accepts INTEGER_ARRAY a as parameter.
#
def pickingNumbers(a):
# Write your code here
a.sort()
b=[]
for i in range(len(a)-1):
l=[]
for j in range(i+1,len(a)):
... |
110259fe449a9bfff934a4e41b68054d01c312fb | wulinlw/leetcode_cn | /中级算法/backtracking_5.py | 2,190 | 3.890625 | 4 | #!/usr/bin/python
#coding:utf-8
# https://leetcode-cn.com/explore/interview/card/top-interview-questions-medium/49/backtracking/95/
# 单词搜索
# 给定一个二维网格和一个单词,找出该单词是否存在于网格中。
# 单词必须按照字母顺序,通过相邻的单元格内的字母构成,其中“相邻”单元格是那些水平相邻或垂直相邻的单元格。同一个单元格内的字母不允许被重复使用。
# 示例:
# board =
# [
# ['A','B','C','E'],
# ['S','F','C','S'],
# ['... |
3880f248f6b66da1e403f08f7c71ebcb7a834c23 | DhananjayNarayan/Programming-in-Python | /General Python Programs/MPHtoMPS.py | 249 | 4.3125 | 4 | print("MPH to MPS Conversion App")
mph = float(input("\nWhat is the speed in miles per hour: "))
#Convert to mph to mps. Where 1mph= 0.4474 mps
mps = mph*0.4474
mps = round(mps, 2)
print("Your speed in meters per second is " + str(mps) + ".")
|
06bc0a1752d14297e1ec09b536c351930a2492f8 | mhernandez2/Python | /añomayor.py | 211 | 3.796875 | 4 | x=int(raw_input("primera edad "))
y=int(raw_input("segunda edad "))
if x==y :
print "ambos de la misma edad"
else:
if x>y :
print str(x)+" es mayor que "+str(y)
else:
print str(y)+" es mayor que "+str(x)
|
25e7e28261a9962f150dafa8ec73a9b9412d046e | rever4433/LearnPythonExample | /src/ex22.py | 913 | 3.765625 | 4 | print("Let's practice everything.")
print('You \'d need to know \' about escapes with \\ that do \n newlines and \t tabs.')
poem="""
\tThe lovely world
with logic so firmly planted
cannot discern \n the needs of love
nor comprehend passion from intuition
and requires an explanation
\n\t\t where there is none.
"""
pr... |
9f48c0f44734fdc842b35399c9844f124167cb20 | yanivn2000/Python | /Syntax/module2/21_stringFunctions.py | 235 | 4.5625 | 5 | # ***** replacing function ****** #
str="abVca"
str=str.replace("a", "A")
print(f"replace a with A= {str}")
# ***** more functions ****** #
str=str.upper()
print(f"after upper: {str}")
str=str.lower()
print(f"after lower: {str}")
|
db9f0c999139ff68893108820949e94f17741dde | cristianpl1996/Computacion-Blanda | /Python/Sistema Informacion de Velocidad/Software/CFLogicFuzzy/ReglasDifusas.py | 668 | 3.890625 | 4 | # -*- coding: utf-8 *-*
"""
Crea las reglas difusas siguiendo el siguiente formato:
"if Conjunto is VariableLinguistica and Conjunto is VariableLinguistica then Conjunto is VariableLinguistica"
Este formato debe ser respetado para que pueda ser procesado y desfuzificado.
-El "Conjunto" es el nombre ... |
cb2c32f062bb3cc51e0d91d709bf5dc5956451a8 | ashjune8/Python-Algorithm-Solutions | /Stacks and Queues/Valid Parenthesis.py | 801 | 3.890625 | 4 | def isValid(s):
"""
:type s: str
:rtype: bool
"""
stack = []
i = 0
if len(s) == 1 or len(s) == 0 or len(s)%2 !=0:
return False
temp = ''
while i<len(s):
if s[i] in ['(','{','[']:
stack.append(s[i])
i += 1
continue
if s[i] ... |
ab66cf33e966af72e04fe109268b3fc04ba15549 | WorasitSangjan/afs505_u1 | /assignment3/ex20.py | 1,154 | 4.21875 | 4 | # Import 'sys' library and call 'argv' function
from sys import argv
# Set the argument for 'argv'
script, input_file = argv
# Create the reading file function
def print_all(f):
print(f.read())
# Create the setting current function
def rewind(f):
f.seek(0)
# Create displaying function (show at specific line... |
f2f2615e9e234b92e916c32f4ce2b9b8ce87ae45 | henrylin2008/Coding_Problems | /Coding Patterns/Two Pointers/Comparing Strings containing Backspaces.py | 3,081 | 4.40625 | 4 | # Problem Challenge 2: Comparing Strings containing Backspaces (medium)
# https://designgurus.org/path-player?courseid=grokking-the-coding-interview&unit=grokking-the-coding-interview_1628743506829_10Unit
# Problem Statement
#
# Given two strings containing backspaces (identified by the character ‘#’), check if the tw... |
d8e710a968b5174a170ca0b4b30beae435757146 | isutare412/python-cookbook | /03_Numbers,_Dates,_and_Times/01_rounding_numerical_values.py | 324 | 3.625 | 4 | print(round(1.23, 1))
print(round(1.27, 1))
print(round(-1.27, 1))
print(round(1.25461, 3))
print(round(1627731, -1))
print(round(1627731, -2))
print(round(1627731, -3))
a = 2.1
b = 4.2
c = a + b
print(c)
c = round(a + b, 2) # DON'T DO THIS
# If you need accurate calcutions, use decimal module (next section)
print... |
515b4ee802d23d18327b6b21181eac49908ffee8 | prashuym/IKPrograms | /Sort-Test1-DutchFlag.py | 872 | 4.21875 | 4 | def dutch_flag_sort(balls):
lenBalls = len(balls)
# Green Flag is used as the iterator to move in one direction
# Red Flag and BlueFlag are used to indicate the position where the next Red or Blue element should go.
RedF = GreenF = 0
BlueF = lenBalls - 1
while (GreenF <= BlueF) :
# ... |
0f2cdf619007797a764333febafb1f2f993b6422 | Jammy2211/autogalaxy_workspace | /scripts/howtogalaxy/chapter_3_search_chaining/tutorial_1_search_chaining.py | 10,805 | 4 | 4 | """
Tutorial 1: Search Chaining
===========================
In chapter 2, we learnt how to perform modeling using a non-linear search. In all of the tutorials, we fitted the
data using just one non-linear search. In this chapter, we introduce a technique called 'non-linear search chaining',
which fits a model us... |
00e04d006bb772244f8358422a993e30e435c517 | SuperFola/swb | /swb/encode.py | 465 | 3.703125 | 4 | #!/usr/bin/env python3
# coding: utf-8
def encode(text):
bits = list(bin(ord(c))[2:].zfill(8) for c in text)
if len(bits) % 2 == 1:
bits.append(''.zfill(8))
out = []
for i in range(len(bits) // 2):
a, b = bits[2 * i], bits[2 * i + 1]
c, d = "", ""
for i in range(4):
... |
f556971d5a50fb4ad4385f20a525ba56245a0348 | patilsangram/Python-Practice | /Python/while2_2.py | 138 | 3.796875 | 4 | count=1
a=input("Enter no for table :")
while(count<11):
c=count*a
count=count+1
print c
raw_input("Table complte ")
|
160194a612ac841019397c75904c50d7606f35eb | JarkkoCareeria/GitGuide | /Opas.py | 376 | 3.75 | 4 | print("Tämä on opas Gitin versionhallintaan")
opas=input("Auttaako tämä opas sinua Gitin hallinnassa?: ")
if opas=="yes":
print("Hyvä, niin ajattelinkin")
print("Sinä hyvä oppilas, minä hyvä opettaja..")
else:
opettele=input("Haluatko opetella lisää? ")
if opettele=="yes":
print("Tutki sitten Y... |
e5677d4ea5fe4fd91fa9a91c8e20102e396d1ddd | edwingilangpratama97/Learning-Python-Beginner | /18-list.py | 115 | 4.03125 | 4 | names = ["Dada", "Didi", "Dudu", "Dede", "Dodo"]
print(names[1:3])
for item in names:
print(f"Nama : {item}") |
3867dcf17ec832affc33387422d382fa0f6fdaa7 | iamyuqi/LeetCode | /Algorithms/007_reverse_integer.py | 658 | 4.125 | 4 | # 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 could only store integers within the 32-bit signed integer range: [−231, 2... |
a599103ab5fcdec6c10a030a9aa20585fdd53473 | opethe1st/CompetitiveProgramming | /CodeChef/2020/09/chef_and_swap.py | 2,331 | 3.875 | 4 | """
Link to (question)[https://www.codechef.com/SEPT20B/problems/CHFNSWAP]
To solve this, I did the maths and came up with a way of generating
candidates. The key equation was
n*(n+1)/2 = 2(k(k+1)/2 + d)
The idea behind this equation is to imagine we split the sequence into two
parts and then swap two numbers in ... |
4f6002c6fe70ce26a74e6779c1144984724653ba | spreadmesh/fastcampus_wps2 | /DAY_12/homework.py | 1,082 | 3.859375 | 4 | # 3. calendar과제
def is_leap_year(year):
return True if year % 4 == 0 and year % 100 != 0 or year % 400 == 0 else False
def get_calendar(year, month):
default_year = 1900
totalday = [0, 31, 28+is_leap_year(year), 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
what_day_is_it = ["일", "월", "화", "수", "목... |
82d195d24e47f5097423a30043722fb124efb383 | kcollett1/Stanford_Algorithms | /course4/week2/graph.py | 9,671 | 3.78125 | 4 |
''' this is my implementation of a WEIGHTED UNDIRECTED complete graph as an adjacency list. '''
from itertools import combinations as comb
class Graph:
def __init__(self):
# set of vertices
self.vertices = set()
# dict of edges, mapped to its weight
self.edges = {}
self... |
4a7e614fbb15d36b90592c2f48ea873a7444f1d5 | CodeGuardianAngel96/OOPS-I-Posted | /MobileClass.py | 641 | 3.9375 | 4 | '''
Write a class with name Mobile.
It contains a method called hi() which contains two
parameters msg and app which is initialized to None.
If no parameter is sent then hi() should print hai ,
if a parameter is sent then it should print hai and the parameter also.
'''
class Mobile:
def hi(... |
6ca282a4daa9c081504728187a0f13899b8e0f47 | aharshbe/python_wp | /wp_f.py | 1,677 | 3.859375 | 4 | #this function writes a file from scratch
#import date and time
import datetime
#import os to remove file
import os
def get_multiline_input():
lines = []
while (1):
line = input()
if line:
lines.append(line)
else:
s = input("Save file? (y/n)")
if (s ... |
d3ae5bc5623edeb62a9d77d9b482cfc586f7a777 | GSichelero/Harvard-CS50 | /pset6/readability/readability.py | 579 | 3.765625 | 4 | def main():
text = input("Text: ")
letters = sum(c.isalpha() for c in text)
words = text.count(" ") + 1
sentences = text.count("?") + text.count(".") + text.count("!")
letters_per_100_word = letters / (words / 100)
sentences_per_100_word = sentences / (words / 100)
index = (0.0588 * lette... |
efe03a8a855b647dfbef9c6f6fa0f5a84db7bd73 | szwxj/algorithm014-algorithm014 | /Week_04/860.py | 577 | 3.53125 | 4 | from typing import List
class Solution:
def lemonadeChange(self, bills: List[int]) -> bool:
s5 = s10 = 0
for k in bills:
if k == 5 :
s5 += 1
elif k == 10 :
s10 += 1
s5 -= 1
elif k == 20 :
if s10 >0 ... |
bfdc4c886ad41ac166d10ac682ef434ad45e858d | YanzhongHuang/Strathclyde_CS547_Advanced_Topic_In_Software_Engineering | /GA.py | 5,614 | 3.75 | 4 | # Random moudle
# 随机模块
import random as rd
# The target string
# 目标字符串
TARGET = "Welcome to CS547!"
# Get the length of the target string.
# 计算目标字符串长度
STR_LENGTH = len(TARGET)
# Encode target string in ASCII
# 将目标字符串转换成ASCII编码
ENCODED_TARGET = [ord(TARGET[i]) for i in range(0, STR_LENGTH)]
# Populat... |
42ee85e1a2a87ba63e11c3f8e5c046767ec8de35 | SamCastelain/aoc2017 | /day6/reallocation2/reallocation.py | 958 | 3.859375 | 4 | #!/usr/bin/env python3.6
import argparse
def rebalance(banks):
highest_blocks = -1
highest_index = 0
for index, blocks in enumerate(banks):
if blocks > highest_blocks:
highest_blocks = blocks
highest_index = index
banks[highest_index] = 0
while highest_blocks:
... |
22a46ad5892ec273bf5a45cdb362279e71793dd7 | RichiePalma/CoderRichie | /Quiz 2 Part I.py | 204 | 4.0625 | 4 | print("Lets do some math!")
a = input("The number that will be multiplying itself:")
b = input("What is the power?")
def superpower(a,b):
return(float(a)**float(b))
print("Resultado", superpower(a , b))
|
15cd1c357b201cc6ede1e6be90f2ce64011c3005 | SrdjanUske/PA | /vezba01/zadatak1.py | 232 | 3.59375 | 4 | import sys
DEFAULT_NUM = 5
def sum(N):
if N == 1:
return 1
else:
return N + sum(N - 1)
if len(sys.argv) > 1:
N = int(sys.argv[1])
else:
N = DEFAULT_NUM
print("Suma prvih " + str(N) + " brojeva iznosi: " + str(sum(N)))
|
101fcd99ec51ffd54cdbbefa2e0139c910c83ece | vivek-kr-jsr/Dynamic_Programming | /0-1knap.py | 1,313 | 3.953125 | 4 | #https://practice.geeksforgeeks.org/viewSol.php?subId=8aacaf36e9cfaf4fa35de65429bce4fc&pid=701431&user=vivek29rajput
def knapSack(W,wt,val,n):
K = [[0 for x in range(W + 1)] for x in range(n + 1)]
# Base Condition
for i in range(n+1):
for j in range(W+1):
if i==0 or j==0:
... |
9592d56e881b06561dd0610d02c7460085c36088 | dvalinotti/python-practice-problems | /overlap.py | 515 | 4.03125 | 4 | # Take two lists and write a program that returns a list that contains
# only the elements that are common between the lists (without duplicates).
# Make sure your program works on two lists of different sizes.
def overlap ( x, y ):
dupes = []
l = x
l.extend(y)
for i in range( len( l ) ):
if ... |
8dfb9c84913d55cd76c6e7347f0de5e54d22b4e8 | joonluvschipotle/baekjoon | /2839.py | 662 | 3.703125 | 4 | a = int(input())
digit = int(str(a)[-1])
total = 0
if digit == 5 or digit == 0:
total = a//5
elif digit == 3 or digit == 9:
total += (a-digit)//5
total += digit//3
elif digit == 6 and a < 10:
total += a//3
elif digit == 6 and a > 10:
a -= 16
total += a//5
total += 4
elif digit == 1:
a -... |
bb3b8743ca07a302bdbf9eb73b524a72e7df810b | scientiacoder/ALG | /ALG/290WordPattern.py | 975 | 3.53125 | 4 | # -*- coding:utf-8 -*-
# __author__=''
class Solution(object):
def wordPattern(self, pattern, str):
"""
:type pattern: str
:type str: str
:rtype: bool
"""
if len(pattern) == 0:
if len(str) == 0:
return True
return False
... |
ac4337d5a7448e9dc93bfdaa16dbbed4d181abb2 | superggn/myleetcode | /basic_array/136-single-number-3.py | 261 | 3.5 | 4 | """
位运算:最优!
"""
from typing import List
class Solution:
def singleNumber(self, nums: List[int]) -> int:
if len(nums) <= 0:
return None
res = 0
for i in nums:
res = i ^ res
return res
|
b252e9e757132f867d241c976f1ee545b31e7756 | thanhmaikmt/pjl | /TestBed/src/brain/examples/multiprocessing/multiple_runs_simple.py | 1,902 | 3.984375 | 4 | '''
Example of using Python multiprocessing module to distribute simulations over
multiple processors.
The general procedure for using multiprocessing is to define and run a network
inside a function, and then use multiprocessing.Pool.map to call the function
with multiple parameter values. Note that on Windows,... |
2e60dac847e99b0d2213ce882485e80d74782014 | choroba/perlweeklychallenge-club | /challenge-228/robert-dicicco/python/ch-2.py | 805 | 3.828125 | 4 | #!/usr/bin/env python
# ---------------------------------------
# AUTHOR: Robert DiCicco
# DATE : 2023-08-01
# Challenge 228 Task 2 Empty Array ( Python )
# ---------------------------------------
myints = [[3, 4, 2],[1,2,3]]
for i in myints:
print(f"Input: @int = {i}")
cnt = 0
while len(i) > 0:
... |
ef64adfa6acdcf0057adbb192e74ef62c043fdfa | kiminh/offer_code | /leetcode/最大乘积子串.py | 468 | 3.53125 | 4 | nums = [2, 3, -2, -2, 4, 5]
def func(nums):
gmax = tmin = tmax = nums[0]
print(tmin, tmax)
for i in range(1, len(nums)):
tmpmin = min(nums[i], tmin * nums[i], tmax * nums[i])
tmpmax = max(nums[i], tmin * nums[i], tmax * nums[i])
tmin, tmax = tmpmin, tmpmax
print(tmin, tmax)
... |
e678483e6f57577b53f1a7200f43e1d9d83c8584 | jiangweiguang/leecode | /数组问题/简单/种花问题/canPlaceFlowers.py | 1,540 | 3.765625 | 4 | def canPlaceFlowers(nums,key):
count = 0
for i,j in enumerate(nums):
if j==1:
continue
else:
if len(nums)>=2:
if i == 0:
if nums[i+1] == 0:
count += 1
nums[i] =1
if... |
f1e9c0110d16912e2a33303f85403e3abbedfe74 | mikhail-malygin/Practice_python | /МФТИ/02_turtle/ex4_circle.py | 313 | 4.15625 | 4 | from turtle import *
def main():
circle(10, 30)
def circle(side, number_of_sides):
shape('turtle')
angleFi = 180 * (number_of_sides -2) / number_of_sides
for i in range(number_of_sides):
left(180 - angleFi / 2) if i == 0 else left(180 - angleFi)
forward(side)
main() |
38fe821eb4d9d7b50a1e78901ccf010c5369772d | joeryan/100pythondays2019 | /011/pokerhand.py | 3,737 | 3.59375 | 4 | import collections
from operator import itemgetter
class Card:
SUITS = ('S', 'H', 'C', 'D')
FACE_VALUES = {'2': 1, '3': 2, '4': 3, '5': 4, '6': 5, '7': 6, '8': 7,
'9': 8, '10': 9, 'J': 10, 'Q': 11, 'K': 12, 'A': 13}
def __init__(self, card):
try:
value, suit = card[... |
d19c4f4290bd72d229e27db93b2e78f41a80de64 | Iyolya/week_03__day_3__homework | /modules/calculator_test.py | 441 | 3.796875 | 4 | import unittest
from calculator import *
class TestCalculator(unittest.TestCase):
def test_add(self):
self.assertEqual ("The answer is 4", add(2, 2))
def test_subtract(self):
self.assertEqual ("The answer is 0", subtract(2, 2))
def test_multiply(self):
self.assertEqual ("T... |
829db509325cc5e442d06ae61813246ec885403c | saggarwal98/Practice | /Python/Assignment/4.py | 150 | 4.15625 | 4 | str1=input()
str2=input()
if str1==str2:
print("Both are equal")
elif str2 in str1:
print(str2+" is a substring of "+str1)
else:
print(-1) |
2cd83ba91ea4c1206a4e4a49f2dfa95773c2f404 | Mmnowski/python_misc | /checkio/speech_module.py | 1,785 | 3.9375 | 4 | FIRST_TEN = ["one", "two", "three", "four", "five", "six", "seven",
"eight", "nine"]
SECOND_TEN = ["ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen",
"sixteen", "seventeen", "eighteen", "nineteen"]
OTHER_TENS = ["twenty", "thirty", "forty", "fifty", "sixty", "seventy",
... |
f6af6c3cde13bad83910e45bf4c68612ba1666ce | Jdpa357/holbertonschool-higher_level_programming | /0x0A-python-inheritance/2-is_same_class.py | 253 | 3.59375 | 4 | #!/usr/bin/python3
"""
Defines a method to evaluate if an object is an instance of the specified class
"""
def is_same_class(obj, a_class):
"""Evaluates if the given object is an instance
of the given class"""
return type(obj) is a_class
|
cc5ddf0b4e63d46ae15abbfc76040b7556d9b373 | yjsyyyjszf/covid-dicom | /Metrics_AI.py | 8,520 | 3.796875 | 4 | # Rafael Scherer
# Métricas IA
"""Este Programa com INPUT sendo as classes de uma lista de dados, as predições
pelo modelo de machine learning da classe de cada valor na lista além da probabilidade
predita para a classe definida pelo modelo, retorna a MATRIZ DE CONFUSÃO, as MÉTRICAS derivadas da matriz,
além de Curva R... |
346f06110b63e3e208f36b48910694b1cef0a936 | mendezag/practicas-python | /polimorfismo/ejemplo_basico.py | 1,467 | 4.09375 | 4 | #CREAMOS VARIAS CLASES CON SU METODOS CORRESPONDIENTES
class Personas():
def Desplazamiento(self):
print("Me desplazo con mis piernas")
class Animales_terrestres():
def Desplazamiento(self):
print("Me dezplazo con mis patitas")
class Animales_acuaticos():
def Desplazamiento(self):
print("Me ... |
3be9a37abbee93a84f81fd454f6cff1dc580f28f | helloprogram6/leetcode_Cookbook_python | /Offer/链表06_18_22_24_35_52.py | 5,567 | 3.71875 | 4 | # -*- coding:utf-8 -*-
# @FileName :05_replaceSpace.py
# @Time :2021/2/28 21:12
# @Author :Haozr
from typing import List
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Node:
def __init__(self, x: int, next: 'Node' = None, random: 'Node' = None):
sel... |
24d72e1751c1bc37f2bfd24bc777957d6910e747 | Renugadevi-S/python3 | /84_no_of_occurance.py | 131 | 4.03125 | 4 | #Python program to count the number occurrence of a specific character in
#a string
str1="renugadevi".count("e")
print(str1)
|
b2ab9ded8cb5e0abe0bffa5c8b367e36de63752d | markopuzav/aoc-2020 | /day03/solution.py | 752 | 3.78125 | 4 | from math import prod
Map = list[str]
def get_input() -> Map:
with open('input.txt', 'r') as f:
return [line.strip() for line in f if line]
def check_slope(area: Map, delta_x: int = 1, delta_y: int = 1) -> int:
m, n, i, j = len(area), len(area[0]), 0, 0
trees = 0
while i < m:
trees +... |
19c795c04790812746a32f6c2eaafd66bd78e202 | cnrmck/static_spines | /old_files/spiney_old.py | 5,378 | 4.0625 | 4 | from math import tau
def convert_fraction(numerator, denominator, desired_denom):
# converts to desired denominator
factor = desired_denom/denominator
numerator *= factor
denominator *= factor
return numerator, denominator
def sum_partial_sum(partial_sum, desired_denom = None):
"""
this fu... |
168a0c484df4111ecb10e411e28dfe91e1399189 | EltonGF/BlueTurma-2B-mod1 | /Exercicios_avaliativo/Ex2.py | 257 | 3.703125 | 4 | cont = 0
frase = input("Olá. Digite uma frase qualquer: ").lower()
vogal = "aeiou"
for i in vogal : #Pesquisar como fazer contagem das vogais na frase.
cont += frase.count(i)
frase = frase.replace(i,"")
print("Vogais na frase:",cont)
print(frase)
|
49a3156772c2e8078fe2e81a0e1c72eb10a4fcdf | j-iNFINITE/Exercise | /PAT/Basic/1045.py | 346 | 3.578125 | 4 | # -*- coding: utf-8 -*-
#测试点1、测试点3 超时
n = input()
rawlist=[int(e) for e in input().split(' ')]
srawlist=sorted(rawlist)
ans=[]
for e in zip(rawlist,srawlist):
A,B=e
if A==B:
pos=rawlist.index(A)+1
if max(rawlist[:pos])==A:
ans.append(A)
print(len(ans))
print(' '.join([str(e) for e i... |
42164aee375322e0a7b924b2f7931e81151ed060 | TakiGuan/LeetCode | /977.squares-of-a-sorted-array.py | 710 | 3.828125 | 4 | '''
Description: Squares of a Sorted Array Solution
Version: 1
Author: Taki Guan
Date: 2020-12-26 16:41:58
LastEditors: Taki Guan
LastEditTime: 2020-12-29 14:53:58
'''
#
# @lc app=leetcode id=977 lang=python3
#
# [977] Squares of a Sorted Array
#
# @lc code=start
from typing import List
class Solution:
def sorte... |
9e1a8ae47dbe3d184e9c901f527e9556b9eeb891 | NathanaelV/CeV-Python | /Exercicios Mundo 1/ex025_procurando_uma_string_dentro_da_outra.py | 377 | 4 | 4 | # Class Challenge 09
# Ler o nome da pessoa e verificar se tem Silva no nome, em qualquer lugar do nome
nome = str(input('Digite seu nome completo: ')).strip()
# Declara str e sempre colocar o strip() para eliminar os espaços do começo e fim
print('Seu nome tem Silva?: {}'.format('silva' in nome.lower()))
# Exemplo... |
189c6f2e39f75d5dc26edfc13da8e48b1c362f4f | pratikpr2/SmartDiscountsML | /itemAnalytics.py | 1,508 | 3.609375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Mon Sep 23 14:45:19 2019
@author: pratprak
"""
import pandas as pd
import numpy as np
import warnings
import matplotlib.pyplot as plt
warnings.filterwarnings('ignore')
FILE_PATH = 'C:\Users\pratprak\Documents\itemData\items.csv'
df = pd.read_csv(FILE_PATH)
print(df.head(5))
pr... |
c26220e85aeb0730109e74435b8b1609d15b2f75 | malcolmabdilla/Battleships | /Battleships_new.py | 3,213 | 3.609375 | 4 | from random import randint
board = []
ships = []
score = 0
win = False
for x in range(0, 10):
board.append(["O"] * 10)
def print_board(board):
for row in board:
print ((" ").join(row))
def generate_coords():
coord = []
row = randint(0,len(board) -1)
col = randint(0,len(board) -1)
c... |
855e43a7418b9e8bcf7b366b8941f5e911384aeb | Korbl/exercism | /python/pangram/pangram.py | 106 | 3.65625 | 4 | def is_pangram(sentence):
import re
return len(set(re.sub('[^a-z]', '', sentence.lower()))) == 26
|
6eb9efacf20127365a3dd4a1c3716f2ea808b893 | lunarknight00/algorithm_challenges | /hacker_rank/ColinearList.py | 1,849 | 3.578125 | 4 | # .if there exist three collinear points in a list of points.
# Definition for a point.
import math
class Point:
def __init__(self, a=0, b=0):
self.x = a
self.y = b
def maxPoints(point):
"""
>>> maxPoints([Point(-1,-1),Point(0,0),Point(1,1)])
1
"""
countPoint = {}
for i in... |
24706a317f6a40c318e9156ad477d3d1ef090f8d | vicchu/leetcode-101 | /04 Recursion/Practice/01_sum_natural_num.py | 250 | 3.625 | 4 |
# With Recursion
def sumNatural(n):
if n <= 0:
return 0
return n + sumNatural(n-1)
# With Formula
def sumNatural2(n):
if n <= 0:
return 0
return int((n * (n+1)) / 2)
print(sumNatural(10))
print(sumNatural2(10))
|
2a69d5744db7d9673769dfc9f779341610ef6261 | fang-ren/algorithm_practice | /Leetcode/medium/74_matrix_search.py | 850 | 3.8125 | 4 | """
author: fangren
"""
# search a target value in a matrix
class Solution(object):
def searchMatrix(self, matrix, target):
"""
:type matrix: List[List[int]]
:type target: int
:rtype: bool
"""
import numpy as np
matrix = np.array(matrix)
matrix = matr... |
a77d967541096e4208c39debe23030b28d3a2f3d | yuancf1024/learn-python-exercise | /2020-01-lxf-python/map_reduce_ex1_str2float_method2.py | 653 | 3.609375 | 4 | # -*- coding: utf-8 -*-
'''方法二
'''
from functools import reduce
DIGITS = {'0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5,
'6': 6, '7': 7, '8': 8, '9': 9, '.': '.'}
def str2float(s):
def f1(s):
return DIGITS[s]
for i in range(len(s)):
if s[i]=='.':
s1 = s[:i]
... |
03e7b844081fe9fea0db1255f71db5bbddef73fd | HamplusTech/PythonCodes2021Update | /reverse.py | 360 | 4.15625 | 4 | # A program to print a given string in reserve order
text = input("Please enter any string\n")
text_reverse = [letter for letter in text.split()]
print()
final = "".join(list(reversed(text_reverse[0])))
print(final)
print ("Another Method")
textLength = len(text)
while textLength > 0:
print(text[textLe... |
086f94fa58ede855f62b69ce9800da3eee6a5f44 | jacobhamblin/little-challenges | /lib/unsorted_list.py | 3,687 | 3.671875 | 4 | def kth_smallest(unsorted_list, k):
if k > len(unsorted_list):
return None
if len(unsorted_list) == 1:
return unsorted_list[0]
first_item = unsorted_list[0]
greater = [num for num in unsorted_list if num > first_item]
lesser = [num for num in unsorted_list if num < first_item]
fi... |
10e2aa3ba96a0d8394fa6eeeebd1d1bc6d29c222 | ara32rus/aprol_tg_bot | /app/db_manage/db.py | 1,420 | 3.765625 | 4 | import sqlite3
from typing import Dict, List, Tuple
def db_insert(db: str, table: str, data: dict):
conn = sqlite3.connect(db)
cursor = conn.cursor()
print(type(data))
columns_joined = ", ".join(data.keys())
value_joined = [tuple(data.values())]
placeholders = ", ".join( "?" * len(data.keys())... |
b021925ded433429b82db79e0ea143baca7688b6 | git-is-good/toys | /make_getter_and_setters.py | 1,953 | 3.640625 | 4 | def make_getter_and_setters(special_starts):
'''As a decorator, make getter and setter for a class automatically.
Example:
@make_getter_and_setters("_special_")
class Hashtable(object):
_special_expandRate = None
_special_expandThreshold = None
=> h = Hasht... |
b5a64dfe10648720111ae8bca65464b887facfa9 | xyloguy/cs1410-2017-40-03-examples | /2017-11-06_exceptions/exceptions.py | 509 | 3.796875 | 4 | def add_two(a, b):
try:
return a + b
except TypeError:
try:
return int(a) + int(b)
except ValueError:
return float(a) + float(b)
except ValueError:
return str(a) + str(b)
except Exception:
raise MyCustomException('We could not handle the... |
96291db391075c2f0eb98dc4c81fe24564f662d4 | frances-zhao/ICS207 | /homework/lesson 16/lesson16b_1.py | 1,956 | 4.3125 | 4 | # *****************************************************
#
# Program Author: Frances Zhao
# Completion Date: May 19 2021
# Program Name: lesson16b_1.py
# Description: Write a program which takes a list of names from the user
# prints all elements in the list that start with “P”.
# Modify your program so the user can spe... |
4cf59d4ecc6b517d526a2647d2c8ddbfabb961c4 | Kwpolska/adventofcode | /2017/day12b_all_connections.py | 1,475 | 3.515625 | 4 | #!/usr/bin/env python3
from typing import Dict, List, Set
import attr
with open("input/12.txt") as fh:
file_data = fh.read().strip()
@attr.s(hash=True)
class Program(object):
name: str = attr.ib(str)
connections_str: List[str] = attr.ib(attr.Factory(list), hash=False)
connections: 'List[Program]' = at... |
8e2631903e8d6e41e0f54f0d116d4294f3c41dad | rsavenkov/GitProject | /ematsyk/class_try.py | 535 | 3.796875 | 4 | class Figure:
def __init__(self,color):
self.color = color
def get_color(self):
return self.color
class Rectangle(Figure):
def __init__(self, color, width = 100, heigth = 100):
super().__init__(color)
self.width = width
self.heigth = heigth
def square(self):
... |
672390c711eadf0a4a5d1dc2adaba36c36616250 | programko-kurzy/kurz-python-1 | /3. Hodina/3.3.py | 848 | 3.765625 | 4 | # 3.3 Príklad
# Napíšte for cyklus, ktorý vypíše všetky nepárne čísla od 0 po 10 (veľmi podobne ako v predchádzajúcom príklade)
for i in range(1, 11, 2):
print(i, end=' ')
print()
# 3.3.1 Bonusový príklad
# Vylepšite príklad 3.3 tak, aby užívateľ zadal aj číslo, pokiaľ má program čísla vypisovať. Teda ak užívateľ ... |
595f52beaf8dfbe2ef3b09a8cfd5f3f88f21bbc3 | dhandyjoe/python-dasar | /Casting.py | 391 | 3.734375 | 4 |
# Casting digunakan untuk mengubah tipe data dari variable
"""
-> int() = mengubah tipe data ke integer
-> float() = mengubah tipe data ke float
-> str() = mengubah tipe data ke string
"""
x = int(1)
y = int(2.8)
z = int("3")
print(type(x))
print(type(y))
print(type(z))
a = float(1)
b = float(2.8)
... |
3a3e1a72888767c32cd43a63ff6951ec213daa2f | almirgon/LabP1 | /Unidade-3/ciclo.py | 333 | 3.671875 | 4 | #coding: utf-8
#Crispiniano
#Unidade 3: Ciclo Trig.
angulo = float(raw_input())
if angulo > 360:
angulo = angulo % 360
if 0 < angulo < 90:
print "Quadrante 1"
elif 90 < angulo < 180:
print "Quadrante 2"
elif 180 < angulo < 270:
print "Quadrante 3"
elif 270 < angulo < 360:
print "Quadrante 4"
else:
pri... |
232c9201e274b747ea9e3c4cef35747ffe26b409 | itsmenick212/algorithm-in-leetcode | /lc_problems/37.SudokuSolver.py | 473 | 3.59375 | 4 | class Solution:
def solveSudoku(self, board: List[List[str]]) -> None:
"""
Do not return anything, modify board in-place instead.
"""
if not board or not board[0]:
return
d = self.build_dict(board)
def build_set(self, board):
s = set()
fo... |
d7771e9a2f8b224fbffe835285f224c88c40b5b8 | Ibukun-Badmus/python-chapter-2 | /Question3.23.py | 408 | 4.21875 | 4 | # 2.3 (Fill in the missing code) Replace *** in the following code with a statement that
# will print a message like 'Congratulations! Your grade of 91 earns you an A in this
# course'. Your statement should print the value stored in the variable grade:
grade = 91
if grade >= 90:
print('Congratulati... |
d99e98b8f255a3aad2cf1d9ee3a44f8df0fe341d | ratimir-matana/Diplomski2019 | /indeksiranje_nizova.py | 964 | 3.59375 | 4 | import numpy as np
# generiranje fiksnih vrijednosti brojeva
np.random.seed(0)
# kreiranje jednodimenzionalnog niza a koji se popuni slučajnim brojevima 0 - 10
a = np.random.randint(10, size=8)
# kreiranje dvodimenzionalnog niza b sa 4 retka i 4 stupca koji se popuni brojevima 0 - 10
b = np.random.randint(1... |
80c6fe4036fea32c7f54456749cc23db219d683b | JAGGER99/PythonFiles | /Python Code #3 Age Calculator.py | 142 | 3.6875 | 4 | birth_year = input('Birth year: ');
age = 2019 - int(birth_year); # you have to turn the birth_year (a string) into an integer...
print(age); |
33ea2aa18ecf11e8bd38fa0dff36e0fe33c28f2d | TheAlgorithms/Python | /project_euler/problem_009/sol2.py | 1,131 | 4.125 | 4 | """
Project Euler Problem 9: https://projecteuler.net/problem=9
Special Pythagorean triplet
A Pythagorean triplet is a set of three natural numbers, a < b < c, for which,
a^2 + b^2 = c^2
For example, 3^2 + 4^2 = 9 + 16 = 25 = 5^2.
There exists exactly one Pythagorean triplet for which a + b + c = 1000.
Find th... |
356f49d5e638bb0d6abd354329f84e69e7d6fd59 | poonyapat/c-with-tutorial | /tutorial-07-1.py | 196 | 4.0625 | 4 | number = 10
if number == 10 :
number = 5
if number == 10 :
number = 7
elif number == 5 :
number = 8
else :
number = 9
else :
number = 6
print(number) |
f79f43504f8820301692b0857291d5e4da2177c3 | FerminAMC/metodos-cuantitativos | /Quizz1.py | 4,005 | 3.734375 | 4 | import random
import math
def quizz_1(number_of_days, cars_per_day_probability, cars_per_day, small_car_probability, small_car, medium_car_probability, medium_car, big_car_probability, big_car):
cash_needed = 0
cash_per_day_stack = []
for i in range(number_of_days):
amount_of_cars = random.r... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.