blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
38b2eb41aff9813fd70eed0c6a12de2f097049fa | liuhatry/python_tools | /Search/blockSearch.py | 1,404 | 3.90625 | 4 | #!/usr/bin/env python
listIndex = [9,19,25,100,200,321]
mylist = [[],[],[],[],[],[],[]]
def findIndex(index,data):
min = 0
max = len(index) -1
while(min <= max):
mid = (max + min) // 2
if data > index[mid]:
min = mid + 1
else:
max = mid -1
return max +... |
2acb0005b760b130fc4c553b8f9595c91b828c0e | tainagdcoleman/sharkid | /helpers.py | 2,892 | 4.125 | 4 | from typing import Tuple, List, Dict, TypeVar, Union
import scipy.ndimage
import numpy as np
import math
Num = TypeVar('Num', float, int)
Point = Tuple[Num, Num]
def angle(point: Point,
point0: Point,
point1: Point) -> float:
"""Calculates angles between three points
Args:
point... |
20912df66b41ae5dd0ff66d24b09d713333cd187 | eglrp/point-cloud-clustering | /analysis/visualize_histograms_for_object_clouds.py | 1,778 | 3.640625 | 4 | import os
import pandas as pd
from collections import Counter
import matplotlib.pyplot as plt
# This python file is used to plot a histogram of the number of points in object PCD files.
# This is useful to see the distribution of the number of points/PCD for different objects
# To run this file you have to download o... |
7aaa877e60eff4a1000e505eefa770912e3bf0a8 | KartikJha/code-quiver | /python/comp-coding/flatten-binary-tree-linked-list.py | 935 | 3.796875 | 4 | class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
class Solution:
def flatten(self, root: TreeNode) -> None:
"""
Do not return anything, modify root in-place instead.
"""
l = TreeNode(-1, N... |
30463e25c78ae51d99a5ddc06a58c1f7d17127ea | sharannyobasu/Hacker-Blocks | /gcd.py | 166 | 3.859375 | 4 | def gcd(a,b):
if(b>a):
if(b%a==0):
print(a)
else:
gcd(b-a,a)
else:
if(a%b==0):
print(b)
else:
gcd(a-b,b)
a=int(input())
b=int(input())
gcd(a,b)
|
3dca2e4f3597cf59d199e95e0b74536c828d26b4 | I-will-miss-you/CodePython | /Curso em Video/Exercicios/ex031.py | 560 | 4 | 4 | # Desenvolva um programa que pergunte a distância de uma viagem em Km.
# Calcule o preço da passagem, cobrando R$050 por Km para viagens
# de até 200km e R$0.45 para viagens mais longas.
distância = float(input('Qual é a distância da sua viagem? '))
print('Você está prestes a começar uma viagem de {}Km.')
'''if distân... |
2858240db931d531fefc1e55824438f36ca22bad | LukasNickel/aoc | /07/solution.py | 2,272 | 3.703125 | 4 | from collections import defaultdict
def part1(puzzle, target='shiny gold bag'):
contains = containment_rules(puzzle)
result = set()
check = [target]
finished_searching = set()
while True:
try:
target = check.pop()
except IndexError:
break
if target i... |
6a2c08824866a7fcc4fefb60974a2051bf0913c4 | hubert-wojtowicz/learn-python-syntax | /module-2/16-for-loops.py | 114 | 3.796875 | 4 | for x in "Python":
print(x)
for x in ['a', 'b', 'c']:
print(x)
for x in range(1,5):
print(x) |
df0c0e1a0fe2c0a997ce32d3d4dd251ca4abbdcd | MrWifeRespecter/TECHNOLOGY | /U12-6/U12-6/U12_6.py | 570 | 3.640625 | 4 | from turtle import *
from random import *
from math import *
setworldcoordinates(-20, -20, 20, 20)
speed(0)
ht()
def draw(x,y):
pu()
setpos(x,0)
pd()
goto(0,y)
#Man gör bara förra uppgiften fast åt olika håll
#Första kvadrant
x=0
y=20
for i in range(21):
draw(x,y)
x+=1
y-=1
#Andra kvadran... |
2e3663ca0bbdc7252f9bc7a4c453708a20be1cdb | gar19421/lab03 | /lab3_GUI_Serial.py | 3,072 | 3.59375 | 4 | #Codigo para comunicacion serial GUI lab03
#Brandon Garrido -19421
#Digital 2 seccion 20
#LIBRERÍAS
from tkinter import *
from tkinter.font import Font
from time import sleep
import serial
import time
import sys
import tkinter as tk
#CREAR PUERTO SERIAL PARA LA COMUNICACION USANDO PYTHON
puerto= serial.Serial()... |
055444edb77a8cf4e79c6e1a57f7c9d4d00ba699 | Javacream/org.javacream.training.python | /org.javacream.training.python/src/3-Einfache Anwendungen/types_control_loop.py | 351 | 3.96875 | 4 | even_message = "an even number: "
odd_message = "an odd number: "
numbers = range(1, 10)
finished = False
for i in numbers:
print ("processing number " , i, ", finished: ", finished)
if i % 2 == 0:
print (even_message, i)
else:
print (odd_message, i)
finished = True
print ("all numbers pro... |
4637c58e87c1e1be51f96bf19ccbfe586be4201a | AbdurrahimBalta/ProjectEuler-AlgorithmQuestion-in-Python | /Question2.py | 936 | 3.65625 | 4 | #Soru 2
#Each new term in the Fibonacci sequence is generated by adding the previous two terms. By starting with 1 and 2, the first 10 terms will be:
#1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...
#By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-valued terms... |
68cebde8659110abe925da3d6ab5189095dd9a1e | FelipeSenco/PokemonMaster | /pokemon.py | 8,755 | 3.765625 | 4 |
class Pokemon:
def __init__(self, name, level, type):
self.name = name
self.level = level
types = ["normal", "fighting", "flying", "electric"]
if (type.lower() in types):
self.type = type.lower()
else:
print("Warning: invalid type! Th... |
462b0a6faa51e5a389bdd47b81d7879a303dc8b1 | damyac/working-days | /workingdays.py | 2,471 | 3.578125 | 4 | #Author: Da'Mya Campbell (damycamp@cisco.com)
#File: workingdays.py
#Date: May 2018 (c) Cisco Systems
#Description: Calculates the number of working days between two dates, excluding weekends and holidays.
import time
from dateutil import rrule
from datetime import datetime
from datetime import date
def workingdays(s... |
f3d150018213352f079d38699361ec144302b336 | Sceluswe/pyNutrition | /myJson.py | 893 | 3.921875 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Save jsonObj to json file.
"""
import json
def loadJSON(filename):
"""
Load a JSON file.
Return JSON object.
"""
returnObj = None
# Try to create the file, if it exists just move on.
try:
with open(filename, "x") as JSONfile:
... |
605e5fea818e882f1ee11c8962ce5db5e9a591af | iamserda/cuny-ttp-algo-summer2021 | /AdrianBarros/assignments/fastSlow/lc202/lc202.py | 2,631 | 4.15625 | 4 | # Problem Statement #
# Any number will be called a happy number if, after repeatedly replacing it with a number equal to the sum of the square of all of its digits, leads us to number 1. All other (not-happy) numbers will never reach 1. Instead, they will be stuck in a cycle of numbers which does not include 1.
'''
... |
6134445a05970921338e0027413584a4905eebc4 | sitxseek/AdventOfCode2019 | /day1/puzzle.py | 324 | 3.515625 | 4 | def parse(lines):
return list(map(int, lines))
def solvePartOne(data):
sum = 0
for n in data:
sum += (n // 3 - 2)
return sum
def solvePartTwo(data):
sum = 0
for n in data:
while True:
n = (n // 3 - 2)
if n > 0: sum += n
else: break
return... |
676b23fefba2422c3d7fef3abda3cd74336b2e49 | MrHamdulay/csc3-capstone | /examples/data/Assignment_8/eyrros001/question2.py | 594 | 3.984375 | 4 | """ recursive function to count the number of pairs of repeated characters in a string
Ross Eyre
05/05/2014"""
def main():
msg = input("Enter a message:\n")
n = pairs(msg)
print("Number of pairs:", n)
# count pairs of characters
def pairs(string):
if(len(string)==0): #if string contains no... |
e91f3dfee2b0eb94123d11b7c8dd0f9775055d8c | alemarlo1992/accounting_summary- | /accounting.py | 1,524 | 4.4375 | 4 |
# To Do
# Read through accounting.py and understand what it’s doing.
# Create a function that takes in a text file of customer orders and parses it to produce similar output.
# Add comments explaining what your code is doing.
# Read over the solution and see how it compairs to your answer.
def underpaid_melons(path)... |
564518af54b7bfe9c0d90fe887df4fa918fa4e0d | sherms77/Calculator-app | /Calculator.py | 1,887 | 4.03125 | 4 | import math
print('This is a calculator app. \nIt lets you do basic arithmitic operations.')
menChoice = ''
def mainMenu():
global menChoice
menChoice = input('\nEnter the type of operation you want to do by entering the number next to one of the four options below or enter q to quit: \n1.Add \n2.Subtrac... |
0a3ae986420c3d891e3c7c09aba183ee8b76ef3f | daniel-reich/ubiquitous-fiesta | /JBTLDxvdzpjyJA4Nv_3.py | 197 | 3.65625 | 4 |
def super_reduced_string(s):
stack=[]
for x in s:
if stack==[] or stack[-1]!=x:
stack.append(x)
else:
stack.pop()
return ''.join(stack) if stack!=[] else 'Empty String'
|
d302dcd5b705246a9e1ce966e9af1066484737da | IgorNikolin/python | /Задачи по функциям 2.py | 623 | 3.96875 | 4 | i = int(input("1) Круг 2)прямоугольник 3)треугольник"))
if i==1:
A = int(input("введите значение Радиуса"))
B = 3.14
s = ((A*B)**2)
print(round(s, 2));
elif i==2:
A = int(input("Введите значение высоты"))
B = int(input("Введите значение ширины"))
s = (A*B)
print(s)
elif i==3:
... |
45ac246159a1cc4d8212be4bab16e8c4259b2ee2 | msbuddhu/PythonBasics | /q135.py | 115 | 3.671875 | 4 | def add(x, y):
return x + y
result = add(10, 20)
print("The sum is", result)
print("The sum is", add(100, 200)) |
377c6b4c8fb04e5bf0148992eaf8fa10be37e939 | Nostromo-04/python | /lesson02/Zadanie2_4.py | 557 | 4 | 4 | # Пользователь вводит строку из нескольких слов, разделённых пробелами.
# Вывести каждое слово с новой строки. Строки необходимо пронумеровать.
# Если в слово длинное, выводить только первые 10 букв в слове.
my_str = input('Введите строку из нескольких слов: ')
split_str = my_str.split()
for i in range(0, len(split_... |
ae2440c591c9aedd06971ddf6507c86543856008 | Pythones/MITx_6.00.1x | /ProblemSet6/borra.py | 181 | 3.5625 | 4 |
list = ['6.00.1x', 'is', 'pretty', 'fun']
ListLen = len(list)
wordLenInList = []
for i in range (ListLen):
wordLenInList.append (len(list[i]))
print ListLen
print wordLenInList |
f91af59a5266d355adc790d03b98a93230eac0ed | ShinCheung/LeetCode | /66.加一.py | 708 | 3.703125 | 4 | # 给定一个由整数组成的非空数组所表示的非负整数,在该数的基础上加一
# 最高位数字存放在数组的首位, 数组中每个元素只存储一个数字
# 你可以假设除了整数 0 之外,这个整数不会以零开头
# 示例 1:
# 输入: [1,2,3]
# 输出: [1,2,4]
# 解释: 输入数组表示数字 123
# 示例 2:
# 输入: [4,3,2,1]
# 输出: [4,3,2,2]
# 解释: 输入数组表示数字 4321
# 注意,9+1=10,会进位
class Solution:
def plusOne(self, digits):
num_int = 0
for num in digits:
... |
9cbbd97635854b3532a20e3410a9fddd874b9538 | MDGSF/JustCoding | /python-leetcode/it_08.06.py | 480 | 3.625 | 4 | from typing import List
class Solution:
def hanota(self, A: List[int], B: List[int], C: List[int]) -> None:
"""
Do not return anything, modify C in-place instead.
"""
def dfs(n, A, B, C):
if n == 0:
return
if n == 1:
C.append(A.pop())
return
dfs(n - 1, A, ... |
1654c8235aa45abf509d82f418234e366cb5f1e2 | duongyen24/python-master | /tik tak toe.py | 474 | 3.6875 | 4 | board = ["-","-","-",
"-","-","-",
"-","-","-",]
def display_board():
print(board[0],board[1],board[2])
print(board[3],board[4],board[5])
print(board[5],board[6],board[7])
display_board()
def play_game():
display_board()
handle_turn()
def handle_turn():
position= input("ch... |
5350fb6bb4df26529187d8b83bead510f9954938 | juanmbraga/CS50-2021-Seminars | /Taste of Python/11.scores.py | 294 | 3.921875 | 4 | def main():
score1 = int(input("Score 1: "))
score2 = int(input("Score 2: "))
score3 = int(input("Score 3: "))
printScore(score1)
printScore(score2)
printScore(score3)
def printScore(n):
for i in range(n):
print("#", end="")
print()
main() |
75f9f740ab41b9ddafaa229f4b5e4b4963983148 | MasumTech/URI-Online-Judge-Solution-in-Python | /URI-1074.py | 357 | 3.875 | 4 | n = int(input())
for i in range(n):
a = int(input())
if a == int(0):
print('NULL')
elif a%int(2)!=int(0):
if a<int(0):
print('ODD NEGATIVE')
else:
print('ODD POSITIVE')
elif a%int(2)==int(0):
if a<int(0):
print('EVEN NEGATIVE')
els... |
03636fdb1ea03d3e264dafb4ef30cf7cef476876 | Baha/tuenti-challenge-4 | /challenge-1/challenge-1.py | 1,694 | 3.609375 | 4 | #! /usr/bin/env python
import sys
class Student:
name = ""
gender = ""
age = 0
studies = ""
academic_year = 0
def __init__(self, line):
fields = [x for x in line.split(',')]
if len(fields) > 4 :
self.name = fields[0]
self.gender = fields[1]
self.age = int(fields[2])
self.st... |
9708a128e871da39e7eabecec0e1ab59fe098a69 | DenisZun/flunet_python | /chapter_01/mulit_vecttor.py | 1,757 | 3.921875 | 4 | # -*- coding:utf-8 -*-
# 二维数组表示向量
"""
len(x) 的速度会非
常快。背后的原因是 CPython 会直接从一个 C 结构体里读取对象的长度,完全不会调用任
何方法。获取一个集合中元素的数量是一个很常见的操作,在 str、list、memoryview
等类型上,这个操作必须高效。
"""
from math import hypot
class Vector(object):
def __init__(self, x=0, y=0):
self.x = x
self.y = y
def __repr__(self):
""... |
ac7dcbab0f3a540ec01bf762ca80eb12ceb1bddc | tenten0113/python_practice | /5/str7_1.py | 240 | 3.53125 | 4 | msg = 'にわにはにわにわとりがいる'
print(msg.replace('にわ', 'ニワ')) # 結果:ニワにはニワニワとりがいる
print(msg.replace('にわ', 'ニワ', 2)) # 結果:ニワにはニワにわとりがいる
|
ea0e631ee3d6b1b9491bf780462673946804efd0 | ConlinLee/homework-python-github | /prime.py | 369 | 3.578125 | 4 | #!-_-coding;utf-8 !-_-
from time import clock
def SuShu(num):
ss=[2]
for x in range(3,num,2):
for y in ss:
if x % y == 0:
break
elif y > int(num**0.5):
ss.append(x)
else:
ss.append(x)
return ss
c = clock()
print(SuShu(10000... |
ed6e26cc6741238d5eb044a15d9d72a46cec78ae | RoslinErla/AllAssignments | /assignments/functions/prime_number.py | 954 | 4.4375 | 4 | # A prime number is a natural number greater than 1 that has no positive divisors other than 1 and itself.
# Write a function named is_prime that takes an integer argument and returns True if the number is prime and False otherwise. (Assume that the argument is an integer greater than 1, i.e. no need to check for erro... |
3b553ac4247327297074a8075d52c8f6e2f0a108 | Yuvaraj421/object_oriented_programs | /stack.py | 1,189 | 4.03125 | 4 | class Node:
def __init__(self, data):
self.data = data
self.next = None
class Stack:
def __init__(self):
self.top = None
def isEmpty(self):
# this block check the linked list
if self.top == None:
return True
else:
return False
... |
b4e7995de611dad194e05521710f98abaed8a7ed | rssbrrw/PythonProgrammingPuzzles | /generators/trivial_inverse.py | 20,862 | 4.25 | 4 | """Trivial problems. Typically for any function, you can construct a trivial example.
For instance, for the len function you can ask for a string of len(s)==100 etc.
"""
from puzzle_generator import PuzzleGenerator
from typing import List
# See https://github.com/microsoft/PythonProgrammingPuzzles/wiki/How-to-add-a-... |
47b3b6b94781b8cf6108feaab7dd83ba91a348da | xavier/KidsCode | /puissance4/pyssance4.py | 4,962 | 3.625 | 4 | # -*- coding: UTF-8 -*-
VIDE = " "
ROUGE = 'R'
JAUNE = 'J'
class Erreur(Exception):
pass
class ErreurDePosition(Erreur):
pass
class Grille:
"""
Grille de Puissance 4
Le système de coordonées de la grille est compris dans l'intervalle [0;7] pour les colonnes et [0;6] pour les lignes.
Les colon... |
5dd7ff7017f8bb50f4d14e29de71509f790a3b02 | dawn888/leetcode | /算法/设计链表.py | 6,624 | 4.15625 | 4 | class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class MyLinkedList:
def __init__(self):
"""
Initialize your data structure here.
"""
self.head=None
def get(self, index):
"""
Get the value of the index-th node in the lin... |
326d10133ac2ee0cda40c789e8fb8e0e4a375d82 | rodfmarin/adventofcode | /2022/13/main.py | 4,822 | 4.09375 | 4 | """
--- Day 13: Distress Signal ---
You climb the hill and again try contacting the Elves. However, you instead receive a signal you weren't expecting: a
distress signal.
Your handheld device must still not be working properly; the packets from the distress signal got decoded out of order.
You'll need to re-order the ... |
2a545ca3926075d6f6a7e0fdbbfc484aec780ffd | ramsandhya/Python | /ex13-argv.py | 1,154 | 4.21875 | 4 | from sys import argv
# script, first, second, third = argv
# print "The script is called", script
# print "The first variable is called ",first
# print "The second variable is called", second
# print "The third variable is called", third
# argv needs these arguments from the command line. The first argument will be th... |
64109eff0291d32e3cb457603fff1fc6ef0b8f0b | Iwontbecreative/Positive-tweets | /positive.py | 2,321 | 3.703125 | 4 | """
Those are functions that use REST api to check users timelines and add
them and check whether text is positive or negative about a topic.
"""
from __future__ import division
from string import punctuation
import tweepy
import credentials as c
from credentials import our_id
with open("positive.txt", "r") as pos:
... |
fb096545a310598d29d222842bb229e90324d67d | HamishBB/zomvennia | /typeclasses/rooms.py | 3,646 | 3.578125 | 4 | """
Room
Rooms are simple containers that has no location of their own.
"""
from evennia import DefaultRoom
from evennia import utils
from evennia import create_object
from characters import Character
class Room(DefaultRoom):
"""
Rooms are like any Object, except their location is None
(which is default... |
d63239b74444d9f366ed6c273a1b098f9e8b80f0 | albinjohn366/AI_Minesweeper_Game | /my_minesweeper.py | 2,739 | 3.875 | 4 | # MINESWEEPER GAME OUTLOOK
import random
class Minesweeper:
mine_number = None
def __init__(self, height=8, width=8, mines=15):
self.mine_number = dict()
self.full_set = set()
self.height = height
self.width = width
self.mines = set()
self.board = []
se... |
c40fdf6704940586bb8273a134458c04559e9a7d | mgoldey/hackerrank | /programming_interview_questions/fizzbuzz.py | 171 | 3.65625 | 4 | for i in range(1,1+int(input())):
ret_str=""
if i%3==0:
ret_str+="Fizz"
if i%5==0:
ret_str+="Buzz"
if ret_str=="":
print(i)
else:
print(ret_str)
|
6dee50a062a8efd25cd1a8eea0d470cb3048951f | clcsar/python-examples | /sum_of_squares.py | 208 | 3.53125 | 4 | square = (i*i for i in range(1000000))
#add the squares
total = 0
for i in square:
total += i
print total
#add the squares
total = 0
for i in (i*i for i in range(1000000)):
total += i
print total
|
5a89f63c90d9a791230a9cdeed72f9921642c008 | rafaelperazzo/programacao-web | /moodledata/vpl_data/303/usersdata/278/67409/submittedfiles/testes.py | 114 | 3.703125 | 4 | # -*- coding: utf-8 -*-
#COMECE AQUI ABAIXO
medida = float(input("medida: ")
print('centimetros eh medida*100') |
5e89bc180f370be3b5603300f1984a5cbb73fd05 | adyadyat/pyprojects | /lw/day12/day12_lw3.py | 506 | 4 | 4 | for i in range(8,0,-1):
for x in range(8,i,-1):
print(" ",end="")
for j in range(i,0,-1):
print(j,end="")
print(" ",end="")
print()
for i in range(8,0,-1):
for x in range(0,i-1):
print(" ",end="")
for j in range(8,i-1,-1):
print(j,end="")
print(" ",end="")
print()
"""
8 7 6 5 4 3 2 1
7 6 5 4 3 2 1
... |
e504e23de74b1e4bad0341b877f1095385a31754 | Adib234/Leetcode | /binary_tree_inorder_traversal.py | 1,090 | 3.921875 | 4 | # Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def inorderTraversal(self, root: TreeNode) -> List[int]:
# res, stack = [], []
# cu... |
76ab412292521cd218ebf6d26c3bd3fe8c8ca893 | kuangbiaodewoniu/calc_wage | /deal_csv.py | 861 | 3.609375 | 4 | # !usr/bin/env python
# -*- coding:utf-8 _*-
"""
@author:dandan.zheng
@file: deal_csv.py
@time: 2018/03/20
"""
import csv
class CSV(object):
def __init__(self, value):
self.file_path = value
def get_data(self):
try:
result = {}
with open(self.file_path, 'r') as... |
118115215f5fbd91d7e85287bcc46d8c787e3f18 | liviaerxin/zipline | /dual_moving_average.py | 3,869 | 3.515625 | 4 | #dual_moving_average.py
#!/usr/bin/env python
#
# Copyright 2014 Quantopian, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless... |
ab49dcf192d10b4a3a07bffb23c022c43a19f09b | airtonsiqueira/python-safaribooks-exercises | /Introduction to Python/Exercises/WebCrawler/scraper.py | 1,207 | 3.609375 | 4 | import os
import urllib.request
from urllib.parse import urljoin
from bs4 import BeautifulSoup
# Para cada arquivo, siga cada link, encontre a imagem e faça download
# Download fotos: urllib
# Parse e tratamento HTML: BeautifulSoup
# Links
index_page = 'https://apod.nasa.gov/apod/archivepix.html'
pasta_downl... |
2c58096eb133997121873eaa74584b72ae64a5b5 | SinanTang/MIT600 | /Lec5_in-class-exercise.py | 4,701 | 4.0625 | 4 | ## using bisection to approximate the square root of input number
def squareRootBi(x, epsilon):
"""
:param x: number to be squared
:param epsilon: the precision the square root expects to be
:return: the approximate square root of input x
"""
assert x >= 0, "x must be non-negative, not " + str(x... |
31fa244890654355ae00b4089c14014c8a4241b4 | pkovarsky/artem_p | /examples/_01_Python_Basics/_22_string_strip.py | 395 | 4.0625 | 4 | """String Manipulation"""
phrase = " Monty Python's Flying Circus "
print(phrase.strip()) # 'strip' removes whitespaces from both ends
# Monty Python's Flying Circus
print(phrase.lstrip()) # 'lstrip' removes leading characters (Left-strip)
# Monty Python's Flying Circus
print(phrase.rstrip()) # 'lstrip' re... |
ca679ffe84f7fed14407e4736ad210bf3b6b2b37 | vla3089/adventofcode | /2018/3.py | 1,441 | 3.546875 | 4 | #!/usr/bin/env python
import collections
fname = "input3.txt"
with open(fname) as f:
content = f.readlines()
content = [line.strip() for line in content]
# claim contract
# #1 @ 432,394: 29x14
def parse_claim(claim):
claim = claim[1:]
claim_id, rest = claim.split('@', 1)
left, rest = rest.split(',', ... |
5d7dca2b51494a3dd1574f52a992a8897fa097d3 | baby5/HackerRank | /DataStructures/LinkedList/TailInsert.py | 359 | 3.578125 | 4 | #coding:utf-8
#stupid
def Insert(head, data):
if head:
node = head
while node.next:
node = node.next
node.next = Node(data)
else:
head = Node(data)
return head
#smart
def Insert(head, data):
node = head
while node.next:
node = node.next
node.... |
a1e6219338ed0855e54e871bb365582d973c78a5 | GabrielYLT/DPL5211Tri2110-1 | /Lab 4/Lab 4.3.py | 230 | 3.734375 | 4 | # Create a while loop that displays I love Python 7 times
#Student ID: 1201200039
#Student Name: Tan Jiue Hong
word = 1
while (word <= 7 ):
print("I love phyton")
word = word + 1
for num in range(10):
print(num) |
fddd5224060a3a5fbb63b33f0a5a7c932f1d75b0 | ATinyLearner/PythonPractice | /test.py | 1,072 | 4.125 | 4 | #create a program for merge sort
user_input=input("Enter the elements of array:").split(",")
alist=[int(i) for i in user_input]
print("Given array is:")
print(alist)
le=len(alist)-1
def merge(a:list,start:int,mid:int,end:int):
n1=mid-start+1
n2=end-mid
l=[None]*n1
r=[None]*n2
k=0
# making temp l... |
9140cfe246e5c9f09e0049a21716a82b04a03819 | eriickluu/pywombat | /Mis ejercicios/Factorial/factorial.py | 132 | 3.703125 | 4 | def factorial(valor):
if valor == 1:
return valor
else:
return valor * factorial(valor-1)
print(factorial(4))
|
a0ae3027a1cf8816049b90ef74df57bb1757f9a5 | muman613/bookshelf | /python/sandbox/test_obj.py | 377 | 3.6875 | 4 |
class Book:
data = {}
def __init__(self, value1: str, value2: int):
self.data = {}
self.data["value"] = value1
self.data["int"] = value2
def __repr__(self):
return "{{ {}, {} }}".format(self.data["value"], self.data["int"])
myBook_1 = Book("stringvalue", 10)
myBook_2 = B... |
e0ec6c235042de5a30abcdeabc175aac1d0c8e8b | mguomanila/programming_tests | /lesson5/countdiv.py | 1,178 | 3.9375 | 4 | '''
Task
Write a function:
def solution(A, B, K)
that, given three integers A, B and K, returns the number of integers within the range [A..B] that are divisible by K, i.e.:
{ i : A ≤ i ≤ B, i mod K = 0 }
For example, for A = 6, B = 11 and K = 2, your function should return 3, because there are three numbers divisi... |
6ef96375c12d962aef6b7472846de7f9bbf5b0d1 | ricklixo/estudos | /DSA_Break.py | 761 | 3.875 | 4 | # Utilizando BREAK e PASS para interromper ou continuar o loop.
counter = 0
while counter < 100:
if counter == 4:
break
else:
pass
print(counter)
counter += 1
# Utilizando continue para pular a letra H e dar prosseguimento a verificação
for verificador in 'Python':
if ve... |
272bca04a591ae32d58f18c7ea86eb45d390897a | youaresherlock/PythonPractice | /python核心技术与实战/16/函数参数传递.py | 1,046 | 4.28125 | 4 | #!usr/bin/python
# -*- coding:utf8 -*-
"""
python里的参数传递: 共享传参(对象的引用传递)
"""
if __name__ == "__main__":
# 变量及赋值
a = 1
b = a
a = a + 1
print(a, b)
# 列表赋值
l1 = [1,2,3]
l2 = l1
l1.append(4)
print(l1)
print(l2)
# 函数参数传递
def my_func1(b):
b = 2
a = 1
my_fun... |
bf8807a56c9d5f4af11300ced17cee53788928b2 | mattfeng/rosalind | /hamm/hamm.py | 574 | 3.546875 | 4 | #!/usr/bin/env python
"""
hamm.py
Counting point mutations
========================
"""
import argparse
def hamming(s, t):
dist = 0
for a, b in zip(s, t):
if a != b:
dist += 1
return dist
def main(fname):
with open(fname) as f:
seq1 = f.readline().strip()
seq2 =... |
4829a6af35b0305f21d81c46aad8aae6ac611d3f | shanksms/python-algo-problems | /arrays/add_two_numbers.py | 535 | 3.734375 | 4 | def add_two_arrays(A, B):
if len(A) > len(B):
B = [0] * (len(A) - len(B)) + B
else:
A = [0] * (len(B) - len(A)) + A
#this will hold the result
C = [0]*len(A)
#carry
c = 0
for i in reversed(range(len(A))):
sum = A[i] + B[i] + c
c = 0
if sum >= 10:
... |
0b3340ecacdb60aae18a17a3bfa5ad7f1380dc6a | fancy84machine/Python | /Projects/Cleaning Data in Python/Ebola+Melt%2C+Split%2C+Assert.py | 1,816 | 3.65625 | 4 |
# coding: utf-8
# In[1]:
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
ebola = pd.read_csv ('ebola.csv', header=0)
# In[2]:
ebola.columns
# In[3]:
#Splitting a column with .split() and .get()
# Melt ebola: ebola_melt
ebola_melt = pd.melt(e... |
f8b54b4dc408b8d7a4480c50a908c6538a76dc22 | LockeShots/Learning-Code | /training_task_9_-_fibonacci_sequence.py | 378 | 4.1875 | 4 | #Generate the fibonacci sequence
def fibseq(limit):
"""
>>> fibseq('10')
0, 1, 1, 2, 3, 5, 8, 13, 21, 34
"""
fiblist = list()
fiblist.append(i+(i+1) for i in range(0, (limit)))
return(fiblist)
if __name__ == '__main__':
limit = int(input("To how many digits would you like to determine ... |
57d465357b45b1ef37ba49ac257158a2b463779b | engtim/Python2021-Introduction | /Assignment2.py | 1,051 | 4.28125 | 4 | # Enter your first and last names
print("Enter First and Last Name: ")
first_name = input("First name: ")
last_name = input("Last name: ")
fullnames = first_name + " " + last_name
# Enter your country of origin
print("Enter your country of origin: ")
country = input("Country: ")
# Enter the nature of your current job... |
9e1c327ab5ba2c58b106897c78eb3e580dca9de5 | Harshad-Chavan/Python_OOPS | /mar_exploration.py | 404 | 3.609375 | 4 | s = 'SOSOOSOSOSOSOSSOSOSOSOSOSOS'
n = 3
def divide_chunks(l, n):
for i in range(0, len(l), n):
yield l[i:i + n]
def marsExploration(s):
count = 0
for part in list(divide_chunks(s, n)):
if part[0] != 'S':
count += 1
if part[1] != 'O':
count += 1
... |
921ca99f41d6d2d5b9700ec0c0c60547984bcd81 | pdefusco/Python | /app_development/lpth/ex40.py | 206 | 3.5 | 4 | #practice classes:
class MyClass():
def __init__(self):
self.var1 = "var1"
def method(self):
print("this method prints this text")
obj1 = MyClass()
obj1.method()
print(obj1.var1)
|
b8ea6a78dbb3d0ba8253e2b0c8c2dacb037a84d0 | xiaodchen/NomNomNow | /Problem1/payment_api.py | 620 | 3.609375 | 4 | # Use this mock API as-is for charging an amount.
# No code in this file should be changed.
import random
class Error(Exception):
"""Base exception class."""
class ChargeFailedError(Error):
"""Raised when a charge fails for whatever reason. Who knows? Not me."""
def Charge(amount):
"""Attempts to charge ... |
ce688de3fa16d6a4660e947af1663abedc1ede0d | Okemp-1/geekbrains-ai-python1 | /Lesson_2/GeekBrains_AI_Strzhelinsky_Python_2-2.py | 1,374 | 4.25 | 4 | '''
2. Для списка реализовать обмен значений соседних элементов,
т.е. Значениями обмениваются элементы с индексами 0 и 1, 2 и 3 и т.д.
При нечетном количестве элементов последний сохранить на своем месте.
Для заполнения списка элементов необходимо использовать функцию input().
'''
el_count = int(input("Введите количест... |
064c1b2f379e9ab6c44b3d04bce149bcdbeab30d | deanrobertcook/job-scraper | /tools.py | 1,723 | 3.890625 | 4 | def dict_depth(d):
"""Return the depth of a dictionary"""
if type(d) is dict:
return 1 + (max(map(dict_depth, d.values())) if d else 0)
return 0
def flatten_json(nested_json, exclude=[''], drop_lone_keys=False):
"""Flatten json object with nested keys into a single level.
Credit: https:... |
49d18c3a615ed7d8024faf8e2d3d98196a390af3 | sash7410/coding | /OOPS.py | 4,907 | 4.46875 | 4 | #OOPS
#%%%
#the class Person has 2 attributes - name and the method say_hi
#an object p is created by calling the class
#every method/func in the class passes the object as the first argument
#the object p is passed as the 1st arg to the say_hi method
class Person:
name = "abc"
def say_hi(self):
p... |
5366b770e6281f7222a95492a2fb28c9b699562f | jonahswift/pythonStudy1 | /firstDay/studySanYuanBiaoDaShi.py | 93 | 3.78125 | 4 | #三元表达式
a=1
b=2
if a>b:
c=a
else:
c=b
print(c)
c=a if a>b else b
print(c) |
464e043185de062b640576a21a16cda902927633 | Moeyinoluwa/tip-calculator | /main.py | 674 | 4.3125 | 4 | print("Welcome to the tip calculator!")
# ask for the total bill
total_bill = float(input("What was the total bill? \n$"))
# ask for the % tip
tip = int(input("What percentage tip would you like to give? \n"))
percentage_tip = tip / 100
# multiply total bill by % tip, add the result to the total bill
final_bill = (tota... |
caed6ffa1ea3ec0c81470b7c162b46ba5ddc2285 | genemalkin/geneveo_utils | /wave_freq.py | 5,959 | 3.578125 | 4 | #
# Simple calculator from wavelengths and frequencies of electromagnetic waves
# This calculator is used among other things for the work for the Standards Committee.
#
import argparse
import sys
supported_units_wave = ['nm', 'um', 'mm', 'm']
supported_units_freq = ['Hz', 'kHz', 'MHz', 'GHz', 'THz']
class EMConver... |
f4132a22dafcd5de091efcdf571355260a1613f8 | doraeball22/Python-for-kids | /1.data_type.py | 3,544 | 4.1875 | 4 | # ชนิดข้อมูล
# 1.Number แบ่งออกเป็น 1.1 จำนวนเต็ม 1.2 จำนวนจริง
integerNumber = 102 # จำนวนเต็ม (integer)
flotingPointNumber = 10.5 # จำนวนจริง เป็นทศนิยม (Floating point)
# + - * / % //
num1 = 9
num2 = 2
print("num1 + num2 = {}".format(num1+num2))
print("num1 - num2 = {}".format(num1-num2))
print("num1 * num2 = {}"... |
7390c61245dd220d6047e3ec5d7e9600c008a003 | aharri64/python_scripting | /Recursion/pretty_print.py | 700 | 4.46875 | 4 | # Pretty print a dictionary structure
# Input: A dictionary and a string
# Output:
# Purpose: Pretty print a dictionary structure
def pretty_print(dictionary, indent=""):
# iterate through every key in the dictionary
for key in dictionary:
# get the value associated with the key
val = dictionar... |
a4958b9bb1e0eb6b727842106ab917848b342bfb | lizzzcai/leetcode | /python/backtracking/0051_N-Queens.py | 5,574 | 4.09375 | 4 | '''
26/03/2020
51. N-Queens - Hard
Tag: Backtracking
The n-queens puzzle is the problem of placing n queens on an n×n chessboard such that no two queens attack each other.
Given an integer n, return all distinct solutions to the n-queens puzzle.
Each solution contains a distinct board configuration of the n-quee... |
ea2064d4f281bb8cc353af8d43cad0915efba640 | chrisdawww/adventofcode2020 | /9/xmas.py | 1,309 | 3.765625 | 4 | """
Day 9
XMAS "encryption"
Part 1: Find the first number where there aren't two numbers in the previous
25 which sum to it
Part 2: Find a contiguous set of numbers which add to the target found from
the first part
"""
def part1(nums):
for i in range(len(nums)):
preamble = nums[i:i+25]
target = num... |
7c408ca7f0d13764d71d8f6cd1c934a3ef8fd557 | Sukhrobjon/CS-2.1-Trees-Sorting | /Code/prefixtree.py | 9,340 | 4.28125 | 4 | #!python3
from prefixtreenode import PrefixTreeNode
class PrefixTree:
"""
PrefixTree: A multi-way prefix tree that stores strings with efficient
methods to insert a string into the tree, check if it contains a matching
string, and retrieve all strings that start with a given prefix string.
Time c... |
57aec935fccd0d5010e033999fe73216b13f2369 | danitrave/BurrowsWheelerTransform | /BURROWS_WHEELER_TRANSFORM/bwt.py | 12,380 | 4.28125 | 4 | ##This algorithm is the implementation of the one for a Burrows-Wheeler transform that allows to convert the genome sequence in a compact string.
##The algorithm must be run on the terminal using python version 3.7 to have a more clear and user-friendly visualization.
##The program asks the user to insert a genome str... |
7bb20b96667672cbe7939d7757e67ca78970bc41 | zhouxinmin/Strip-Packing-Problem | /daily/study/practise/shixi/test.py | 1,795 | 3.5625 | 4 | # ! /usr/bin/env python
# -*- coding: utf-8 --
# ---------------------------
# @Time : 2017/3/10 19:03
# @Site :
# @File : test.py
# @Author : zhouxinmin
# @Email : 1141210649@qq.com
# @Software: PyCharm
import sys
import copy
# num = sys.stdin.readline().strip()
# num_list = list(num)
# real_num = 0
# f... |
5709a20758e62ec61a63865bfbb1e71afb9a5964 | bong1915016/Introduction-to-Programming-Using-Python | /evennumberedexercise/Exercise11_02.py | 497 | 3.71875 | 4 | def main():
matrix = []
for i in range(4):
s = input("Enter a 4-by-4 matrix row " + str(i) + ": ")
items = s.split() # Extracts items from the string
list = [ eval(x) for x in items ] # Convert items to numbers
matrix.append(list)
print("Sum of the elements ... |
13ff45bda1f369d31a7997dbbca9c5a99bb0e7b5 | DropthaBeatus/Python_GameMaster | /Game_Time/Pieces.py | 822 | 3.625 | 4 | import random
import copy
import json
class Card:
def __init__(self, value, suite, card_name, code, color):
self.value = value
self.suite = suite
self.card_name = card_name
self.code = code
self.color = color
class Deck:
cards = []
def __init__(self):
wit... |
78a4623a68ac759093d7740ec6bf2ce9cbe37fe7 | ErnestoDibia/Team-Sanger | /Gladys_python.py | 711 | 3.65625 | 4 | #!/usr/bin/env python3
#Defining my variables
#Name
Name = "Gladys Rotich"
#Email address
Email_address = "gladysjerono86@gmail.com"
#Slack username
Slack_username = "@Gladys"
#Preferred biostack
Biostack = "Genomics, Data Science"
#Twitter handle
Twitter="@jerono7_gladys"
#Finding the hamming distance
def hammi... |
dea54043661a6a0bd7cceb73f427c982965b59eb | kritikyadav/Practise_work_python | /if-else/ifelse6.py | 174 | 4 | 4 | a=int(input('year= '))
if a%4==0 and a%100==0:
print('is a leap year')
elif a%4==0 and a%100!=0:
print('is a leap year')
else:
print('is not a leap year')
|
2e2e5aff1e814d7942bb81d078d932a7f586def6 | GudiedRyan/day_1 | /main.py | 2,225 | 4.21875 | 4 | MENU = {
"espresso": {
"ingredients": {
"water": 50,
"milk": 0,
"coffee": 18,
},
"cost": 1.5,
},
"latte": {
"ingredients": {
"water": 200,
"milk": 150,
"coffee": 24,
},
"cost": 2.5,
},... |
667134240639a296d1ddbeae3b4743684fa6542b | mashpolo/leetcode_ans | /500/leetcode506/ans.py | 845 | 3.546875 | 4 | #!/usr/bin/env python
# coding=utf-8
"""
@desc:
@author: Luo.lu
@date: 2018-11-16
"""
class Solution:
def findRelativeRanks(self, nums):
"""
:type nums: List[int]
:rtype: List[str]
"""
nums_bak = sorted(nums)
map_rs = {}
for (index, x) in enumerate(nums_b... |
11d41b600ae5aaf0d16df22ca822940e80e4f484 | jeen0404/Text-to-speech-python | /entertext.py | 1,387 | 4.03125 | 4 | from gtts import gTTS
from playsound import playsound
import playmp3
#here you can add wellcome sound
'''
wellcome=""
playsound(wellcome)
'''
#this function is use to take input from user
def entertext():
text=str(input("enter the text"))
return text
#this is our main function it convert str... |
5a515700c6a379d58b4033c64b80b4d3959dcaa1 | wp6530/studypython | /01python基础/进程线程协程/线程04线程同步.py | 1,108 | 3.671875 | 4 | # -*- coding = utf-8 -*-
import threading
import time
import random
# lock = threading.Lock()
# list1 = [0] * 10
#
#
# def task1():
# # lock.acquire()
# for i in range(len(list1)):
# list1[i] = 1
# time.sleep(0.5)
# # lock.release()
#
#
# def task2():
# # lock.acquire()
# for i in r... |
0ab27fcc067c8d104f58fe80f9abb60768921b67 | mauricio-velasco/min-cross-entropy | /optimalTransports.py | 13,959 | 3.765625 | 4 | '''
Created on May 14, 2021
@author: mvelasco
'''
import numpy as np
import pdb
import time
import numpy as np
import matplotlib.pyplot as plt
class Empirical_Measure:
"""
An empirical measure is determined by a list of data points (self.data_vectors)
in some R^n. n=self.dim. Represents the sum of Dirac ... |
e708a4ff294f9296bbbe05413894c4a96604a106 | cp-helsinge/2020-attack | /common/tech_screen.py | 1,897 | 3.546875 | 4 | """============================================================================
Tech screen
Create a transparent overlay display of internal values usefull for game
development and debuging
Activare in-game with F3
============================================================================"""
import p... |
4bc5292f05f9fddcc8b792169b9733040be6a318 | msn322/Python | /Ericsson-Python/decorators2_check.py | 1,101 | 3.65625 | 4 | '''
Write a decorator that decorates functions that take a variable number of numeric values
and returns 4 numeric values.
'''
from __future__ import division
def check(func):
def ifunc(*numbers):
if not all( isinstance(number, (int, float)) for number in numbers):
raise TypeError('all paramet... |
333b8016fc41cd485cfd0849140b3554a8141876 | andersontmachado/Python_na_PRATICA | /Ex051-Progressão Aritmetica ou uma PA.py | 201 | 3.75 | 4 | primeiro=int(input('Primeiro Termo: '))
razao=int(input('A razão: '))
decimo=primeiro+(10-1)*razao
for c in range (primeiro,decimo+razao,razao):
print('{}'.format(c),end= '->')
print('ACABOU')
|
ee731b059372d40a750b8f02fe7ced4f0a2036ce | SamShepp/Practicals-2018 | /prac_05/hex_colours.py | 559 | 4.09375 | 4 | """
CP1404 Practical
Hexadecimal colour lookup
"""
COLOUR_CODES = {"AliceBlue": "#f0f8ff", "Blue1": "#0000ff", "BlueViolet": "#8a2be2",
"Brown": "#a52a2a", "CadetBlue1": "#98f5ff", "Chartreuse1": "#7fff00",
"Chocolate": "#d2691e", "Coral": "#ff7f50", "CornFlowerBlue": "#6495ed",
... |
93db7022345dfc4903ead4812529a98e10e2397e | qiaozhi827/leetcode-1 | /04-栈_队列_优先队列/4-队列和广度优先遍历/01-102.py | 1,105 | 3.796875 | 4 | # 二叉树的层次遍历
# 使用队列
from leetcode.tree_node import TreeNode, get_binary_tree
class Solution(object):
def levelOrder(self, root):
"""
:type root: TreeNode
:rtype: List[List[int]]
"""
if root is None:
return []
res = []
queue = [root]
... |
8d5cc3d56604c2915b441de5df2fb56f580ca0a6 | s-ferdousy/Codeforces19 | /1335A - Candies And Two Sisters.py | 105 | 3.59375 | 4 | import math
t=int(input())
while(t>0):
n=int(input())
print (math.floor((n - 1) / 2))
t=t-1 |
a866463640bf268dc00ece18ea037e28c70cb05c | Manjuguna/pythonpractice | /Q60.py | 69 | 3.59375 | 4 | x=int(input(""))
su=0
for i in range(1,x+1,1):
su=su+i
print(su)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.