blob_id stringlengths 40 40 | repo_name stringlengths 5 119 | path stringlengths 2 424 | length_bytes int64 36 888k | score float64 3.5 5.22 | int_score int64 4 5 | text stringlengths 27 888k |
|---|---|---|---|---|---|---|
889cbcdf068e31c2d220b9795010d509bf1aac39 | momchilantonov/SoftUni-Programming-Basics-With-Python-April-2020 | /While-Loop/While-Loop-Exercise/04_walking.py | 410 | 4.03125 | 4 | steps_count = 0
goal = 10000
while steps_count < goal:
command = input()
if command == 'Going home':
steps_to_home = int(input())
steps_count += steps_to_home
break
else:
walked_steps = int(command)
steps_count += walked_steps
if steps_count >= goal:
print(f'Goa... |
ac365e0927468c06f3983268e0d6819f3c5ef2f7 | bpham1525/DevNetTest | /TestFile.py | 578 | 3.640625 | 4 | class TestClassA:
def __init__(self):
self.a = 1
self.b = 2
self.c = 3
def testfuncA(self):
d = self.a
e = self.b
return d + e
class TestClassB(TestClassA):
def __init__(self):
TestClassA.__init__(self)
self.d = 4
self.c = 5
def... |
f5d7c06055eda24b80b226570a5e92faeae9d0cd | daniel-reich/ubiquitous-fiesta | /v3iQ4XiW385SrkWKo_5.py | 468 | 3.53125 | 4 |
def check(lst):
for i in range(len(lst)-1):
if lst[i+1] == lst[i]:
return True
return False
def final_result(lst):
while check(lst):
indexes = []
for i in range(len(lst)-1):
char = lst[i]
if char == lst[i+1]:
for y in range(i, len(lst)):
if lst[y] == char:
... |
9e37d2c0d861dde0d828778d54f57d67dcad7864 | jbacon/DataMiningPythonPrograms | /ChaosTheoryPrograms/SimpleBifurcationDiagramQuadraticFunction.py | 3,075 | 3.703125 | 4 | #Josh Bacon
#Gisela
#quadc1.py
import math
import turtle
import sys
#The Quadratic Function
def Q(c, x):
return (x * x + c)
#Creates the Axis for the graph
#horizontal c-axis from -1.75 to 0.25
#vertical x-axis from -3 to 3
def drawAxis(pen):
pen.up()
pen.goto(-0.01, -3)
pen.write(-... |
66b20965db4d1fc9315bd0983d3cb8fed8b06e5b | DidioArbey/MisionTIC2022-Ciclo1-FundamentosDeProgramacion | /clase13/pandas_workshop.py | 3,078 | 3.703125 | 4 | """
* Series: Estructura de una dimensión.
* DataFrame: Estructura de dos dimensiones (tablas).
* Panel: Estructura de tres dimensiones (cubos).
"""
import pandas as pd
import numpy as np
# Series(data=lista, index=indices, dtype=tipo) : Devuelve un objeto de tipo Series
# con los datos de la lista lista, las fila... |
22d8447bb96d97eff0361bf0a2e3c199391538ba | Tiashaadhya005/webdev_django_project | /graph_code.py | 2,599 | 3.796875 | 4 | class Graph:
def __init__(self):
self.vertices=31
self.graph=[[],
[2,9,14,21,28],[3],[20],[5],[6],[18],[8],[],
[10,22],[11,24],[12],[13,30],[],
[15],[20],[17],[18],[7,30],[],
[16,4],[9],[23],[10],[25],[26,29],[27],[],
... |
5f7db8a4f2e54c5e44fc188e352783581774058e | fyp858585/codewars | /codewars_code/codewars67.IntegersRecreation One.5kyu.py | 380 | 3.5625 | 4 | def list_squared(m,n):
answer = []
for i in range(m,n+1):
li = []
for j in range(1,i+1):
if i % j ==0:
li.append(i**2)
a = sum(li) **0.5
if int(a) == a:
answer.append([int(a),sum(li)])
return answer
if __name__ == '__main__':
r= l... |
7d615b32a108244092a02d71a7d7eee02b50648d | anupjungkarki/IWAcademy-Assignment | /Assignment 1/Function/answer16.py | 276 | 4.3125 | 4 | # Write a Python program to square and cube every number in a given list of integers using Lambda.
nums = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
print(nums)
for_square = list(map(lambda x: x ** 2, nums))
print(for_square)
for_cube = list(map(lambda x: x ** 3, nums))
print(for_cube)
|
29ecd5c97783209197ce8acd8fadd5e26301f0e1 | MattHeffNT/axi-draw-lols | /agents.py | 5,596 | 4.28125 | 4 | """
Write your code to play tic-tac-toe in this file.
Have a look over the example agent `make_first_avaliable_move` before implimenting
your own agent.
"""
# Import the function engine from engine.py
# If you get an error saying you can't find engine, check that engine.py (from the same wattle
# folder as this file... |
53e2d20fa771204e44bba0e403dbb732f61b8bdb | nmasharani/ProjectEuler | /Python/euler4.py | 603 | 4.21875 | 4 | # A palindromic number reads the same both ways. The largest palindrome
# made from the product of two 2-digit numbers is 9009 = 91 99.
# Find the largest palindrome made from the product of two 3-digit numbers.
from sys import exit
def reverseNum(num):
strng = (str(num))[::-1]
#print strng
return int(strng)
l... |
36b74ec36c2edfd32a9106df77c6faec3822e9f1 | AnTznimalz/python_prepro | /Prepro2019/Pizza_number.py | 341 | 3.65625 | 4 | box = set()
def cal(num,wow):
if wow+6 <= num:
box.add(wow+6)
cal(num, wow+6)
if wow+9<=num:
box.add(wow+9)
cal(num, wow+9)
if wow+20<=num:
box.add(wow+20)
cal(num, wow+20)
num = int(input())
if num<6:
print("no")
else:
cal(num,0)
for i in sorted(b... |
af03e1c63da6c5b5eec4c98fa19cb6020a359b1c | reyllama/leetcode | /Python/C47.py | 996 | 3.84375 | 4 | """
47. Permutations II
Given a collection of numbers, nums, that might contain duplicates, return all possible unique permutations in any order.
"""
class Solution(object):
def permuteUnique(self, nums):
"""
:type nums: List[int]
:rtype: List[List[int]]
"""
# idea from @vu... |
829c71d0cc847fda4f1d8d074fbb2ae639de3ba9 | amirjodeiri/Assignment | /list_organize.py | 442 | 4.3125 | 4 | cars = ["bmw", "benz", "audi", "kia", "toyota"]
print(cars)
# sort the list alphabetically permanently
cars.sort()
print(cars)
# sort the list in reverse alphabetical order permanently
cars.sort(reverse=True)
print(cars)
# sort the list in alphabetical order temporarily
print(sorted(cars))
# finding the length of the l... |
14e29f2eacd637a3e663a6d25146957f879715a6 | arpiagar/HackerEarth | /search-insert-position/solution.py | 622 | 3.78125 | 4 | #https://leetcode.com/problems/search-insert-position/solution/
class Solution:
def searchInsert(self, nums: List[int], target: int) -> int:
start = 0
end = len(nums)-1
return self.find_in_array(nums, target, start, end)
def find_in_array(self, nums, target, start, end):
mid ... |
e79ea12fb4c3962ec99b808d7435d39df7092255 | markvilar/pyVO | /utilities.py | 2,139 | 3.515625 | 4 | import numpy as np
import cv2
import csv
from typing import Tuple, List
def visualize_harris_corners(img: np.ndarray, points_and_response: List[Tuple[float, np.ndarray]], radius=4, thickness=2):
"""
Visualizes the rgb image and the Harris corners that are detected in it.
:param img: The image.
:param ... |
327b89d08007d5e18a70b5aae321b16cdc4ec9f7 | logyball/advent_of_code_2020 | /day_2/solver.py | 562 | 3.546875 | 4 | file_input = open("input.txt", "r")
txt = file_input.read().splitlines()
# tup def (low bound, high bound, letter, password)
def check_password(t: tuple):
cnt = 0
for ltr in t[3]:
if ltr == t[2]:
cnt += 1
if t[0] <= cnt <= t[1]:
return True
return False
cnt = 0
for line... |
e1e90abc92102acdc98286e3295f6b19cef12b02 | rubiodamian/syperCrawler | /sypercrawler/lib/linkcheck.py | 651 | 3.875 | 4 | from urllib2 import urlopen, HTTPError, URLError
'''Checks if an url is broken or not and returns the request status code
"response" can be a status code (404,500,200) or,
if the request have a redirection (like 301 or 302),
the url of that redirection'''
def check_url(url):
try:
response = urlopen(ur... |
302f6f870a66c38801a9cdc9cf0073dcd3994ad7 | rajeshpandey2053/python_assignment | /function/F18.py | 93 | 3.703125 | 4 | string = input("Enter the string: ")
func = lambda str: str.isnumeric()
print(func(string)) |
9a941aad797390db70bd6f31f942e9f0ad3ee0f2 | michaelarg/kaggle | /nucleus /python_scripts/u-net_tf.py | 9,292 | 3.71875 | 4 | import os,sys
import numpy as np
import tensorflow as tf
#import weakref
from tflearn.layers.conv import conv_2d, max_pool_2d
#def u_net():
#def variables)
X = tf.placeholder(tf.float32, shape=[None, 640, 960, 3], name="X")
y = tf.placeholder(tf.float32, shape=[None, 640, 960, 1], name="y")
a = tf.constant(2, nam... |
b5ba2dc9f3e637494e65e13e4fa2d90b816b6bab | GrnTeaLatte/AlienInvasion | /Chapter_8/8-11_unchanged_magicians.py | 434 | 3.90625 | 4 | def show_magicians(magicians, great_magicians):
while magicians:
add_great = magicians.pop()
print("The Great " + add_great.title())
great_magicians.append(add_great)
def make_great(great_magicians):
print("\nThe following magicians are great: ")
for name in great_magicians:
print(name)
magicians = ['doof... |
f17b99c61027532fd88887c3919d0752c040a0c7 | martincordero/1-de-Carrera | /Clase_13_05.py | 304 | 3.90625 | 4 | def palabras(frase):
'''
Función que recibe una frase y devuelve un diccionario con las palabras
'''
palabras = frase.split()
longitud = map(len, palabras)
palabras = dict(zip(palabras, longitud))
return palabras
frase = input('Introduce una frase: ')
print(palabras(frase)) |
ca9c38704bb656bf6238b8e23edc6e70877ead6e | Pandiarajanpandian/Python---Programming | /Beginner Level/AmstrongNumber.py | 165 | 3.90625 | 4 | x=int(input("enter a number"))
temp=x
sum=0
while (temp>0):
a=temp%10
sum=sum+a**3
temp=temp//10
if (sum==x):
print("yes")
else:
print("no")
|
d29f67c54163010ee10329dc1f4aae4161cc7a8c | Alan-Liang-1997/CP1404-Practicals | /prac_04/quick_pick.py | 488 | 3.984375 | 4 | import random
number_quick_picks = int(input('How many quick picks would you like to generate? '))
for line in range(0, number_quick_picks):
quick_pick_list = []
for i in range(0, 6):
calculated_int = random.randint(1, 45)
while calculated_int in quick_pick_list:
calculated_int = r... |
7ce8cf25ce9aa78272b5865ee6cb603391e4b04b | CS-NSI/Sorting_algorithms | /insert.py | 200 | 3.53125 | 4 | def insert(t,i): #ok
for current_index in range(i-1,-1,-1):
if t[current_index] > t[current_index+1]:
swap(t,current_index,current_index+1)
else:
break |
4c95ade35dd14ee9a9b61a70b20ebd829299bf56 | ponchitaz/my_py | /Task1-noOOP.py | 662 | 4.0625 | 4 | import random
theText = input('Tell me a story: ')
theWords = theText.split()
def shuffledText(singleWord):
singleWord = list(singleWord)
random.shuffle(singleWord)
singleWord = ''.join(singleWord)
return singleWord
def main():
for singleWord in theWords:
if len(singleWord) >... |
f175c07fbb64e5e29882cadea8d71d9f2477074f | prajwalprabhu/password_generator | /main.py | 638 | 3.625 | 4 | import random
import tkinter as tk
password=''
alphbets='''qwertyuiopasdfghjklzxcvbnmQWERTYUIOPLKJHGFDSAZXCVBNM123456789'''
def generate(e1):
global password
required_charecters=int(e1.get())
password=random.sample(alphbets,required_charecters)
e2=tk.Entry(root)
e2.pack()
e2.insert(0,passw... |
b0d328709ee4c95982bf341959b8e0e5785b135a | LiuZhipeng-github/python_study | /数据结构/python 基础/sort_way/choosee_sort.py | 790 | 4.03125 | 4 | '''
选择排序:首先在未排序序列中找到最小(大)元素,存放到排序序列的起始位置,然后,再从剩余未排序元素中继续寻找最小(大)元素,然后放到已排序序列的末尾。
以此类推,直到所有元素均排序完毕。
时间复杂度为O(n^2)但不稳定(考虑升序每次选择最大的情况)
'''
def selection_sort(alist):
for j in range(0, len(alist) - 1): # 多次找到每次中最小的数
min = j
for i in range(j + 1, len(alist)):
if alist[min] > alist[i]: # 先找一... |
6e1773708f70be58f8a124e3cfcb1273924966cf | E-Brons/self.py | /ex-8.2.2.py | 447 | 4.125 | 4 | import random
def get_item_price(x):
return x[1]
def sort_item_prices(list_of_tuples):
''' Sort tuples of ('item', price) from lowest price to highest price
:param arg1: list of tuple items (;item name', item_price)
:type arg1: list of tuples (str, float)
'''
list_of_tuples.sort(key=g... |
753d2a93a7f0f53831789856cc668e414531c660 | sumedhasingla/LeetCode | /AllPermutationsOfAString-DFS.py | 1,376 | 3.640625 | 4 | import sys
from copy import deepcopy
'''
Question: Find all possible permutations of a given string
Solution:
'''
class Node(object):
def __init__(self, state, path, inputString):
self.state = state
self.path = path
self.inputString = inputString
def goalTest(self):
if len(self.path) == len(self.inputSt... |
32cc232b5d672595c886422fe1cffcf608003fb2 | resync/resync | /resync/url_authority.py | 2,579 | 3.59375 | 4 | """Determine URI authority based on DNS and paths."""
from urllib.parse import urlparse
import os.path
class UrlAuthority(object):
"""Determine URI authority based on DNS and paths.
Determine whether one resource can speak authoritatively
about another based on DNS hierarchy of server names and
path... |
8abf5047ee328f3c942123ee2c247fb9ee2bb0e4 | chaosWsF/Python-Practice | /leetcode/0463_island_perimeter.py | 1,215 | 3.796875 | 4 | r"""
You are given a map in form of a two-dimensional integer grid where 1 represents land and 0 represents
water. Grid cells are connected horizontally/vertically (not diagonally). The grid is completely surrounded
by water, and there is exactly one island (i.e., one or more connected land cells). The island doesn't... |
6a256e3aec941333c7098fe2769b5f5d1208399a | fabiogelbcke/CtCI-Python | /stacks and queues/ex1.py | 2,803 | 3.890625 | 4 | class Node:
def __init__(self, initdata=None):
self._data = initdata
self._next = None
@property
def data(self):
return self._data
@property
def next(self):
return self._next
class TripleStack:
"""
Implementation of a triple stack using only one list.
I... |
bc0a0b9d72baaea1ca6a491d376e5846b4ca8574 | chunlei85/vocab_b | /libs/utils/list_helper.py | 611 | 3.84375 | 4 | # !/usr/bin/python3
# encoding:utf-8
'''
@File : list_helper.py
@Time : 2020/12/15 17:00:37
@Author : AP
@Version : 1.0
@WebSite : ***
'''
# Start typing your code from here
def reverse(s, i: int = None, j: int = None):
"""
翻转
:param s: 需翻转的数组
:param i: 翻转开始位置
:param j: 翻转结束位置
... |
368c83b1b1cad3f8efc3edb0261300adedd01eea | Rudedaisy/CMSC-201 | /Labs/lab11/lab11.py | 791 | 3.6875 | 4 | # File: lab11.py
# Written By: Edward Hanson
# Date: 11/17/15
# Section: 18
# E-mail: ehanson1@umbc.edu
# Description: Translates english words into the "Ong" language.
def main():
word = str(input("Please enter a word to translate into Ong: "))
myWord = ong(word)
myWord.translateO... |
1d6c0129c80de383b6a22f6ac2991f08c3b0c798 | Coderucker/bitbuild | /BitBuild/util/match_os.py | 567 | 3.9375 | 4 | import re
from typing import Match
def match_platform(string: str, to_match_platform_list: list) -> tuple[Match[str], str]:
"""
A Function to Match the preferred operating system.
You need to provide a list of platforms inorder to match it.
Example Usage:
```python
match_platform("build_ar... |
07f99a512dff6d38a4b1c2673b0d38797c20c432 | MHM18/hm18 | /hmpro/zhangxiyang/class/Student.py | 375 | 3.796875 | 4 | class Student(object):
name = ""
score= 5
def __init__(self,name,score):
self.name = name
self.score = score
def print_score(self):
print ("he")
print('%s %s' %(self.name, self.score))
if __name__ == '__main__':
bart = Student('Bart Li',58)
lily = Student("Li... |
f35f30aa7728920b045a747c2c17ffd71a33bed1 | SashoStoichkovArchive/HB_TASKS | /projects/week06/05_04_2019/generators/book_read.py | 537 | 3.546875 | 4 | import keyboard, os
first_part = open("book/001.txt", "r")
second_part = open("book/002.txt", "r")
for line in first_part:
if line.startswith("#"):
input("Next chapter ->")
os.system('cls' if os.name == "nt" else "clear")
print(line[1:])
else:
print(line)
for line in second_pa... |
c95481531d8f0d093455cc0a6fc1e088a555b710 | sudeepnarkar/Programming-in-Python | /rename_files.py | 551 | 3.65625 | 4 | import os
def rename_files():
files_list = os.listdir("directory path")
# print(files_list)
char_delete="0123456789"
current_dir = os.getcwd()
print("Current working directory:"+current_dir)
os.chdir("directory path")
for file_name in files_list:
print("Old filename:"+file_nam... |
6d6199828da19fb5636e7e3b4ae8432e1efa4b8f | kiponik/Python | /Lecture1/HomeTask1.py | 581 | 4.03125 | 4 | # Создаём переменные
variable1 = 'variable1'
variable2 = 2
variable3 = True
variable4 = 4.44
# Вывод переменных
print(type(variable4), type(variable3), type(variable2), type(variable1))
print(variable4, variable3, variable2, variable1)
# Ввод данных
inputInt = int(input('Enter the number: '))
inputDecimal = float(... |
be989d3c0ac16e33383d0e0daf5fcba072c4e79d | monty8800/PythonDemo | /base/19.返回函数.py | 563 | 3.890625 | 4 | # 返回函数
# 1.函数作为返回值
# 求和函数
def calc_sum(*args):
ax = 0
for x in args:
ax = ax + x
return ax
# 不直接返回结果,而是返回一个函数
def lazy_sum(*args):
def sum():
ax = 0
for n in args:
ax = ax + n
return ax
return sum
# 当我们调用lazy_sum()时,返回的并不是求和结果,而是求和函数:
fu = lazy_sum(1,2... |
bf0796a7c2455aaa0328a0988228987679d2c61d | waithope/leetcode-jianzhioffer | /剑指offer/08-二叉树下一个节点.py | 1,929 | 3.90625 | 4 | # -*- coding:utf-8 -*-
'''
二叉树下一个节点
=========================
给定一颗二叉树和其中的一个节点,找出中序遍历序列的下一个节点,树中的节点除了
有两个分别指向左、右子节点的指针,还有一个指向父节点的指针。
'''
class TreeNode(object):
def __init__(self, val, left=None, right=None, parent=None):
self.val = val
self.left = left
self.right = right
self.pa... |
b7620fe096cecea62b1ed57c9a20b776531732fe | AlekseiNaumov/Home_Work | /lesson6/6_1.py | 1,684 | 3.640625 | 4 | # 1. Создать класс TrafficLight (светофор) и определить у него один атрибут color (цвет) и метод running (запуск).
# Атрибут реализовать как приватный. В рамках метода реализовать переключение светофора в режимы: красный, желтый,
# зеленый. Продолжительность первого состояния (красный) составляет 7 секунд, второго (жел... |
884f6bce115704e0343d3ec429c0365b11ab45e6 | ahmetceylan90/firstApp | /Introduction/Lesson5/while.py | 666 | 3.78125 | 4 | #sonsuz döngü örneği
# while(True):
# print("abc")
###############
# i = 0
# while i <= 100:
# if i % 2 == 0:
# print (i)
# i = i + 1
##########
# i = 1
# cift = 0
# tek = 0
# while i <= 1000:
# if i % 2 == 0:
# cift = cift + 1
# else:
# tek = tek + 1
# i = i + 1 ... |
6e9792625e3f1ef71088d1b302d9ad0819f6d582 | tetrismegistus/minutia | /exercises/guided_tutorials/advent15/1_1.py | 208 | 3.53125 | 4 | #!/usr/bin/env python3
floor = 0
for line in open('input.txt'):
for x in line:
if x == '(':
floor += 1
elif x == ')':
floor -=1
print(floor)
print(floor)
|
b57242307803053bffdc9fae80d48000b8cca47e | deyuanyang/python_bioinfo | /get_seq_by_size_range.py | 1,281 | 3.59375 | 4 | #!/usr/bin/env python3
# coding: utf-8
from Bio import SeqIO
import argparse
class fasta_parser():
def __init__(self, fasta):
self.fasta = fasta
def create_seqio_object(self):
return SeqIO.parse(self.fasta, 'fasta')
def get_seq_by_size_range(self, min_seqsize, max_seqsize... |
5a179067df89d0b3282fb1cdc8b037f73b24e8eb | genshang/data-scrape | /app.py | 826 | 3.578125 | 4 | import urllib2
from bs4 import BeautifulSoup
web_page = "https://finance.yahoo.com/quote/FB?p=FB" #created a variable and assigned it the website from yahoo finance FB (getting the website)
page = urllib2.urlopen(web_page)# .urlopen is a function, web_page is the vessel for the website
# print(page)
soup = BeautifulS... |
6d821277fb641301264d66ac93d1bbe786897538 | SKumarMN/DataStructuresPython | /array/subarray_with_zero_sum.py | 387 | 3.75 | 4 | def subArrayExists( arr, n):
s = set()
sum = 0
for i in range(n):
sum +=arr[i]
if(sum == 0 or sum in s):
return True
else:
s.add(sum)
arr2=[4, 2, -3, 1, 6]
arr = [-3, 2, 3, 1, 6]
n = len(arr2)
if subArrayExists(arr2, n) == True:
print("Found a s... |
dee933dae3a4ad5fc6ffc7a9e4c36f820e77019e | Ian-Dzindo01/HackerRank_Challenges | /Python/Sherlock_and_Angrams.py | 783 | 3.84375 | 4 | # two strings angrams if letters of one can be rearranged to form the other
# the idea is to traverse the values of this dictionary divide each of the counts by 2 and add that to the tally
s = 'mom'
def sherlockAndAnagrams(s):
subs = []
r = 0
for i in range(1, len(s)):
d = {} ... |
c40a0f74428e0620cadc0497d13d0113d4d0b069 | ziamajr/CS5590PythonLabAssignment | /CS5590 - 01 Lesson 3 InClass/InClass2.py | 501 | 4.25 | 4 | #David Ziama
#ClassID # 3
#June 23, 2017
# Write a program that takes a list of numbers (for example,a=[5,10,15,20,25])
# and makes a new list of only the first and last elements of the given list.
# For practice, write this code inside a function.
#
a = [5, 10, 15, 20, 25]
print(a[0],a[-1])
#def list(... |
5217771c5fcb6fe749c9892479010c0c9d42a14c | Catedra-Cabify-ETSIT-UPM/madrid_air_quality | /functions/air_quality.py | 2,278 | 3.65625 | 4 | #!/usr/bin/env python3
# Python script with functions to manipulate air quality
# data from datos.madrid.es. It is meant to be imported as
# a library.
import pandas as pd
import numpy as np
def pollutant_daily_ts(path, station_code, pollutant):
"""Return the daily time series of a pollutant measssured
at a... |
6f113c269dbcd2f5d694d67712f9ad675829aa37 | qiaozhi827/leetcode-1 | /11-并查集/00-union_find.py | 5,977 | 3.578125 | 4 |
class UnionFind1:
def __init__(self, n):
self.count = n
self.parent = []
for i in range(n):
self.parent.append(i)
def find(self, p):
while self.parent[p] != p:
p = self.parent[p]
return p
def is_connected(self, p, q):
... |
e5f29a9fb7c2d4106d32342267a4290ff0ae999f | med10d/Code_Suggestions | /adventure_Suggestions.py | 7,121 | 4.0625 | 4 | class Player:
def __init__(self, name, room):
self.name = name
self.room = room
self.moves = 0
# Your code works great for allowing the user to navigate to the different rooms in your adventure game. These comments
# are suggestions for how you could potentially condense your code, allowing... |
9b22b5c1f379f0c001e9c38d5ba5fc2987d361a1 | Wambuilucy/CompetitiveProgramming | /HackerRank/IntroToTutorialChallenges.py | 169 | 3.75 | 4 | #! /usr/bin/python3
# https://www.hackerrank.com/challenges/tutorial-intro
v = int(input())
n = int(input())
ar = input()
arr = ar.split(' ')
print(arr.index(str(v)))
|
32b3b52a9e2db1fd18c0ae1045585f2c98349e01 | brandonPauly/pythonToys | /exercisesInClass.py | 1,200 | 4.03125 | 4 | def pattern(n):
'print a recursive pattern'
if n == 1:
print(1, end = ' ')
else:
pattern(n-1)
print(n, end=' ')
pattern(n-1)
def cheer(n):
'recursively print a cheer'
if n <= 1:
print('Hurrah!')
else:
print("Hip")
cheer(n-1)
def p... |
4dd972497846b6d3acaf307fde7ad07e26572e73 | GuhanSGCIT/Trees-and-Graphs-problem | /distance between both magnets.py | 2,105 | 3.96875 | 4 |
"""
Given coordinates of two pivot points (x0, y0) & (x1, y1) in coordinates plane.
Along with each pivot, two different magnets are tied with the help of a string
of length r1 and r2 respectively. Find the distance between both magnets when they
repelling each other and when they are attracting each other.
In... |
08350051a33919912ce69610c9b17b26ef173614 | YANG007SUN/hackerrank_challenge | /easy/gemstones.py | 325 | 3.640625 | 4 | # https://www.hackerrank.com/challenges/gem-stones/problem?h_r=next-challenge&h_v=zen&h_r=next-challenge&h_v=zen
def gemstones(arr):
res = []
for i in range(len(arr)):
res +=list(set(arr[i]))
d = dict(Counter(res))
counter = 0
for k in d:
if d[k]==len(arr):counter +=1
return co... |
d5aa740943edc76795f72b39c568444c839f5db5 | gjogjreiogjwer/jzoffer | /数组/旋转数组的最小数字.py | 1,974 | 4.375 | 4 | # -*- coding:utf-8 -*-
'''
旋转数组的最小数字
把一个数组最开始的若干个元素搬到数组的末尾,我们称之为数组的旋转。
输入一个递增排序的数组的一个旋转,输出旋转数组的最小元素。例如,
数组 [3,4,5,1,2] 为 [1,2,3,4,5] 的一个旋转,该数组的最小值为1。
example1:
输入:[3,4,5,1,2]
输出:1
example2:
输入:[2,2,2,0,1]
输出:0
解:采用二分法。设置两个指针,分别指向头尾。
若中间元素大于第一个指针,即它位于前面的递增数组,更新第一指针指向中间元素;
若中间元素小于第一个指针,即它位于后面的递增数组,更新第二指针指向中间元素... |
33e055d6db5e05a8e240e54b4890a4f7a3dd3b5c | HJTGit/git | /Python学习/什么是dict.py | 191 | 3.703125 | 4 | #新来的Paul同学成绩是 75 分,请编写一个dict,把Paul同学的成绩也加进去。
d = {
'Adam': 95,
'Lisa': 85,
'Bart': 59,
'Paul': 75
}
print (d.get('Adam')) |
9a66ccc78167a67cfbccd0b16f9ea23d7ea286bc | lobstersalad/EPIPython | /PrimitiveTypes/parity.py | 567 | 3.984375 | 4 | def parity(x: int) -> int:
result = 0
while x:
print("x is currently: " + str(bin(x)[2:]))
result ^= 1
print("result is currently " + str(result))
a = x & ~(x - 1)
print ("a is " + str(bin(a)[2:]))
x &= (x - 1)
return result
while True:
try:
numbe... |
bf83092923c75b816b1a5d97a1c66416e889f528 | Anderson-Lab/data-301-student | /book/Chapter 1 Tables Observations Variables/1.1 Introduction to Tabular Data.py | 23,539 | 4.4375 | 4 | # ---
# jupyter:
# jupytext:
# formats: ipynb,py,md
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.4'
# jupytext_version: 1.2.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# # Chapter 1. Tables, Obser... |
0baae2da4abde3904fe7935aec0270b37d5f9ca9 | ArunaRanjitha/guvi | /code/Five.py | 118 | 3.609375 | 4 | p,q,r=input().split()
max(p,q,r)
if(p>q) and (p>r):
print(p)
elif(q>p) and (q>r):
print(q)
else:
print(r)
|
da8c4755834d9aabbf3019a6439c6c1b04d4af82 | thomasmcclellan/pythonfundamentals | /11.02_OOP_attributesAndMethods.py | 1,444 | 4.5 | 4 | # Attributes are characteristics of an object
# Methods are operations we can perform on an object
class Dog():
def __init__(self,breed,name): #Methods look likes functions within the class and have the __#__ syntax
self.breed = breed #Attribute involves self.#
self.name = name #self operates similarly to th... |
607d3dd3832d7e114afde579e4f2546e1d10aa6e | rugbyy/AlgorithmChallenges | /fizzbuzz/fizzbuzz.py | 422 | 3.578125 | 4 | def fizz_buzz(self, num):
if num == 0: # seems this should have been < 1 instaed of == 0. need to read instructions carefully
raise ValueError
if not num:
raise TypeError
num_list = []
for n in range(1,16):
if n % 3 == 0 and n % 5 == 0:
num_list.append("FizzBuzz")
elif n % 5 == 0:
num_list.append("Bu... |
fe1ecf93898bcf75553daf0b914c336647bada4c | Daishijun/InterviewAlgorithmCoding | /ZuoShenBook/stringQ/statisticString.py | 1,304 | 3.765625 | 4 | # -*- coding: utf-8 -*-
# @Date : 2019/4/20
# @Time : 18:44
# @Author : Daishijun
# @File : statisticString.py
# Software : PyCharm
'''
字符串的统计字符串
'''
def getCountString(string):
if not string:
return ''
res = string[0]
num =1
for i in range(1, len(string)):
if string[i] == str... |
09682bcc29af9bec3b191578cf9d11583960c991 | bhavisheythapar/LeetCode | /groupAnagrams/groupAnagrams.py | 308 | 3.984375 | 4 | def groupAnagrams (str):
dict={}
for element in str:
sorted_word=str(sorted(i))
if sorted_word not in dict:
dict[sorted_word]=[]
dict[sorted_word].append(i)
return dict.values()
ex1 = ["eat", "tea", "tan", "ate", "nat", "bat"]
str="abcde"
groupAnagrams(ex1) |
f89a270de40aa5ab9195c691e171680683a26106 | aos/advent | /2018/day06/part_1.py | 2,466 | 3.625 | 4 | # Day 6 - Puzzle 1
# What is the size of the largest area?
import collections
def largest_area(inp_arr):
areas = collections.defaultdict(int)
max_x, max_y = _grid_size(inp_arr)
grid = _generate_grid(max_x, max_y)
populated = _populate_grid(inp_arr, grid, max_x, max_y)
for y, row in enumerate(po... |
6cb5ec8533c242d9a80e6408fd35a1b06d4317e2 | Md-Saif-Ryen/roc-pythonista | /OOP/Calculator.py | 470 | 3.90625 | 4 | class Calculator:
# Write methods to add(), subtract(), multiply() and divide()
def add(self, num1, num2):
self.add = num1 + num2
return self.add
def subtract(self, num1, num2):
self.subtract = num1 - num2
return self.subtract
def multiply(self, num1, num2):
sel... |
a2d39b6382d66687417e4d335798e25f4762f41c | tripathyas/Online-Hackathon | /codeutility.py | 388 | 3.515625 | 4 | # you can write to stdout for debugging purposes, e.g.
# print("this is a debug message")
def solution(A):
# write your code in Python 2.7
A.sort()
i = 0
num = 1
while i < len(A) and A[i] <= 0:
i += 1
while i < len(A):
if A[i] == num:
num+=1
elif A[i] > num:... |
0b8bce1a911df9858fd81fb20902dcdd76545b5e | kbtania/Labs | /lab_map_filter_reduce/Tasks/reduce_filter2.py | 434 | 3.75 | 4 | # Дано масив (список) елементів цілого типу.
# Знайти суму додатних елементів.
from functools import reduce
count = int(input('Count el: '))
previous_list = [int(input('Enter element: ')) for x in range(count)]
positive_num = list(filter(lambda x: x > 0, previous_list))
positive_sum = reduce(lambda positive_sum, x: po... |
0a39d7e8fe212f64f06a1c50090714b50567b231 | xiangcao/Leetcode | /Python_leetcode/99_recover_binary_search_tree.py | 2,119 | 3.875 | 4 | # Definition for a binary tree node.
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution(object):
firstMisplaced = secondMisplaced = None
import sys
lastVisited = TreeNode(-sys.maxint-1)
#Wrong.
def recoverT... |
1b0404aa3de9a6d98a360008e95c2d8164ba1465 | sailakshmi-mk/pythonprogram1 | /venv/co4/5. Class publisher.py | 907 | 4.125 | 4 | class Publisher:
"information about books"
def __init__(self, pubname):
self.pubname = pubname
def display(self):
print("Publisher Name:", self.pubname)
class Book(Publisher):
def __init__(self, pubname, title, author):
Publisher.__init__(self, pubname)
self.title = title
s... |
6a85e507b567026f9e6ec7734020b8e2a7ba7f17 | neerajjadhav3012/Programming | /Stack_Queue/BalancedParenthesesCheck.py | 1,614 | 4.25 | 4 |
# coding: utf-8
# # Balanced Parentheses Check
#
# ## Problem Statement
#
# Given a string of opening and closing parentheses, check whether it’s balanced. We have 3 types of parentheses: round brackets: (), square brackets: [], and curly brackets: {}. Assume that the string doesn’t contain any other character tha... |
32546ed9a098998b6290208aa4050f85666fc441 | habahut/CS112-Spring2012 | /Friday Classes/core/input.py | 2,178 | 3.640625 | 4 | #dont need the thing at the top because this is not an executable file
import pygame
from pygame.locals import *
class KeyDownListener(object):
def on_keydown(self,event):
pass
def on_keyup(self, event):
pass
class MouseListener(object):
def on_click(self,event): pass
def on_motion... |
cbd1b9111b4bfc61488027a5aa594fc9a536fd8d | linzer0/karel-python | /karel.py | 3,660 | 3.734375 | 4 | from gui import Gui
from tkinter import *
class World():
def print_world(self):
for i in self.world:
print(*i)
print('\n')
def get_karel(self):
x = -1
y = -1
for i in range(len(self.world)):
for j in range(len(self.world[i])):
... |
c2d92dc6c6e4f8b291ad08da61c177b9423ca11c | Victoriasaurio/Exercises | /Mutante.py | 2,358 | 3.734375 | 4 | x = int(input("Ingrese el tamaño del array --> "))
adn = input("Ingresar la secuencia del ADN --> ")
_array = []
_adn_array = []
# STRING-ARRAY
for a in adn:
_array.append(a)
c = 0
i = 0
h = x
# MATRIZ
while c < x:
_adn_array.append(_array[i:h])
i += x
h += x
c +=1
#HORIZONTAL
eje_y = 0
eje... |
be031abb14007940c96be57f24e5184fdfdc575d | bikennepal/Python-Basic | /user_input.py | 134 | 4.1875 | 4 | # input function
# user input
name=input("enter your name")
print("This is your name" + name)
#Input is always taken as string |
9983abbb454982bd007ef6850fa38184256d5475 | greenblues1190/Python-Algorithm | /LeetCode/9. 트리/310-minimum-height-trees.py | 1,769 | 4.09375 | 4 | # https://leetcode.com/problems/minimum-height-trees/
# A tree is an undirected graph in which any two vertices are connected by exactly
# one path. In other words, any connected graph without simple cycles is a tree.
# Given a tree of n nodes labelled from 0 to n - 1, and an array of n - 1 edges
# where edges[i] = [... |
032e8138940a597508a66bd2f53025b6b00d5162 | reentrant/python_exercises | /book_learning/list_permutations.py | 1,841 | 4.15625 | 4 | #!/usr/bin/python -tt
# Source:
# LEARNING TO PROGRAM WITH PYTHON
# Richard L. Halterman
"""
Example: List Permutations
"""
from itertools import permutations
DEBUG = True
counter = 0
def permute(prefix, suffix):
'''
Recursively shifts all the elements in suffix into prefix
'''
global counter
coun... |
78f13ae8cccfb13c7bcecc9bf11a38c4e966611b | CRFranco/TWELVE-MONKEYS | /versao2_entities/macacos.py | 2,233 | 4.03125 | 4 | #!/usr/bin/env python
# -*- coding: utf8 -*-
'''
Created on 24 de mai de 2016
@author: cristiano.franco
'''
from random import randint
class Macaco :
_descricao = None
_life = 0
def __init__(self, descricao):
self._descricao = descricao
self._life = 5
def get_des... |
b4793b2b916119635c0df76b48690b24dbd10c62 | carlos2020Lp/progra-utfsm | /guias/2012-2/septiembre-3/fibo-menores.py | 229 | 3.84375 | 4 | m = int(raw_input('Ingrese m: '))
print 'Los numeros de Fibonacci menores que', m, 'son:'
anterior = 0
actual = 1
print 0
while actual < m:
print actual
suma = anterior + actual
anterior = actual
actual = suma
|
ddb3bce7f4a1d53a386f06f83150d6a97cd020ef | therouterninja/Studies | /hackerrank/algorithms/03_strings/01_pangrams.py | 299 | 4.03125 | 4 | # Enter your code here. Read input from STDIN. Print output to STDOUT
mystring = raw_input()
all_values = set()
total = 0
for char in mystring:
all_values.add(char.lower())
for value in all_values:
total += ord(value)
if total == 2879:
print "pangram"
else:
print "not pangram" |
c06602210d9435abc93d044504a3cbcaaa67504e | enthusiasm99/crazypython | /02/P43-ternary_operator_test.py | 374 | 3.765625 | 4 | a = 5
b = 3
st = 'a大于b' if a > b else 'a小于b'
print(st)
st = print('crazyit'), 'a大于b' if a > b else 'a小于b'
print(st)
st = print('crazyit'); x = 20 if a>b else 'a不大于b'
print(st)
print(x)
c = 5
d = 5
print('c大于d' if c>d else ('c小于d' if c<d else 'c等于d'))
print('c大于d') if c>d else (print('c小于d') if c<d else print(... |
44afd7bd1f0ce0421d99a4868dce566036a6581f | deepshikhadas20/Data-visualization | /Data-visualization-master copy/Teacher refrence/plot.py | 215 | 3.59375 | 4 | import pandas as pd
import plotly.express as px
df = pd.read_csv("line_chart_csv")
fig = px.line(df,x="Year",y="Per capita income", color="Country",
title="per Capita")
fig.show() |
5503fbdc6bf437f0c22b557f4ae8188258e079b8 | 1412qyj/PythonAdvanced | /code/2.python高级知识-多进程/filesCopy.py | 4,340 | 3.71875 | 4 | # 完成将一个文件夹和文件复制到另一个文件夹中
import os
import multiprocessing
# 1.定义一个文件夹复制器的类
import time
class FolderCopy(object):
def __init__(self):
self.file_names = []
self.file_name = None
self.source_file_name = None
self.dest_file_name = None
self.queue = None
self.source_... |
b59c23d5f82e155a207339d374c2be6d13b2c770 | upadhyay-arun98/PythonForME | /Basic Python Programming/1. Input-Process-Output/computeLoan.py | 427 | 4.21875 | 4 |
annual_rate = float(input("Enter Yearly Interest Rate\n"))
monthly_rate = annual_rate/1200
years = int(input("Enter number of years, for example 5: \n"))
loan_amount = float(input("Enter loan amount, example 120000.95 \n"))
EMI = loan_amount * monthly_rate / (1 - 1/(1 + monthly_rate)**(years*12))
total_payme... |
9dac8e190ab71b6da89e4269ecd0e3f081ff43a5 | congyingTech/Basic-Algorithm | /medium/clone-graph.py | 609 | 3.515625 | 4 | # encoding:utf-8
"""
给你无向 连通 图中一个节点的引用,请你返回该图的 深拷贝(克隆)。
图中的每个节点都包含它的值 val(int) 和其邻居的列表(list[Node])。
class Node {
public int val;
public List<Node> neighbors;
}
"""
# Definition for a Node.
class Node(object):
def __init__(self, val = 0, neighbors = []):
self.val = val
self.neighbors = ne... |
b8a730d4c5a0f950f6806f53474c73e61f5938ee | davll/practical-algorithms | /algo.py/algo/tree/segment_tree.py | 1,913 | 3.5625 | 4 | # Segment Tree
# 1. The root represents the whole array A[0:N]
# 2. Each leaf represents a single element A[i]
# 3. The internal nodes represents the union of elementary intervals A[i:j]
import math
class SegmentTree:
def __init__(self, arr):
n = len(arr)
ns = 2 * (2 ** int(math.ceil(math.log2(n)... |
10c218a4ccf3446983c711948d892b565545e994 | yxc775/SeniorRoject | /Database/stockDB_init.py | 2,470 | 4.03125 | 4 | '''
A SQLite-based local SQL database for effect testing and verification purposes.
This program is mainly used for testing stock data passing and storage
in SQL and design improvement.
This part initializes an empty sqlite local database with structures designed in database.jpeg
with no additional table for stocks c... |
7642d27291f51f92bf2a827c4adfdeefbab5c683 | dariadec/kurs_python | /10/zad_1_wprowadzenieOOP_piesel.py | 468 | 3.53125 | 4 | class Dog:
def __init__(self, name, color, breed):
self.name = name
self.color = color
self.breed = breed
def bark(self):
return self.name + " says Hau"
def wag(self):
return self.name + "is wagging his tail"
obj_pimpek = Dog("Pimpek", "white", "jamni... |
17d7604962a5322eafcbe217c7ff251dc52323fe | parkjaewon1/python | /ch06/fat1.py | 130 | 3.78125 | 4 | def fat1(num):
result = 1
for i in range(1, num + 1):
result *= i
return result
print(fat1(3))
print(fat1(5)) |
0462ccecd6000d59ca342107fac0e2ed230b62d1 | just4cn/algorithm | /sort_algorithm/insertion_sort.py | 362 | 3.78125 | 4 | # coding: utf-8
def insertion_sort(nums):
if not nums:
return
length = len(nums)
# 从第1个数开始排序(第0个默认有序)
for i in xrange(1, length):
key = nums[i]
j = i - 1
while j >= 0 and nums[j] > key:
nums[j + 1] = nums[j]
j -= 1
nums[j + 1] = key
... |
d0e9de6520d8ee9a354b208f1ae5ce4e599e6e09 | Herna7liela/New | /Question5.py | 954 | 4.1875 | 4 | # Based in the definition of the mathematical constant e, as the sum of an infinite
# series (see wikipedia: http://en.wikipedia.org/wiki/E_%28mathematical_constant%29)
# create a program that ask the user for the number of terms used to calculate the
# approximation, and returns its value.
# because e is the sum o... |
2351c73df5fc1afdc90adea116506ea4d5bee1e1 | Neil-Do/HUS-Python | /Python 100 Problem/Problem41.py | 138 | 3.75 | 4 | def printTuple():
t = tuple(i**2 for i in range(1, 10))
half = len(t) // 2
print(t[:half])
print(t[half:])
printTuple()
|
e0674ff4cc06b6da7a09f26951f680e42e3393ff | JesseStorms/exercises | /01-basic-python/08-sets/02-remove-duplicates/student.py | 203 | 3.59375 | 4 | # Write your code here
def remove_duplicates(xs):
seen = set()
res = []
for thing in xs:
if thing not in seen:
seen.add(thing)
res.append(thing)
return res |
1bc088e0f040d9554a2579a3052f7c650f987fa4 | indraastra/puzzles | /euler/prob001.py | 124 | 3.703125 | 4 | #!/usr/bin/python
from __future__ import print_function
print(sum(n for n in range(1000) if (n % 3) == 0 or (n % 5) == 0))
|
7d19e7fca4207f3ef4c0bdb8a5c11fe012b6e641 | behnamasadi/PythonTutorial | /Tutorials/class/inheritence.py | 1,052 | 4 | 4 | # https://stackoverflow.com/questions/4015417/python-class-inherits-object
# Is there any reason for a class declaration to inherit from object?
# In Python 2: always inherit from object explicitly. Get the perks.
# In Python 3: inherit from object if you are writing code that tries to be Python agnostic, that is, it n... |
8da9b75117bcd50435936664d470dd50f7fad315 | apanana/rosalind | /mer.py | 697 | 3.65625 | 4 | """
Given: A positive integer n<=10^5 and a sorted array A[1...n] of integers from
-10^5 to 10^5, a positive integer m<=10^5 and a sorted array B[1...m] of
integers from -10^5 to 10^5.
Return: A sorted array C[1...n+m] containing all the elements of A and B.
"""
def mer(xs,ys):
zs = []
i,j = 0,0
while i < len(xs) ... |
aa2f2595699137a5ffa4ad8bcf99bbb55c878b1a | cp4011/Algorithms | /热题/208_实现 Trie (前缀树).py | 2,150 | 4.3125 | 4 | """实现一个 Trie (前缀树),包含 insert, search, 和 startsWith 这三个操作。
示例:
Trie trie = new Trie();
trie.insert("apple");
trie.search("apple"); // 返回 true
trie.search("app"); // 返回 false
trie.startsWith("app"); // 返回 true
trie.insert("app");
trie.search("app"); // 返回 true
说明:
你可以假设所有的输入都是由小写字母 a-z 构成的。 保证所有输入均为非空字符串。
"""
... |
efd370844802e61c304bc119d39f4a37560c1d93 | thinkphp/matrix | /linesToDec.py | 1,216 | 3.984375 | 4 | '''
Se da o matrice binara Matrix de tip (m,n). Fiecare linie retine
cifrele reprezentarii binare a unui numar natural. Se cere
afisarea numerelor in baza 10, un numar reprezentand unei linii,
cat si suma lor.
Exemplu:
m = 5, n = 4;
0 0 1 1 3
1 0 0 1 9
Matrix = 1 1 1 0 14 31
0 0 0 0 ... |
9c3d9ccf658772d9a60ad197d75483518406ab4a | Ricardo301/CursoPython | /Desafios/Desafio050.py | 142 | 4.0625 | 4 | s = 0
for x in range(0, 6):
num = int(input('Digite um valor: '))
if num % 2 == 0:
s += num
print('A soma dos pares é: ', s)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.