blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
f8a5ca7f60934fb810cc0e799525bc47e1e14baa | shoebot/toybot-scenegraph | /toybot/languages/toybot.py | 813 | 3.625 | 4 | """Code specific to the ToyBot language."""
from typing import Optional, Tuple
from toybot.scenegraph import Path, SceneGraph
Color = Tuple[float, ...]
class ToyBot:
"""Minimal Bot language."""
def __init__(self, graph: SceneGraph) -> None:
"""Attach SceneGraph instance for the bot to output graphi... |
2d89347ab0240f2fe4a95ef37ffe3caf5225f030 | daniel-reich/turbo-robot | /vQgmyjcjMoMu9YGGW_14.py | 1,100 | 4.625 | 5 | """
Create a function that returns the simplified version of a fraction.
### Examples
simplify("4/6") ➞ "2/3"
simplify("10/11") ➞ "10/11"
simplify("100/400") ➞ "1/4"
simplify("8/4") ➞ "2"
### Notes
* A fraction is simplified if there are no common factors (except 1) between the n... |
d6944c5fde2dbdc96912db0a98b8652c27e0594c | kechol/exercise | /atcoder/arc002_4/a.py | 1,546 | 3.734375 | 4 | #!/usr/bin/env python
import sys
class BoardGame:
def __init__(self, h, w, b):
self.h = h
self.w = w
self.board = b
def judge(self):
while self.move('o', 1):
if not self.move('x', -1):
return True
return False
def move(self, p, d):
#... |
b788b40efa1b8ca99eab89956febc37900df2672 | elice-python-coding/ESNG_season2 | /String_operate/p1.py | 293 | 3.78125 | 4 | def isPalindrome(s):
answer = "true"
sl = s.lower().strip()
s_arr = list(filter(lambda i:i.isalnum(), sl))
leng = len(s_arr)
for i in range(leng//2):
if s_arr[i] != s_arr[leng - 1 - i]:
return "false"
return answer
print(isPalindrome("race a car")) |
70b39e20cb5564ba76c81810f2c703915fc4b150 | LenKIM/implements | /archive-len/hackerrank/warm-up/repeated-string.py | 866 | 3.75 | 4 | #!/bin/python3
import math
import os
import random
import re
import sys
# Complete the repeatedString function below.
def repeatedString(s="abc", n=10):
#abc_list = "".join(["abc"] * 7)
#abc_string = abc_list[:10]
#"abc abc abc abc abc abc abc ..."
# 10 개
a_len = len(s)
a_mod_n = n / a_len... |
2b98be94167213b1bf5117b7124670c679a2e3b1 | howsoft/myarchive | /python scripts/Python Scripts/PYMOM/modules/drag1.py | 9,018 | 3.5 | 4 | import functions
import textfunctions
import os
import shutil
resources = ["matrix.png"]
# -------- START OF makeXmlFromText() -------------------- #
def makeXmlFromText(lines, questionClass):
questionType = ""
answerOrder = ""
height = ""
paragraphs = []
labels = []
def outputParagraphs():
newstring = ""
... |
7ab4c9b92dc6fb1591658ec47eeee8c8708d8a43 | laohou/Leetcode | /Permutations II.py | 827 | 3.546875 | 4 | class Solution(object):
def permuteUnique(self, nums):
"""
:type nums: List[int]
:rtype: List[List[int]]
"""
self.result = []
nums = sorted(nums)
self.recurPermute(nums, 0, len(nums))
return self.result
def recurPermute(self, nums, l, r):
... |
09315777768cf339bfb073be9bf320520e2a88c5 | sammthomson/one_tough_puzzle | /puzzle.py | 5,188 | 3.578125 | 4 | """ Script to solve "One Tough Puzzle" a.k.a. "Impuzzable"
as seen at http://nrich.maths.org/1388
Author: Sam Thomson
Date: 1/1/2012
"""
HEART, CLUB, DIAMOND, SPADE = "hcds"
NUM_ROWS = 3
NUM_COLS = 3
NUM_PIECES = NUM_ROWS * NUM_COLS
PIECE_WIDTH = 16 # in characters, for printing
# enumeration of sides of all pieces, c... |
3fca63b541572c55967d635bd1f7413440339695 | Avenger98/Python-Programms | /IfTaskTriangularSides.py | 429 | 4.25 | 4 | num1 = float(input("Enter the first number: "))
num2 = float(input("Enter the second number: "))
num3 = float(input("Enter the third number: "))
if num1 + num2 > num3:
if num1 + num3 > num2:
if num2 + num3 > num1 :
print("It can be triangular")
else:
print("can not ... |
decd574e0de6f2738be2441b83e35ed6dc24f8b4 | jingfei510/PythonProjects | /class2.py | 250 | 3.65625 | 4 | class Car:
color = ' '
valu = ' '
gar = ' '
def __init__(self,color,valu,gar):
self.color = color
self.valu = valu
self.gas = gas
def buy (self):
print('i have so much money')
bob = Car()
|
ce281299507e4cae4cdaa9a3f30122690ab64a67 | douradodev/Algoritmos-ADS | /ALG_2019_VICTOR_DOURADO-20210622T123110Z-001/ALG_2019_VICTOR_DOURADO/Atividade_Fabio02a/Fabio02a_19_IMC.py | 263 | 3.84375 | 4 | def main():
altura = float(input("Digite sua altura: "))
peso = float(input("Digite seu peso: "))
imc = peso / (altura**2)
if imc < 25:
print("IMC NORMAL")
elif imc >= 25 and imc <= 30:
print("PESSOA OBESA")
else:
print("OBESIDADE MORBIDA")
main() |
cb8691e27b64d07c203c359fdbbbe0a230f43f36 | ipython/ipyparallel | /docs/source/examples/itermapresult.py | 2,295 | 3.75 | 4 | """Example of iteration through AsyncMapResults, without waiting for all results
When you call view.map(func, sequence), you will receive a special AsyncMapResult
object. These objects are used to reconstruct the results of the split call.
One feature AsyncResults provide is that they are iterable *immediately*, so
y... |
44038f3653393be00861c4912392f8aa8f4c4879 | littlespeechless/leetcode | /21/main.py | 1,414 | 3.890625 | 4 | # Definition for singly-linked list.
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
class Solution:
def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode:
# c1 = l1
# c2 = l2
# s = None
# head = None
# whi... |
12757559c07042fe9496e683d70fdda191738eb6 | raymond30031/playground | /robotics/line_fitting/least_square_curve_fit.py | 622 | 3.59375 | 4 | # Curve fitting with non-linear least square method
# Note: Must know the fitting function in advance
# Reference: https://docs.scipy.org/doc/scipy/reference/generated/scipy.optimize.curve_fit.html
import numpy as np
from scipy.optimize import curve_fit
# Assumes ydata = f(xdata, *params) + eps
# Num of points
num = ... |
98f1e74c440c182ee9c81ed5197410c57864da2d | joelmedeiros/studies.py | /Fase13/Challange50.py | 158 | 4.125 | 4 | sum = 0
for i in range(0, 6):
number = int(input('Write a number: '))
if (number % 2 == 0):
sum += number
print('The total is {}'.format(sum)) |
e5ab6f2e1f2a058b61f46b065670ec6d5591e50f | fatemameem/CSE220_BRACUSpring2021 | /Lab/assignment 2.py | 3,927 | 3.9375 | 4 | -*- coding: utf-8 -*-
"""
Created on Wed May 12 00:53:08 2021
@author: Meem
"""
def exponential(m,n):
if n==0 or n==1:
return m
else:
return m*exponential(m,n-1)
pass
print(exponential(3,2))
class Trace:
def hMB(self,h):
if (h==0):
print("Stop: ",... |
19b98d0e1dc6acd5bb5b2a883e425a15877e1570 | sssvip/LeetCode | /python/num004.py | 2,876 | 3.9375 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Date : 2017-09-29 18:23:23
# @Author : David:admin@dxscx.com
# @Link : http://blog.dxscx.com
# @Version : 1.0
"""
There are two sorted arrays nums1 and nums2 of size m and n respectively.
Find the median of the two sorted arrays. The overall run time complexity... |
1e2cd8ce5ece71a9eb6e695cd4b4e9bcf83a8d18 | wombywill/Coding-partner-assignments | /7 7 data visualization soeng.py | 2,313 | 3.734375 | 4 | def checkCommas(dataPoint):
if ',' not in dataPoint:
print('Error: No comma in string.')
return False
elif dataPoint.count(",") > 1:
print('Error: Too many commas in input.')
return False
else:
index = dat... |
853d1228c29be67a3582de3a19c485e57755bb55 | Crone1/College-Python | /Year One - Semester Two/Week Four/swap_v1_042.py | 248 | 3.546875 | 4 | def swap_keys_values(d):
keys = []
values = []
dic = {}
for k, v in d.items():
keys.append(k)
values.append(v)
i = 0
while i < len(values):
dic[values[i]] = keys[i]
i = i + 1
return dic |
0a0d7544453850fd688796ab3003f23a49e8b7a0 | vlad-bezden/py.checkio | /scientific_expedition/seven_segments.py | 2,914 | 4.03125 | 4 | """Seven Segments.
https://py.checkio.org/en/mission/seven-segment/
You have a device that uses a Seven-segment display to display 2 digit numbers.
However, some of the segments aren't working and can't be displayed.
You will be given information on the lit and broken segments.
You won't know whether the broken segme... |
bab4132702a9523be7535168068bb2d2d7c765ed | milanix13/COVID-19 | /src/analysis.py | 8,652 | 3.734375 | 4 | '''Code for analysis of data'''
from data_munging import *
from plotting import *
import scipy.stats as stats
import numpy as np
def death_case_frequency(total_death_case, total_cases):
'''Inputs: total_death - total # covid deaths proportional to population
total_cases - total # covid cases propor... |
17ee81e31a20a2c1cae4dd44dbe6053958f35301 | Kiranathas/Python-para-no-programadores | /uno_al_diez.py | 379 | 3.875 | 4 | # ~ pide un numero por teclado y guarda en una lista su tabla de multiplicar hasta el 10
lista= []
numero = int(input("ingrese un número: "))
contador = 1
while contador <= 10:
lista.append(numero * contador)
contador += 1
print(lista)
#otra forma
for n in range (1,11): #paso el 11 porq es último ... |
51aa6f91d46e03e7973acb8715b1f0991ba02729 | MatthewReganPgr/Python-Programs | /Hangman.py | 5,716 | 4.0625 | 4 | #201278659 Regan_Matthew-CA05
#11/2017
#Hangman game
import random
import re
#Declaring variables
animalList = 0
furnitureList = 0
foodList = 0
guesses = 0
correctGuesses = 0
incorrectGuesses = 0
remainingGuesses = 0
previousGuesses = 0
emptyWord = 0
finalGuess = 0
letterOccurance = 0
indexOfGuess ... |
797643788b0f7bbf47bc2a3f75286f3c4521b471 | Aiooon/MyLeetcode | /python/offer_18_deleteNode.py | 1,295 | 3.796875 | 4 | """
剑指 Offer 18. 删除链表的节点
给定单向链表的头指针和一个要删除的节点的值,定义一个函数删除该节点。
返回删除后的链表的头节点。
注意:此题对比原题有改动,原题要求在 O(1) 时间复杂度内
示例 1:
输入: head = [4,5,1,9], val = 5
输出: [4,1,9]
解释: 给定你链表中值为 5 的第二个节点,那么在调用了你的函数之后,该链表应变为 4 -> 1 -> 9.
示例 2:
输入: head = [4,5,1,9], val = 1
输出: [4,5,9]
解释: 给定你链表中值为 1 的第三个节点,那么在调用了你的函数之后,该链表应变为 4 -> 5 -> 9.
说明:... |
e8b78f3b71bbf316843f6631c2df527d2040db27 | PeteSpangler/UD_DS_A | /P2/Sorting_Algorithms/pairsum.py | 902 | 4.125 | 4 | """
Given an input array and a target value (integer), find two values in the array whose sum
is equal to the target value. Solve the problem without using extra space. You can assume
the array has unique values and will never have more than one solution.
"""
def pair_sum(arr, target):
# sort the list
arr.sor... |
6ebdc698b876fef8bf858ffaa499077616ea7765 | rociotrevino/Prueba | /Tarea 2-2 Contraseña.py | 343 | 3.9375 | 4 | #Programa que almacena una cadena de caracteres (contraseña) y pregunta al usuario por la contraseña, e imprima si coincide o no
contra="hola"
nuevacontra=str(input("Escriba la contraseña : "))
nuevacontra=nuevacontra.lower()
if (contra==nuevacontra.lower()):
print("Contraseña válida")
else:
print("Contr... |
e3220fab09ca197e39dbda429c72665a80cb4d7f | fitzscott/BattleCruisers | /SmarterComputerPlayer.py | 2,015 | 3.703125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Thu Mar 30 21:25:00 2017
@author: bushnelf
"""
import random
import RandomComputerPlayer as rcp
class SmarterComputerPlayer(rcp.RandomComputerPlayer):
"""
SmarterComputerPlayer - weight card plays toward cards seen
in other players' recovery zones.
Only slight... |
4e6551d2b62f358b6fc225cd807c838c309dd800 | pranaylobo/Team-Kalm-CP | /Hackerearth/Recursion/Easy/Python/ItsConfidential.py | 358 | 3.84375 | 4 | import sys
def middle_char(txt,mid1):
if len(txt)>0:
mid = int((len(txt) - 1)/2)
print(txt[mid],end="")
middle_char(txt[:mid],mid1)
middle_char(txt[mid+1:],mid1)
mid1=0
for i in range(int(input())):
x1=int(input())
text=input()
var=midd... |
258ae6b1f08cc27a5e3f956e02880dfdb2ecfb2b | Zheaoli/pypractice | /a.py | 1,946 | 3.546875 | 4 | # encoding: utf-8
"""
@version: ??
@author: lizheao
@contact: lizheao940510@gmail.com
@software: PyCharm
@file: a.py
@time: 23:38
"""
class Grade(object):
def __init__(self):
self._score = 0
def __get__(self, instance, owner):
return self._score
def __set__(self, instance, value):
... |
69ab1262bb7688b3651ecbe05a21d5913738d204 | molaksh/PythonProjects | /MatPlotLib PyPlot/Sample 1.py | 1,501 | 4.125 | 4 | import matplotlib
import random
matplotlib.use('TkAgg')
import matplotlib.pyplot as plot
# plot values
#CHANGES: change the x, y1 and y2 values. You can enter the numbers by hand, use the range function or a random function.
# len(x), len(y1) and len(y2) must be at least 8 - done
x = list(range(0,8))
y1 = list(random... |
58ce208d8ee73b505a0eac835b04f6a8740fbaa5 | nkuraeva/python-exercises | /week7/sales.py | 485 | 3.609375 | 4 | with open('input.txt') as inFile:
myDict = {}
for line in inFile:
Name = str(line.split()[0])
product = str(line.split()[1])
quantity = int(line.split()[2])
if Name not in myDict:
myDict[Name] = myDict.get(Name, {})
myDict[Name][product] = myDict[Name].get(pro... |
e9661e1237403e3a97a44b4c302e1157f378325c | cody1984/Titanic | /Titanic.py | 1,124 | 3.78125 | 4 | """ Feature engineering of Titanic data set"""
import pandas as pd
import numpy as np
train = pd.read_csv('train.csv')
df = train
# print(df.head(10))
# https://stackoverflow.com/questions/19913659/pandas-conditional-creation-of-a-series-dataframe-column
# New column to show group status
conditions = [
(df['Si... |
9551bb1477b895108323761196046179544218c3 | mysantos/exercicio-python | /validar.py | 232 | 4.09375 | 4 | numero = None
while numero is None:
try:
numero = int(input("Digite uma numero: "))
pt ValueError:
print("Erro: Digite um numero")
print(f"O numero digitado foi {numero}")
|
7b208a9917c18d06a3db2c800a582a35b3dfd79b | wwwwodddd/Zukunft | /atcoder/abc238_d.py | 121 | 3.53125 | 4 | for t in range(int(input())):
a,s=map(int,input().split())
if s<2*a or (s-2*a&a)>0:
print('No')
else:
print('Yes') |
5d28d1bab2dfc9617b2dcd9da88f0b79ea6e88ae | mhmtnzly/Class5-Python-Module-Week6 | /main.py | 2,025 | 3.828125 | 4 | from client import Client
from bank import Bank
import time
b1=Bank(input('Name of Bank: '))
available=True
while available:
print("Welcome to {}".format(b1.name))
print("""Choose an option:
1. Open new bank account
2. Open existing bank account
3. Exit
""")
choice=int(i... |
12b26ccf928be98c313878d93146f5c4e00a7f3d | s-surineni/atice | /alien_dict.py | 1,590 | 3.875 | 4 | # https://practice.geeksforgeeks.org/problems/alien-dictionary/1
from collections import defaultdict
class Graph:
def __init__(self, num_of_vertices):
self.graph = defaultdict(list)
self.num_of_vertices = num_of_vertices
def add_edge(self, start, end):
self.graph[start].append(end)
... |
554b6a60f0ce12acadbc4ed27d349fb4c37f04b1 | Soist/waste_sorter | /Activity2/Milestone1.py | 1,823 | 3.65625 | 4 |
import cv2
import numpy as np
uppLeft = None
lowLeft = None
uppRight = None
def mouseResponse(event, x, y, flags, param):
"""This function is a callback that happens when the mouse is used.
event describes which mouse event triggered the callback, (x, y) is
the location in the window where the event happ... |
a8c59df19273a7baa34e28e76a3711077a219ac2 | alexandru-dinu/competitive-programming | /leetcode/letter_combinations_of_a_phone_number.py | 385 | 3.578125 | 4 | # https://leetcode.com/problems/letter-combinations-of-a-phone-number
from itertools import product
class Solution:
def letterCombinations(self, digits: str) -> List[str]:
if not digits:
return []
ds = [None, None, "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"]
ret... |
f31770932b862c9fae3c71c628bcded24f6c561a | noahjillson/Project-Euler | /problem4.py | 741 | 3.953125 | 4 | # 2520 is the smallest number that can be divided by each of the numbers from 1 to 10 without any remainder.
# What is the smallest positive number that is evenly divisible by all of the numbers from 1 to 20?
class Problem_5:
def __init__(self, max_divisor: int):
self.max_divisor = max_divisor
def cal... |
22205d1c0a6c1f62e04c847e2d40f1d83b92f4f7 | sathyanarayan/Webscrapping_freelancer_moneycontrol | /python/scrap.py | 1,642 | 3.734375 | 4 | import requests
import lxml.html as lh
import pandas as pd
import csv
"""
This Program is to download the Splits data - View Company Splits during
the year, from https://www.moneycontrol.com/stocks/marketinfo/splits/index.php
As part of Freelancing project request raised:
https://www.freelancer.com/pr... |
09d17250e9f7bfdeff4da84a805fc4dcd7182060 | artkpv/code-dojo | /_algos/math/permutations/permutations.py | 2,584 | 3.84375 | 4 | #!python3
"""
k-element permutations from n-element set.
"""
def quicksort(a, l, r):
def partition(a, l, r):
m = (l+r)//2
a[m], a[r] = a[r], a[m]
p = a[r]
i = l
j = r-1
while i <= j:
while a[i] <= p:
if i == r:
... |
5c9518df486e24f1657276ddc6bd38e6f190d0bb | ceyhunsahin/TRAINING | /EXAMPLES/EDABIT/EXPERT/128_string_compression_from_characters_array.py | 1,257 | 4.25 | 4 | """
https://edabit.com/challenge/6RHxTTndfASnPyp8Z EXPERT
String Compression from Characters Array
The function is given an array of characters. Compress the array into a string using the following rules. For each group of consecutively repeating characters:
If the number of repeating characters is one, append the s... |
016d3e701e2d3b54fb9b01e09faf9055ce484928 | jbudd/seaturtle | /drive_seaturtle.py | 2,153 | 3.578125 | 4 | import Tkinter as tk
from motor_functions import *
class App(object):
def __init__(self):
self.right = False
self.left = False
self.up = False
self.down = False
self.forward = False
self.back = False
self.degree = 0
self.direction = 1
def keyPres... |
be80bcf30f9e79d869e3bc452752014b4c0118db | kirancrazy99/python_codesnippets | /word_count.py | 1,067 | 3.921875 | 4 | " This script is for to find the number of occurance of each word"
from collections import Counter
text="""
Data wrangling, sometimes referred to as data munging, is the process of transforming and mapping data from one "raw"
data form into another format with the intent of making it more appropriate and valuable fo... |
369f1b94e5288f82fdee4e2ed7c840f70ea1ac54 | AnatoleZho/Python3 | /python_work/class.py | 11,180 | 4.40625 | 4 | # 类
# 1. 创建和使用类
# 1.1 创建 Dog 类
class Dog(): # Python 中约定 首字母大写的名称指定为类
'''一次模拟小狗的简单尝试'''
def __init__(self, name, age):
'''初始化属性name和age'''
self.name = name
self.age = age
def sit(self):
'''模拟小狗被命令时蹲下'''
print(self.name.title() + 'is now sitting.')
def roll_over(self):
'''模拟小狗被命令时打滚'''
print(self... |
b4029e86ad5930fcfa5316ef00049b03d895cbb5 | humbertoperdomo/practices | /python/PythonCrashCourse/PartI/Chapter03/car.py | 516 | 4.40625 | 4 | #!/usr/bin/python3
cars = ['bmw', 'audi', 'toyota', 'subaru']
# Sorting a List Permanently with sort() Method
#cars.sort()
#print(cars)
#cars.sort(reverse=True)
#print(cars)
# Sorting a List Temporarily with the sorted() Function
#print("Here is the original list: ")
#print(cars)
#print("\nHere is the sorted list:... |
0cd589d186ed6e6853cdad13c5784440c86ffc82 | MJSchut/RobotStarForce | /src/managers/statemanager.py | 1,326 | 3.984375 | 4 | class StateManager:
"""
Functions for different game states.
The game is always in a state (e.g. a menu state, or a play state). The statemanager functions
as a finite state machine. An entry state must be given to initialize the state manager.
"""
@property
def currentState(self):
... |
bc20d44d2c45fdd195ba47a5e996353f48145a34 | oumaymabg/holbertonschool-higher_level_programming | /0x0A-python-inheritance/4-inherits_from.py | 361 | 3.859375 | 4 | #!/usr/bin/python3
"""inherits_from:returns True if the object is an
instance of a class that inherited
(directly or indirectly) from the specified class"""
def inherits_from(obj, a_class):
"""obj:object
a_class:class
return returns True if the object is an instance of a class """
return isinstance(ob... |
0ba17e737417bb5c457d07edafaeed79df743c59 | kliner/leetcode | /275.py | 881 | 3.578125 | 4 | class Solution(object):
def hIndex(self, citations):
"""
:type citations: List[int]
:rtype: int
"""
n = len(citations)
ans = self.visit(citations, 0, n, n)
if ans:
return ans
else:
return 0
def visit(self, citations, lo, h... |
fd34906880f793dc4bbbcc924f3957496d8c98df | dariamarc/algo | /strong_password.py | 4,844 | 4.21875 | 4 | def get_info(s):
"""
Get the number of lowercase letters, uppercase letters, digits and groups of reapeating characters of string.
:param s:
:return: no_lowercase - no of lowercase letters
no_uppercase - no of uppercase letters
no_digit - no of digits
repeat... |
05bcec5af080dcf244c2e98038e0965ad5a97aca | takamuradono/Exorcist | /numbergame.py | 797 | 3.765625 | 4 | import random
print ("Hello warrior. Enter your name and face death standing proud")
name = input(str)
secretNumber= random.randint(1,99)
print ("HAHAHA," + name + ", i am hiding somewhere between 1 and 99! TRY AND FIND ME BEFORE I KILL YOUR ENTIRE VILAGE")
for guessesTaken in range(1, 20):
print ("Roll the D20 until... |
c71de016445392958f579be95a13e9c39e416cc7 | eet6646/AnalyzeLogicEq | /analyzeLogicEq.py | 5,743 | 3.703125 | 4 |
import string
import re
import argparse
# UserInput : ReplaceWith
SYMBOL_LOGIC = {
'*': 'and', # and
'&': 'and',
'+': 'or', # or
'|': 'or',
'\'': 'not', # not
'!': 'not',
'#': '^', # xor
'^': '^',
'(': '(', # grouping
')': ')'
}
SYMBOLS = list(' ()') + sum([[key,... |
daa98b24ab0f0f9df74725990506ba76392664e5 | Yakisoba007/PyTrigno | /src/signalAnalysis/cumulant.py | 13,667 | 3.640625 | 4 | """Compute the cumulant of a vector process.
"""
import numpy as np
import itertools
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
def combinations_with_replacement(iterable, r):
"""From
http://docs.python.org/library/itertools.html#itertools.combinations_with_replacement
... |
81485e62b26057056d204970d2b74e5b95856563 | haibincoder/PythonNotes | /leetcode/003.py | 1,034 | 3.828125 | 4 | class ListNode:
def __init__(self, x):
self.val = x
self.next = None
# 链表转list
def ListNodeToList(head):
list = []
list.append(head.val)
while head.next is not None:
head = head.next
list.append(head.val)
return list
def addTwoNumbers(l1, l2):
"""
:type l1:... |
c3b160b1e1778a600def8870edc1f726cb43ce26 | DivyaReddyNaredla/python_classes | /Cash counter program_using_dictionary.py | 4,144 | 3.875 | 4 | ## Cash Counter program
while True:
print("------------------Welcome to fresh fruits zone--------------------")
print()
print("...................................................................")
print()
print("Here are your Available fruits are : ")
print()
print(".............. |
766279648c76a22a958f14273198cd0454580153 | LoganKen/ForNewWay | /circulation.py | 2,932 | 3.71875 | 4 | """
循环语句
"""
#while True:
count = 0
while count <= 10:
# if count == 7:
# pass
# else:
# print(count)
if count !=7:
print(count)
count += 1
"""
break终止当前循环
"""
count = 1
while True:
print(count)
count += 1
if count == 10:
break
"""
continue不再继续往下走,直接返回while条件
"""
c... |
d4a506635e9d35e2632a4c5e5b04d2b33a7ccd09 | dgtest01/aoc2019 | /1/1-1.py | 213 | 3.703125 | 4 | #!/usr/bin/python3.6
with open('input.txt') as f:
lines = f.readlines()
fuelTotal = 0
for line in lines:
fuelTotal += (int(line) // 3) - 2
print(f"The total amount of fuel required is {fuelTotal}.")
|
5fba2fab91e25dc000f5a487c48fa0d76378ca53 | johnhjernestam/John_Hjernestam_TE19C | /Övningsprov/uppgift5.py | 183 | 3.609375 | 4 | mening = input("Skriv en mening: ")
def räkna_ord(text):
ord = text.split()
antal_ord = len(ord)
return antal_ord
print(f"Antal ord i citatet: {räkna_ord(mening)}")
|
e776b6d2e8589cde80020cbdcbc42af7ff62c0a2 | rumeng160/mianshi | /mianshiti.py | 1,064 | 3.578125 | 4 | def how_many_ways(digitarray):
#如果数字是以“0”开头,将“0”去掉
digitarray = digitarray.lstrip('0')
length = len(digitarray)
#当去掉“0”后,数字的长度等于0时,直接返回0,因为0在条件里无法转换为字母
if length == 0:
return 0
#按照该数字的长度生成一个列表,用于后面进行计算
li = list(range(length+1))
li[0] = 1
print(li)
#循环去判断该数字的每一个值
for ... |
e2c9d7c047cef0837d180dab8d752f0e4b3b4a89 | dginz/cloudapp | /py/tuple.py | 514 | 3.59375 | 4 | #!/usr/bin/python
#Filename: tuple.py
#example of tuple
skills = ('C','C++','Java')
print('I have', len(skills), 'skills')
print(skills)
webskill = ('HTML', 'CSS', 'PHP')
print('I have learned', webskill, len(webskill), 'skills')
newskill = (skills, webskill)
print('I have', len(webskill)+len(skills), 'currently sk... |
e7d19b0f54405abc92e1146ba2465ecc536a1ed9 | mkzia/eas503 | /old/spring2021/week4/for_ex_solutions.py | 6,202 | 4.375 | 4 | ###############################################################
# for_ex1.py
# Write a function that takes in a list of values and returns its sum
def sum_list(input_list):
summed_values = 0
for value in input_list:
summed_values += value
return summed_values
print(sum_list([1, 2, 3, 4]))
###... |
e967eab18a367d023fbda1596eda7d4a1c559d56 | matheusspaiva/python | /projeto_2/SalvarImagem.py | 1,483 | 3.609375 | 4 | #importa biblioteca que trabalha com imagens pillow (PIL)
#importa biblioteca que trabalha com arquivos
from PIL import Image, ImageFont, ImageDraw
import pandas as pd
def criarImagem(nome, diretor, professor):
#cordenação dos textos
pessoa_cod = (600,500)
diretor_cod = (300,1010)
professor_cod = (1250... |
51dfed218a68726eac9b74e95340aac315cba14c | YasinEhsan/developer-drills | /cyclicSort/find_duplicate_num.py | 283 | 3.703125 | 4 | #9.27 11:34
def find_duplicate(nums):
# TODO: Write your code here
i = 0
while i < len(nums):
j = nums[i] -1
if i != j:
# already sorted
if nums[j] == j+1:
return j+1
nums[i], nums[j] = nums[j], nums[i]
else:
i+=1
return len(nums)
|
b3ef059c8578f22039dd917f8b56262a2c28a77a | ypycff/pythonClass | /PythonDev/Python-Labs/Solutions/07-MoreOOP/company.py | 2,452 | 3.53125 | 4 | from datetime import datetime
class Employee:
# Class variables.
__minimumSalary = 12000
__nextEmployeeID = 0
# Initialization.
def __init__(self, name, salary):
self._name = name
self._salary = max(salary, Employee.__minimumSalary)
self._joined = datetime.now()
... |
53ffcb698c5a34a7a162e433ee2fe69455ed4ace | JulieWang417/lambdata_ds10 | /lambdata_Julie/day2.py | 1,210 | 4.03125 | 4 | class SuperList():
def __init__(self, initial_state=[]):
self._data = initial_state
def __repr__(self):
string_representation = str(self._data)
return string_representation
def __eq__(self, other):
is_equal = self.__dict__ == other.__dict__
return is_eq... |
1c6bfee602bbbc48565b8dd8c52e7397bb4b5e53 | mattclarke/advent_of_code_20 | /day_6/day_6.py | 1,667 | 3.53125 | 4 | with open("input.txt") as f:
PUZZLE_INPUT = f.read()
# PUZZLE_INPUT = """
# abc
#
# a
# b
# c
#
# ab
# ac
#
# a
# a
# a
# a
#
# b
# """
puzzle_input = PUZZLE_INPUT.strip().split("\n")
# print(puzzle_input)
group_answer_count = []
yes_answers = set()
for line in puzzle_input:
if line == "":
group_ans... |
925ab59628c41adae7153bdd627c873d66e4a49c | jackmorrison12/python-tutorial | /worksheet2/worksheet2_q1.py | 554 | 3.953125 | 4 | # Question 1
numbers = [1,2,3,4,5,6,7,8,9,10]
print(numbers)
for i in range(len(numbers)):
numbers[i] *= numbers[i]
print(numbers)
# Question 2
even = []
odd = []
for i in range(1,101):
if i % 2 == 0:
even.append(i)
else:
odd.append(i)
print("Even: ", even)
print("Odd: ", odd)
# Question 3... |
15ad3fba4df5c3962578eaf7c73a5e23c99c41a9 | mtkwock/Genome-Matching | /code/genome.py | 15,917 | 3.578125 | 4 | from thinkbayes2 import *
from scipy import stats
import random
import string
import sys
import os
import matplotlib.pyplot as plt
class Argument_Parser():
'''
Simple object used to parse and set different command line arguments.
This is not the primary part of the code, but its stored values are used
throughout... |
74609075c75a40411cc58a11e64c99786b8f7e19 | ZMbiubiubiu/For_Test | /leetcode/50.py | 1,018 | 4 | 4 | """
Pow(x, n)
实现 pow(x, n) ,即计算 x 的 n 次幂函数。
分治算法、递归
x ^ n
x * x * x * x * ... * x
可以将其一分为二,
如果为偶数, x ^ n = (x ^ (n/2) ) ^ 2
如果为奇数,x ^ n = (x ^ ((n-1)/2) ) ^ 2 * x
"""
class Solution:
# method 1.递归
def myPow(self, x: float, n: int) -> float:
# 递归基(有两个)
if not n:
return 1
... |
04c824b6d226d961817583b0704c4a6546a04f73 | thestmv/Python | /Tehtävät 4/pairs.py | 774 | 3.859375 | 4 | # Harjoitukset 4
# Tehtävä 2
# Suljeparit
#
# () {} [] <>
# pairs.py
print("Hello! I find pairs.")
print("Enter the first character:")
merkki1 = input()
print("Enter the second character:")
merkki2 = input()
if(merkki1 == "("and merkki2 == ")"):
print('Characters "' + merkki1 +'" and "'+ mer... |
2fd586325839c2cbe7cef186a0560afa557f669b | iXploitID/multi | /1.py | 173 | 3.59375 | 4 | print ("MENGHITUNG VOLUME BALOK")
p = float(input("Panjang = "))
l = float(input("Lebar = "))
t = float(input("Tinggi = "))
v = p*l*t
print ("Volume Balok = %0.2f" %v)
|
0bc344bb0c74f8353ebfb890efb422690aaf9ec2 | TimothySjiang/leetcodepy | /Solution_518.py | 468 | 3.578125 | 4 | class Solution:
def change(self, amount: int, coins: List[int]) -> int:
coins.sort()
return self.recursion(amount, coins, current=0, index=0)
def recursion(self, amount, coins, current, index):
if current == amount:
return 1
res = 0
for i in range(index, len(... |
c13df2cd275a7a569bae189d48e9524cebedbc81 | dbconfession78/interview_prep | /companies copy/drawbridge/magical_strings.py | 1,534 | 3.75 | 4 | # Instructions
"""
Given an integer, n how many different strings of length n can be made with the letters 'aeiou', while abiding by the following rules:
1. 'a' can be followed only by 'e'
2. 'e' can be followed by 'a' or 'i'
3. 'i' can be followd by 'a,'e,' 'o,' or 'u'
4. 'o' can be followed by 'i' or ... |
c56a967fcb45196f67efb1681811fc03ba21eb40 | will-hossack/Poptics | /examples/jones/PolarPlot.py | 658 | 3.59375 | 4 | """
Example program to form a ciccular polasised beam, pass through
linear polarsier and do a polar plot of the output intensity.
"""
import poptics.jones as j
import matplotlib.pyplot as plt
from poptics.tio import getFloat
import math
def main():
theta = math.radians(getFloat("Polariser angle",30.0))
... |
fccff8b10bf3df80f17036780662a9dc9c2f5c86 | Zahidsqldba07/Hackerrank-Challenge-All | /Python/Numpy/Floor, Ceil and Rint.py | 1,661 | 3.859375 | 4 | # floor
# The tool floor returns the floor of the input element-wise.
# The floor of x is the largest integer i where i<=x.
# import numpy
# my_array = numpy.array([1.1, 2.2, 3.3, 4.4, 5.5, 6.6, 7.7, 8.8, 9.9])
# print numpy.floor(my_array) #[ 1. 2. 3. 4. 5. 6. 7. 8. 9.]
# ceil
# The tool c... |
cf7ce13e25c81c828005c637e58642ba734e47d8 | jcream31/workout_music_recommender | /src/find_songs.py | 3,078 | 3.5 | 4 | import pandas as pd
import time
import requests
from auth import Token
import pickle
'''Functions for generating a database of songs'''
def get_top_tracks(artist_id):
'''Takes the artist_id returned from get_artist_id()
and returns a dictionary where keys are track ids
and values are the track name... |
cee1ebbfed144fa1308ddd07508241d7a7fcce16 | lascau/OOP | /Python/Multiset project/Proiect Python brezovan1/multiset.py | 2,831 | 3.875 | 4 | #adauga un element in multimea multipla
def add(e, M):
if e in M:
M.update({e : M[e] + 1})
else:
M.update({e : 1})
#adauga n elemente in multimea multipla
def read(n, M):
for i in range(0, n):
x = int(input())
add(x, M)
#verifica daca multimea multipla e vida
def is_empty(... |
533ac6b2c01f488c81ac392750780387ee09b283 | ParticularJ/python_learning | /slice_ex.py | 1,136 | 3.953125 | 4 | # 省略(ellipsis),用法为(...)
# f(a, ..., z),若x是4维,那么x[i,...]就等于x[i,:,:,:]
l = list(range(10))
print(l)
l[2:5] = [20, 30]
print(l)
del l[5:7]
print(l)
l[3::2] = [11, 22]
# 不能这样赋值 l[2:5] = 100
# 切片的右侧必须为可迭代的序列
l[2:5] = [100]
print(l)
# 对序列使用 + 和 * ,其中+号表示拼接,*表示复制
# 如果a*n,序列a里的元素是对其他可变对象的引用的话
# my_list = [[]]*3,其实得到的三个元素... |
c5a6dafc332be5b85d886f4188916f9e11cb415f | tarcisiovale/Pyquest | /envExemplo/Lista02/Lista02Ex08.py | 520 | 3.859375 | 4 | """
Crie um programa que leia o nome e a altura de 10 pessoas e ao final escreva:
a altura média do grupo, o nome e a altura da pessoa mais alta.
"""
maior = soma = media = 0
for cont in range (10):
nome = input('Digite seu nome: ')
altura = float(input('Digite sua altura: '))
soma += altura
if altura >... |
3337aace6696e864510cc02c9fba5c7ac0451220 | utolee90/Python3_Jupyter | /workspace2/10-collection/test.py | 511 | 4 | 4 | # 리스트 내포
result = [0 for a in range(5)]
print(result)
print('-' * 30)
result = [num*3 for num in range(1, 5) if num%2 == 0]
print(result)
print('-' * 30)
# enumerate : 리스트의 위치 값과 데이터를 묶어서 관리
list1 = ['foo', 'bar', 'baz']
for i, v in enumerate(list1) :
print(i, v)
print('-' * 30)
# zip(리스트, 리스트) : 리스트를 동일한 위치 값끼... |
d106f11762d1b8a11067efd36a35448555b7c0f6 | hundyoung/LeetCode | /leetcode/Q1160_Find_Words_That_Can_Be_Formed_by_Characters.py | 752 | 3.703125 | 4 | from typing import List
class Solution:
def countCharacters(self, words: List[str], chars: str) -> int:
char_dict={}
result=0
for c in chars:
char_dict[c]= char_dict.get(c,0)+1
for word in words:
is_enough=True
char_dict_copy = char_dict.copy()
... |
5a09aed3b1d79488d8250fec2eddf52fe643322b | tanishq-mishra/Hacktoberfest-2018 | /Python3/volPrism.py | 385 | 4.25 | 4 | # volPrism calculates the volumes of rectangular prisms.
def volPrism():
edge1 = float(input("What is the length of the base length? "))
edge2 = float(input("What is the length of the base width? "))
edge3 = float(input("What is the length of the height? "))
vol = edge1 * edge2 * edge3
... |
fcea28289415e1ec26a176fa3bc63daeadc015d2 | rpatel26/intro_to_iot_python_starter_code | /libraries/RGB_LED/RGB_LED/COLOR/COLOR.py | 1,832 | 4.1875 | 4 | #! /usr/bin/python
class Color():
"""
Setters and getters for an RGB color, used as a utility for the RGB_LED library.
"""
def __init__(self):
self._color=(0, 0, 0)
#self._red = 0
#self._green = 0
#self._blue = 0
def set_color(self, red, green, blue):
"""
... |
860b0b4c34d05dd2c95cda53b2fe9e6e1d917484 | shankar7791/MI-10-DevOps | /Personel/Vinayak/Python/Practice/1 March/Program 1.py | 54 | 3.609375 | 4 | list=[1,2,3,4,5,6,7,8]
for i in list:
print("*"*i) |
eea0be40813e15560ef51137c652e559e3d1b1fb | PranavaReddy/competitve_programming | /week2-exam/morse.py | 611 | 3.53125 | 4 | def unique_morse_code(words):
morse={"A":".-","B":"-...","C":"-.-.","D":"-..","E":".","F":"..-.","G":"--.","H":"....","I":"..","J":".---","K":"-.-","L":".-..","M":"--","N":"-.",
"O":"---","P":".--.","Q":"--.-","R":".-.","S":"...","T":"-","U":"..-","V":"...-","W":".--","X":"-..-","Y":"-.--","Z":"--.."}
li=[]
fo... |
6e0edec39443d9f5cd210679469c412b75d99ff5 | Feiniu6ABC/No-name | /cities.py | 698 | 3.84375 | 4 | n = int(input())
dic = {}
for i in range(n):
# now get the two city strings for each of the first n lines
# Hint: Consider using a dictionary here...
# replace the pass keyword below with your code
line = input().split("---")
dic[line[0]] = line[1]
# you still have to read in the 2nd part of the inp... |
a1023b4a05da280ddc93882a99121e3335ff0f57 | sumukh31/100-days-of-code | /pair_sum.py | 1,055 | 3.90625 | 4 | # Given a list of numbers and a number k, return whether any two numbers from the list add up to k.
# For example, given [10, 15, 3, 7] and k of 17, return true since 10 + 7 is 17
def pair_sum(arr,k):
#Edge-case:
if len(arr) < 2:
return
# create set data structures since element insertion in set ... |
0e08be379d6d7cd3e731a6d1a017fb576803ee47 | codud0954/megait_python_20201116 | /06_list/quiz01/quiz01.py | 506 | 4.0625 | 4 | numbers = [3, 8, 9, 4, 2, 1, 7, 5]
# 1. List의 4번째 값을 6으로 바꾸고 전체를 출력하세요.
numbers[3] = 6
print(numbers)
# 2. List의 값 중 가장 큰 값을 출력하세요
# 가장 큰 값은 9 입니다.
max = numbers[0]
for num in numbers:
if max < num:
max = num
print("가장 큰 값은 %d 입니다." % max)
# 3. List의 모든 수의 합
# 합은 39 입니다.
sum = 0
for nu... |
5ef185173ab00d834cd7bf6e13dd8a063d303afe | ssooda/pajang | /Hjun/python/chap08-1.py | 768 | 3.8125 | 4 | # 131
# 사과
# 귤
# 수박
# 132
# #####
# #####
# #####
# 133
print("A","B","C",sep="\n")
# 134
print("출력:\"A\"")
print("출력:\"B\"")
print("출력:\"C\"")
# 135
str_a = "A"
str_b = "B"
str_c = "C"
print(f"변환: {str_a.lower()}")
print(f"변환: {str_b.lower()}")
print(f"변환: {str_c.lower()}")
# 136
변수 = [10,20,30]
for i in 변수:
... |
3eb352e874a83debff4d5f6c26f116b094858127 | Capoqq/InteligenciaComputacional | /tercer taller/punto6.py | 661 | 4.1875 | 4 | def Union(lista1, lista2):
final_lista = list(set(lista1) | set(lista2))
return final_lista
def interseccion(lista1, lista2):
lista3 = [value for value in lista1 if value in lista2]
return lista3
def Diferencia1(lista1, lista2):
return (list(list(set(lista1)-set(lista2)) + list(set(lista2)-set(li... |
23994f517792d50f9f77b4f744b72a1cfb433c32 | WCC-wcc/-offer | /牛客43-树的子结构/1.py | 1,766 | 3.828125 | 4 | # -*- coding:utf-8 -*- #子树: 只要包含了一个结点,就得包含这个结点下的所有节点.
# class TreeNode: #子结构: 包含了一个结点,可以只取左子树或者右子树,或者都不取。
# def __init__(self, x): #要查找树A中是否存在和树B结构一样的子树,分成两步:
# self.val = x #第一,在树A中找到和B的根结点的值一样的结点R;
# self.left = None #第二,判... |
e8340392dd453153d42ee929e585a20d65da414a | guanboang/IoT_Security | /HASH.py | 8,047 | 3.5 | 4 | import difflib
'''
时间 2020年6月17日 Python实现
'''
def circular_shift_left(int_value, k, bit):
'''
循环左移
:param int_value: 数据
:param k: 移位k位
:param bit: 数据总位数
:return: 移位后数据
'''
bit_string = '{:0%db}' % bit
bin_value = bit_string.format(int_value) # 8 bit binary
bin_value = bin_value... |
42c3721b219721ef4fe76089706d5f66bacfd2d3 | itsolutionscorp/AutoStyle-Clustering | /all_data/exercism_data/python/nucleotide-count/c76dbe7f480b46b2ac59758aac512815.py | 394 | 3.703125 | 4 | class DNA:
def __init__(self, dna):
self.dna = dna
def count(self, element):
if ['A', 'C', 'G', 'T', 'U'].count(element) == 1:
return self.dna.count(element)
else:
raise ValueError("%s is not a nucleotide." % element)
def nucleotide_counts(self):
result = {}
for nu in ... |
b68520c8dccf5f44540d1126c4edeb9aad6527dd | avdata99/programacion-para-no-programadores | /ejercicios/ejercicio-050/ejercicio.py | 1,204 | 4.0625 | 4 | """
Tarea: corregir la función para que devuelva el resultado correcto
Por una falla, se indica siempre que ningun numero es primo
Solo UNA linea de codigo necesita corregirse
"""
def es_primo(n):
"""
Dado un numero "n", indicar si es primo o no
"""
# Fijarse si es divisible por los numeros inferiore... |
f4bf45bb3c2ccee453c66778637912f74fe736f2 | AlexHurl/UCDPA_AlexHurley_ | /main.py | 5,473 | 3.59375 | 4 | # Importing necessary packages
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
import numpy as np
import datetime
birddata = pd.read_csv("bird_tracking.csv")
# Print name of each bird
bird_names = pd.unique(birddata.bird_name)
# print(bird_names)
# # Information about the CSV file
birddata.i... |
e859798d72bfbc7653b2f70d01a6a2e5bfbc8a6d | devMEremenko/Coding-Challenges | /Python/LeetCode/!860. Lemonade Change.py | 624 | 3.625 | 4 | # https://leetcode.com/problems/lemonade-change/submissions/
class Solution:
def lemonadeChange(self, bills: [int]) -> bool:
# $5 -> no
# $10 -> 5
# $20 -> 5,10 (preferred) or 5,5,5
f = t = 0
for item in bills:
if item == 5:
f += 1
... |
0c2bbf9744d39609d738eccc982711f30779edb0 | htl1126/leetcode | /428.py | 1,367 | 3.6875 | 4 | # Ref: https://leetcode.com/problems/serialize-and-deserialize-n-ary-tree/discuss/150790/Python-O(n)-recursive-both-functions
"""
# Definition for a Node.
class Node(object):
def __init__(self, val=None, children=None):
self.val = val
self.children = children
"""
class Codec:
def serialize(sel... |
144dc20d6483e7aa18f2b8912dcc0b131465c6ae | yulin871030/my-learning-note | /Leetcode/104_Maximum Depth of Binary Tree_06170131.py | 736 | 3.828125 | 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):
def maxDepth(self, root):
"""
:type root: TreeNode
:rtype: int
"""
if root is Non... |
a1107ed8c5b98a79d8fa0ab91f381f2b9618be67 | xiao2912008572/Appium | /json学习/test.py | 588 | 3.78125 | 4 | import datetime
'''
y = int(input('请输入4位数字的年份:')) # 获取年份
m = int(input('请输入月份:')) # 获取月份
d = int(input('请输入是哪一天:')) # 获取“日”
targetDay = datetime.date(y, m, d) # 将输入的日期格式化成标准的日期
print(targetDay)
print(datetime.date(targetDay.year-1,12,31))
print(targetDay - datetime.date(targetDay.year - 1, 12, 31))
'''
for mon... |
b6c1d7430dc9ed4fcc7d4066c7ce956d1811835d | colinhowlin/ella | /rps.py | 2,310 | 4.0625 | 4 | # Imports
import random, time
# Variable Definitions
hands = {1:'Rock', 2:'Paper', 3:'Scissors'}
draws = 0
wins = 0
losses = 0
def rock():
print (' _______')
print (" ---' ____)")
print (' (_____)')
print (' (_____)')
print (' (____)')
print (' ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.