blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
6bd1c805e910d22d3926dcc483e1992953438865 | ivo-bass/SoftUni-Solutions | /programming_fundamentals/lists_advanced_exercise/10. Inventory.py | 753 | 3.90625 | 4 | def collect(inv, i):
if i not in inv:
inv.append(i)
return inv
def drop(inv, i):
if i in inv:
inv.remove(i)
return inv
def combine_items(inv, i):
old, new = i.split(":")
if old in inv:
inv.insert(inv.index(old) + 1, new)
return inv
def renew(inv, i):
if i in inv:
inv.remove(i)
inv.append(i)
ret... |
45106d0a9a71b876a21b7ad0bcc44cfbd0c65c8c | Vakonda-River/Stanislav | /lesson3_4.py | 352 | 4.15625 | 4 | #x^(-y)=1/x^y
x_1 = float(input('Введите действительное положительное число: '))
y_1 = int(input('Введите целое отрицательное число: '))
def step(x,y):
s = 1
for i in range(abs(y)):
s *= x
res = 1/s
return (res)
print(step(x_1,y_1))
|
c448debe4dc822e37755d58fc878bfb62f00e7d0 | srikanthpragada/PYTHON_03_AUG_2020 | /demo/oop/minh/demo5.py | 339 | 3.625 | 4 | class A:
def process(self):
print(type(self))
print('In A')
class B:
def process(self):
print('In B')
class C(A, B):
def process(self):
# Call method in both superclasses
A.process(self)
B.process(self)
print("In C")
obj = A()
obj.process()
obj =... |
c4633b79e90c0ced6077ab85860a4c233a91576f | daniel-reich/ubiquitous-fiesta | /6sSWKcy8ttDTvkvsL_22.py | 308 | 3.75 | 4 |
def after_n_days(days, n):
d = {
"Sunday":0,
"Monday":1,
"Tuesday":2,
"Wednesday":3,
"Thursday":4,
"Friday":5,
"Saturday":6
}
arr = [(d[day] + n)%(len(d))for day in days]
l = []
for n in arr:
l.append([k for k,v in d.items() if v == n])
return sum(l,[])
|
159226419cbf94e4b9b1bfe84ef1b01f5f0a2f7d | erjan/coding_exercises | /minimize_hamming_distance_after_swap_operations.py | 3,137 | 3.90625 | 4 | '''
You are given two integer arrays, source and target, both of length n. You are also given an array allowedSwaps where each allowedSwaps[i] = [ai, bi] indicates that you are allowed to swap the elements at index ai and index bi (0-indexed) of array source. Note that you can swap elements at a specific pair of indice... |
bb7219177527b96c77d15869c247ad16615a0693 | sagdog98/PythonMiniProjects | /Lab_1.py | 2,248 | 4.34375 | 4 | # A list of numbers that will be used for testing our programs
numbers = [1, 2, 3, 4, 5, 6, 7, 8]
# Question 1: Create a function called even, which takes in an integer as input and returns true if the input is even, and false otherwise
def even(num):
# Provide your code here
return True if num % 2 == 0 else F... |
9cfa73c453c362fdebac50b70055974c6bc1fcbb | AndrewLu1992/lintcodes | /110_minimum-path-sum/minimum-path-sum.py | 839 | 3.671875 | 4 | # coding:utf-8
'''
@Copyright:LintCode
@Author: hanqiao
@Problem: http://www.lintcode.com/problem/minimum-path-sum
@Language: Python
@Datetime: 16-05-27 03:45
'''
class Solution:
"""
@param grid: a list of lists of integers.
@return: An integer, minimizes the sum of all numbers along its path
""... |
e6cc1e0d3809349eb9720f502792478be8d06b80 | didh9i/Kodium | /diary.py | 1,085 | 3.625 | 4 | # Задание №2
# Создайте словарь с 3 ключами - любые 3 дня недели, и задачу,
# которое пользователь должен в этот день выполнить.
# Ниже, в данный словарь, добавьте еще одну задачу в один из дней.
# На консоль выводится измененный словарь.
#
# Выполнил
# Петров Данил Анатольевич
# Mail: ccla... |
420dbe1ea5e83b2e6d95014ac6ff88f37e69bc0e | ianonavy/potatoipsum | /generate.py | 1,144 | 3.859375 | 4 | #!/usr/bin/env python
from random import shuffle, randint, random
def generate(wordlist, num_paragraphs):
lipsum = []
for i in xrange(num_paragraphs):
lipsum.append(random_paragraph(wordlist))
return '\n\n'.join(lipsum)
def random_paragraph(wordlist, max_chars=512):
paragraph = []
while ... |
1e01c08ffcb29f62ca8f3ff50f77cb48619cb45a | Essi5764/python-challenge | /PyPoll/main.py | 1,946 | 3.828125 | 4 | import csv
# Importing the election data
candidates = []
candidate_votes = {}
total_vote=0
winning_candidate=""
winning_count=0
with open("election_data.csv", 'r') as csvfile:
# Split the data on commas
csvreader = csv.reader(csvfile, delimiter=',')
header = next(csvreader)
#Find Total vo... |
1fad51027b38612085af823850a8b02a14f10e34 | sgreenh23/Engineering_4_Notebook | /Python/Python Challenge-MSP.py | 1,255 | 3.671875 | 4 | word = input("Player 1, what's the word? \n")
print ("\n" * 50)
aVariable = 0
def executioner():
x = ("-----|", " O ", " |", " |\ ", " /|\ ", " /"," / \ ")
for stuff in range(0,aVariable):
if aVariable <= 3:
print(x[stuff])
if aVariable == 4:
if s... |
a8e57910a6f4cac298f82ea24b61a85eee163d56 | soyalextreme/estructura-datos-algoritmos | /src/first_partial_exercises/ex_9.py | 1,692 | 3.734375 | 4 | """
30-09-2020
Excersice 9
Estructura de Datos y algoritmos
Average Trip
6to Semestre
Alejandro AS
"""
from lib.inputs import input_int, input_float
from lib.util import clean_screen
from lib.menu.epp_menu import Menu
class ReportTrip():
trip_amount_persons = []
trip_weight = []
... |
dfaf6577accea2021e87ef9ac10c8f1331d7bde7 | julijonas/bi-search | /backend/app/infrastructure/validation.py | 5,601 | 3.578125 | 4 | import re
import json
import sys
class ValidationException(Exception):
def __init__(self, key, message):
super(ValidationException, self).__init__()
self._key = key
self._message = message
def __str__(self):
return "Failed to validate %s: %s" % (self._key, self._message)
clas... |
97a3e6915bb9f22804ce9f517ca2adaa6edaed4d | JuanPGrisales/EjemplosTarea | /Tareas/Correcion.py | 4,258 | 3.5625 | 4 | import random
class colegio:
def __init__(self):
self.diccionarioEstudiantes = {}
def calcularSumaNotasEstudiantes(self):
_listaNotasEstudiantes = self.listarNotaEstudiantes() # Notas de los estudiantes
_sumaNotasEstudiantes = sum(_listaNotasEstudiantes) # sumar las notas de... |
df39f35dba6cb63c4be7d728a8fc3d78392a5a17 | PaulaStrel/tasks | /contest_sort/A.py | 262 | 3.796875 | 4 | N = int(input())
A = [0] * N
for i in range(N):
A[i]=int(input())
def bubble_sort(A):
for i in range(1, N):
for k in range(N - i):
if A[k] > A[k + 1]:
A[k],A[k+1] = A[k+1],A[k]
return A
print(bubble_sort(A)) |
00768aa0f7143cd3c48f338722dfe8424f4437f1 | twishabansal/programmingLangsWTEF | /Python/Assignments/PascalTriangle.py | 298 | 3.828125 | 4 | def pascals_triangle(row):
def fact(n):
if n==0:
return 1
else:
return n*fact(n-1)
string=''
for i in range(row):
string+=str(int(fact(row)/(fact(row-i)*fact(i))))
string+=' '
string+=str(1)
return string
|
63f31efa728417520e9bf692180eb8fbb58e8d9a | jugalj05hi/Project-Euler | /Q1_SumOfMultiples_3and5.py | 155 | 3.734375 | 4 | i = 0
three = 0
five = 0
while (i<1000):
if(i % 3 == 0):
three = three + i
elif( i % 5 == 0):
five = five + i
i += 1
tot = three + five
print(tot)
|
a1a9423ac1dd1cdeacbfe5f351a0769bef507422 | elmasbusenur/Format | /Format.py | 266 | 3.671875 | 4 | print("oyuncu kaydetme programi")
ad=input("oyuncunun adi:")
soyad=input("oyuncunun soyadi:")
takim=input("oyuncunun takimi:")
bilgiler=[ad,soyad,takim]
print("oyuncunun adi:{}\noyuncunun soyadi:{}\noyuncunun takimi:{}".format(bilgiler[0],bilgiler[1],bilgiler[2])) |
d4dd62baef1734197c92c60ae26b7105f229e5d3 | fadedmax/testingscripts | /testcodeagain.py | 1,538 | 4.03125 | 4 | def calculator():
print ("1. Addition")
print ("2. Subtraction")
print ("3. Multiplacation")
print ("4. Division")
print ("5. Primes to 100")
print ("6. Find factors")
print ("")
question = input("Please select a option")
if question == "1":
num1 = int(input("Enter first number: "))
print (num1)
n... |
51850a9176581ccf8b4c193d5a8d2985b6c9f77a | linnndachen/coding-practice | /Leetcode/959-dfs_uf.py | 2,834 | 3.515625 | 4 | from typing import List
class Solution:
def regionsBySlashes(self, grid: List[str]) -> int:
# union find - better solution 不同upscale,直接把 grid 切割为点
# 同类里面生成线 - 则产生新的区间
n = len(grid)
parents = [0]*(n+1)*(n+1)
def find(x):
if parents[x] != x:
parent... |
7b4c6f0599d00d79c8f1da8afbaa296e6b135ba1 | dornheimer/rl_bearlib | /src/map_generators/base_generator.py | 3,961 | 3.734375 | 4 | from abc import ABCMeta, abstractmethod
from src.globals import TILES
class Tile:
"""A tile on the game map, represented by a character and color.
Can block movement and/or sight.
"""
def __init__(self, tile_type=None, *, color_lit='t_brown',
color_dark='t_black', char='#', blocks=T... |
c73dee4a04228d9226ebe1bf0f1e34870388ad40 | indrajithi/code-lab | /pyLab/sample.py | 495 | 3.578125 | 4 | line = 'whippoorwills'
stack = []
for i in range(len(line) - 1):
# if(i < len(line)):
if (line[i] == line[i + 1]):
stack.append(i)
print line[i],i
print line
print stack
for i in range(len(stack) - 1):
if (i + 3) <= len(stack):
if stack[i] + 2 == stack[i + 1... |
8ce4a075aacf0d2ac7ea91cdf50d81b04deab187 | eldridgejm/dsc80-sp21 | /discussions/05/disc05.py | 758 | 4.125 | 4 | import pandas as pd
import numpy as np
def impute_with_index(dg):
"""
impute (i.e. fill-in) the missing values of column B
with the value of the index for that row.
:Example:
>>> dg = pd.read_csv('data.csv', index_col=0)
>>> out = impute_with_index(dg)
>>> isinstance(out, pd.Series)
... |
35ee8afe01a077c7714d29db560b94fb2d33dbb8 | JohnMai1994/CS116-2018_Winter_Term | /CS116/a02-j4mai/a02-j4mai/a02q3.py | 2,603 | 3.65625 | 4 | ##===============================================
## Jiadong Mai (20557203)
## CS 116 Winter 2018
## Assignment 02, Question 3
##===============================================
import check
import math
# Question 3
## Useful constants for pressure trends
steady = "Steady"
rising_s = "Rising Slowly"
rising_f = ... |
1667e4c6cefda6a99ab2f784a69764d0acfe74a5 | yueyehu/pythonStudy | /Triangle Angles.py | 804 | 3.96875 | 4 | from math import acos
from math import pi
def angles(a, b, c):
if a+b>c and a+c>b and b+c>a:
theta1 = round(acos(((a**2+b**2-c**2)/(2.0*a*b)))/(2*pi)*360)
theta2 = round(acos(((a**2+c**2-b**2)/(2.0*c*a)))/(2*pi)*360)
theta3 = round(acos(((c**2+b**2-a**2)/(2.0*c*b)))/(2*pi)*360)
ang =... |
4b69358e19c7898767f2ddb06669dd1111b56eb1 | takujiozaki/python-game-learn | /findAlphabet/quiz.py | 1,873 | 3.796875 | 4 | '''
欠落しているアルファベットを検出するCUIゲーム
書籍「Pythonでつくるゲーム開発」に掲載されていたものをアレンジしています。
'''
import random
import datetime
#入出力
class SystemIO(object):
def print(self, word):
print(word)
def input(self):
return(input())
#game flow
class FindLetter(object):
#プロパティ
QUESTION = ''
r = ''
answer = ''
playtime = []
def __init_... |
401e9235ed52a7a0d75f05ea1e39c3af43e8d98a | BoZhaoUT/Teaching | /Fall_2015_CSCA08_Intro_to_Computer_Science_I/Week_5_Importing/week5_pep8_examples.py | 777 | 3.734375 | 4 | def is_accepted(program_code,gpa,name):
csc_accepted =(program_code=='CSC')
mat_sta_accepted= (((program_code=='MAT')or(program_code == 'STA'))and(gpa>=3))
non_cms_accepted = (gpa> 3.5)
name_accepted =(name=='Brian')
result = (csc_accepted or mat_sta_accepted or non_cms_accepted or name_accepted)
... |
e781f39cde75a2d03feebb7e9ba28664b37c903a | DimitryKrakitov/Genos | /room.py | 3,482 | 3.5 | 4 |
class ist_map:
n_nodes = 0
nodes = []
def __init__(self):
n_nodes = 0
def construction(self, client):
# God node (IST):
god = node()
ist_map.n_nodes = 1
#Make all the gets to fenix, and build the tree representing the map
campus_spaces = client.get_space... |
b7ab7cc9f1bfbdb67a20ce308b7a85129b01b7c1 | ileana2512/change.py | /main.py | 170 | 3.578125 | 4 | print("Please enter an amount that is less than a dollar:")
c=int(87)
print("Q:", c//25)
c = c%25
print("D:", c//10)
c = c%10
print("N:", c//5)
c = c%5
print("P:", c//1)
|
50e53698d6b6038cd4eff2a770b48d544e0c66c8 | KhaderA/python | /day2/day3/classvariabletest.py | 568 | 3.75 | 4 | class Employee:
empcount=0 #class attribute
def __init__(self,sal):
Employee.empcount+=1
self.sal=sal
def __del__(self):
Employee.empcount-=1
def displaycount(self):
return Employee.empcount
def displaysal(self):
return self.sal
#@staticmethod
#def dis... |
8dfc93eb81bd3ad5671056bacf0123eeb1355204 | readiv/ls1 | /Semana01/for.py | 3,885 | 4 | 4 | """
Домашнее задание №1
Цикл for: Оценки
* Создать список из словарей с оценками учеников разных классов
школы вида [{'school_class': '4a', 'scores': [3,4,4,5,2]}, ...]
* Посчитать и вывести средний балл по всей школе.
* Посчитать и вывести средний балл по каждому классу.
"""
import random
def get_averege_and_s... |
786e488335ca8ef7fc681da8f695ac3fed724287 | peterts/mlflow-demo | /mlflow_demo/plotting.py | 922 | 3.5 | 4 | import numpy as np
from plotly import graph_objs as go
from sklearn.metrics import confusion_matrix
def create_confusion_matrix_fig(labels, labels_pred, colorscale='Greens'):
"""
Create a confusion matrix figure with Plotly
Args:
labels (numpy.array): Real labels
labels_pred (numpy.array):... |
28695fbe355ab95266082edad7efb2a406164b9a | g-lyc/PRACTICE | /py-code/5-16.py | 494 | 3.859375 | 4 | # -*- coding: UTF-8 -*-
def pay(paid,balance):
print "Pymt# Paid Balance"
print "----- ----- ------"
i=0
b=balance
while(balance>paid):
balance=balance - paid
i +=1
print "%d $%f $%f"%(i,paid,balance)
i +=1
print "%d $%d $%f"%(i,balance,0)
if __name__ == '__m... |
08cf633a4dc926bcccdacc57a717156b80f899d9 | NewMike89/Python_Stuff | /Ch.4/4-1pizzas.py | 420 | 4.28125 | 4 | # Michael Schorr
# 3/18/19
# listing my favorite pizzas and using a loop to print some stuff about them.
pizzas = ['buffalo chicken', 'zesty italian', 'pepperoni']
for pizza in pizzas:
print(pizza.title() + ", is one of my favorite pizzas.")
print("I really like pizza, so much so that I ate a whole large pizza the... |
6bc0c1e1ee041f26542cded0f0b2c6100f1cdeda | Hits-95/Python | /NumPy/random/5_normal_distribution.py | 395 | 3.96875 | 4 | #norma distrubution
from numpy import random
import matplotlib.pyplot as ptl
import seaborn as sbn
print(random.normal(size = (2,3)))
#Generate a random normal distribution of
#size 2x3 with mean at 1 and standard deviation of 2:
print(random.normal(loc = 1, scale = 2, size = (2,3)))
#Visualization of Normal Distr... |
9739877aaee66de669032f49e767bd7c5ce963b5 | DracoMindz/holbertonschool-machine_learning | /supervised_learning/0x08-deep_cnns/1-inception_network.py | 2,481 | 3.625 | 4 | #!/usr/bin/env python3
"""
function that builds the inception network
"""
import tensorflow.keras as K
inception_block = __import__('0-inception_block').inception_block
def inception_network():
"""
Data in the shape(224, 224, 3)
Convolutions inside & outside inception block
use a rectified line... |
cf759d7d25d53209c5a5698d3d92a31a2911ca0b | ebosetalee/ds-and-algos | /doubly_linked_list/doubly_linked_list.py | 2,418 | 4.28125 | 4 | from linked_list.linked_list import LinkedList
from node.node import Node
# This is a subclass of LinkedList
class DoublyLinkedList(LinkedList):
def add(self, value):
"""
Adds the value to the end of the list
:param value: the value to be added
"""
new_node = Node(value)
... |
606cd3eb44ffff59adffa594592baf7d9735ec4b | heartyhardy/learnin-python | /basics.py | 482 | 3.78125 | 4 | ''' Exceptions '''
try:
age = int(input("Enter your age: "))
print(age)
except ValueError:
print("Invalid input!")
''' Functions '''
# def square(number):
# return number * number
# print(square(10))
# def setName(first, last):
# print(f'{first} {last}')
# # Positional args - order matters
# se... |
715873045c10cbd749964b759b937aecf0a9b716 | arunslb123/DataStructureAndAlgorithmicThinkingWithPython | /src/chapter04stacks/StackWithLinkedList.py | 1,930 | 3.734375 | 4 | # Copyright (c) Dec 22, 2014 CareerMonk Publications and others.
# E-Mail : info@careermonk.com
# Creation Date : 2014-01-10 06:15:46
# Last modification : 2008-10-31
# by : Narasimha Karumanchi
# Book Title : Data Structures And Algorithmic Thinking With Python
# Warranty ... |
29869fa7667649925b622ebed3625b4eadcad806 | zstall/PythonProjects | /CS 2050/CS 2050 HW 2 Dictionaries.py | 9,934 | 3.671875 | 4 | from __future__ import print_function
import unittest
import math
import copy
'''
Description: Creating a dictionary that will assign a value to a specific key and will use
linear chaining for collisions. If the dictionary exceeds 78% load it will automatically
increase the dictio... |
63207540c303a4f7329410e4ae915d38295312db | juhiiyer/scripts | /scripts/python/prog_with_mosh/num_2_word.py | 438 | 4.3125 | 4 | #!/usr/bin/python3.7
'''
this program converts numbers into words:
ex:123
output: one two three
'''
NUMBER = input('Type the number: ')
VALUES = {
"1" : 'One',
"2" :'Two',
"3" : 'Three',
"4" : 'Four',
"5" : "Five",
"6" : 'Six',
"7" : 'Seven',
"8" : 'Eight',
"9" : 'Nine',
"0" : 'Z... |
49f194be65b08f98683ec2e7e73e1e6f801649ec | abhinavsoni2601/experiment | /day 2/list_oddandeven.py | 170 | 3.703125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Wed May 8 16:47:45 2019
@author: Gourav
"""
list1=list(range(0,21))
print(list1[::2])
list2=list(range(1,21))
print(list2[::2]) |
596dc381edc674847d0fc75952fdcb09c78026fa | rrbaetge/Prac_05 | /five_numbers.py | 479 | 4.03125 | 4 | def main():
numbers = []
while len (numbers) != 5 :
user_num = int(input("Enter a number"))
numbers.append(user_num)
print("The first number is {} ".format(numbers[0]))
print("The last number is {} " .format(numbers[-1]))
print("The smallest number is {} ".format(min(numbers)))
... |
3c977064d1c626ae50dc70e5d42882ccce393b6b | jagannara/Dijkstra-Shortest-Path-Algorithm | /shortest_path.py | 3,656 | 4.21875 | 4 | # References:
# 1. https://www.pythonpool.com/dijkstras-algorithm-python/
# 2. http://nmamano.com/blog/dijkstra/dijkstra.html
# 3. https://en.wikipedia.org/wiki/Dijkstra%27s_algorithm
# 4. http://semanticgeek.com/graph/exploring-dijkstras-shortest-path-algorithm/
def shortest_path(graph, source, target):
# `graph... |
626ec234ff484f1232ee2fcbd806941403dc1ea6 | Sedge77/Proyecto1Compi1 | /Token.py | 666 | 3.609375 | 4 | class Token():
def __init__(self,Tipo,caracter): #Constructor de la clase animal
self.Tipo=Tipo #usamos la notacion __ por que lo estamos encapsulando, ninguna subclase puede acceder a el, es un atributo privado
self.caracter=caracter
def setTipo(self,Tipo):
self.__Tipo=Tipo ... |
4f051ce5e2e306ff1f6169e65699e3541dace60e | aecanales/ayudantia-arduino-pv | /Ejemplos/Comunicación Serial/1 - Leer Arduino desde Python/ejemplo_1.py | 923 | 3.515625 | 4 | # Ayudantia Arduino: Comunicación Serial
# IDI1015 - Pensamiento Visual @ PUC
# Alonso Canales(aecanales@uc.cl)
#
# Ejemplo 1: Leer Arduino desde Python
# Importamos la libreria serial para poder comunicarnos con una placa Arduino.
import serial
# Creamos la conexión con la placa. Debemos tener en cuenta:
# 1- El pu... |
85c3b7c0853df5df5e2508c63b59dddd1c36e0f5 | estraviz/codewars | /7_kyu/Case-sensitive/case_sensitive.py | 114 | 3.5625 | 4 | """
Case-sensitive!
"""
def case_sensitive(s):
return [not s or s.islower(), [c for c in s if c.isupper()]]
|
625cd34b79eb4b6567069c410fe464aed7b2ee83 | nirmalnishant645/LeetCode | /0560-Subarray-Sum-Equals-K.py | 713 | 3.703125 | 4 | '''
Given an array of integers and an integer k, you need to find the total number of continuous subarrays whose sum equals to k.
Example 1:
Input:nums = [1,1,1], k = 2
Output: 2
Note:
The length of the array is in range [1, 20,000].
The range of numbers in the array is [-1000, 1000] and the range of the integer k is ... |
5e293c6df293e544ede8939d4e03017bb892f045 | AdamZhouSE/pythonHomework | /Code/CodeRecords/2340/60634/243447.py | 604 | 3.515625 | 4 | problems = int(input())
for x in range(problems):
size = int(input())
array = input().split(" ")
water = [0 for x in range(size)]
volum = 0
wall = int(array[0])
i = 0
while i < size:
array[i] = int(array[i])
if array[i] > wall:
wall = array[i]
water[i... |
8c97254ac84722342a66b6c713c03450c69ecc1d | ashwin015/Ashwin | /69.py | 121 | 3.921875 | 4 | a = int(input("enter the num"))
b = int(input("enter the num"))
c=b-a
if(c%2==0):
print "even"
else:
print "odd"
|
33110ef7e47f689eb6b203b8962f8edd27238d73 | AndreyLyamtsev/python | /dz1-1.py | 2,403 | 4.3125 | 4 | month = int(input("Введите месяц: "))
day = int(input("Введите день: "))
if month == 1 and 1 <= day <= 20:
print("Ваш знак зодиака Козерог")
elif month == 12 and 23 <= day < 31:
print("Ваш знак зодиака Козерог")
elif month == 1 and 21 <= day <= 31:
print("Ваш знак зодиака Водолей")
elif month == 2 and 1 <= ... |
b01fd82aa1b888bf5514a2b3efbb84490ae68942 | projeto-de-algoritmos/D-C_soulmate | /inversion_counter.py | 858 | 3.671875 | 4 | def mergeSort(alist):
count = 0
leftcount = 0
rightcount = 0
blist = []
if len(alist) > 1:
mid = len(alist) // 2
lefthalf = alist[:mid]
righthalf = alist[mid:]
leftcount, lefthalf = mergeSort(lefthalf)
rightcount, righthalf = mergeSort(righthalf)
i = 0
... |
13216620aa37bf105aedf32e4fda5aefb323211b | Kaiduev/Task2 | /task2/Циклические алгоритмы/Armstrong_numbers.py | 113 | 3.546875 | 4 | for x in range(100, 1000):
a = 0
for d in str(x):
a+= int(d) ** 3
if a == x:
print(x) |
0c56f4b96031322cda4055c329aee7acfd0a6e61 | taritro98/DSA_Prac | /missing_element.py | 202 | 3.546875 | 4 | def missing_num(lst,n):
sum_n = (n*(n+1))//2
return sum_n - sum(lst)
for _ in range(int(input())):
n = int(input())
lst = [int(i) for i in input().split()]
print(missing_num(lst,n)) |
c589f17fb1f99a6de9b5d0500ef2962b66e9e1ee | SRD2705/Python-Projects | /Live location of ISS(International Space Station).py | 922 | 3.765625 | 4 | ################################## Live location of ISS(International Space Station) ########################
'''
In this python program we plot the live location of the ISS using an API
Detail explanation in in the program
'''
import pandas as pd
# import panda for data exploration and customization
import p... |
19493c89d2d7217ed7f7f169bb57d9d18da46fd1 | manthan-98/CodeRepository | /DIce Rolling.py | 384 | 3.96875 | 4 | import random
dice = random.randint(1,6)
print(dice)
i = 0
while i<1:
roll = input('Do you like to roll the dice again\n For YES type Y\n For NO tpye N\n>').upper()
if roll == 'Y':
dice = random.randint(1, 6)
print(dice)
elif roll !='Y' and roll !='N':
print('Not Valid')
... |
3b6a5183db434c163878a916c494e2ab477a7990 | Freshman23/algorithms_and_data_structures | /lesson_2/les_2_task_5.py | 529 | 4.21875 | 4 | """5. Вывести на экран коды и символы таблицы ASCII, начиная с символа под номером 32 и заканчивая 127-м
включительно. Вывод выполнить в табличной форме: по десять пар «код-символ» в каждой строке."""
table = ''
for code in range(32, 128):
if (code - 1) % 10 == 0:
table += f'{code:3}: {chr(code)}\n'
e... |
2904eda811196e2c038fed37c110a8f5201f83cd | JZolko/Terminal_Solitaire | /Aces_High_Solitaire.py | 10,954 | 4.21875 | 4 | """
This program is based off a variant of traditional solitaire called Aces Up.
The user starts out with 4 cards and can either move within the tableau, move to
foundation or have more cards dealt to the tableau. The game can only be won
once all colums are aces and have a length of 1.
"""
i... |
8995743cb3d0d382f69092eb9275509a8def8bff | PRKKILLER/Algorithm_Practice | /Company-OA/Robinhood/BlackWhiteMatrix.py | 1,575 | 4.0625 | 4 | """
You are given a rectangular matrix "numbers" consisting positive integers, where cells are colored in the
black and white
Your task is to sort the numbers on the chess board according to a set of queries. each element of the query
is [x,y,w], representing a w*w submatrix with its upper-left corner at (x,y) on th... |
7ef43a9bf278ab4f2f967c0f92c464af374ca59b | jjloftin/cs303e | /CreditCard.py | 2,620 | 4.28125 | 4 | # File: CreditCard.py
# Description: Assignment 5. Write a program that determines whether or not it's valid and if it is valid if it is a MasterCard, Discover, Visa,
# or American Express credit card
# Student Name: Johnathn Loftin
# Student UT EID: jjl2328
# Course Name: CS 303E
# Unique Number: 90110
... |
42a52002b1984a302ea71122cb2d6ccf1dc551e5 | zhuxinkai/python3-book-practice | /beginning-python-3ed-master/Chapter11/listing11-6.py | 1,315 | 3.75 | 4 | '''
要确保文件得以关闭,可使用一条try/finally语句,并在finally子句中调用close。
# 在这里打开文件
try:
# 将数据写入到文件中
finally:
file.close()
实际上,有一条专门为此设计的语句,那就是with语句。
with open("somefile.txt") as somefile:
do_something(somefile)
with语句让你能够打开文件并将其赋给一个变量(这里是somefile)。在语句体中,你将数据
写入文件(还可能做其他事情)。到达该语句末尾时,将自动关闭文件,即便出现异常亦如此。
'''
def process(string):
print('... |
1262837e04c8bafaed9476233974c418789247cf | luangcp/Python_Basico_ao_Avancado | /loop_for.py | 2,302 | 4.625 | 5 | """
Estruturas de repetição
Loop for
Loop -> é uma estrutura de repetição
for -> Uma dessas estruturas (para)
#Python
for item in interavel:
//Esecução do loop
Utilizamos loops para iterar sobre sequencias ou sobre valores iteraveis
Exemplos de iteraveis:
- String
nome= 'Luan'
- List = [1, 3, 5, 7, 9]
- Range
... |
bbe30bf41d54d72f00b97ef85cda1c15357dddd3 | jsneed/TheModernPython3Bootcamp | /Section-034/exercise-349.py | 896 | 3.859375 | 4 | '''
Write a function called parse_bytes that accepts a single string. It should return a list of the binary
bytes contained in the string. Each byte is just a combination of eight 1's or 0's. For example:
parse_bytes("11010101 101 323") # ['11010101']
parse_bytes("my data is: 10101010 11100010") # ['10101010... |
3b9f7f8a58a7cafc886c24241804feab19d2e697 | kaustubhhiware/hiPy | /think_python/dictionary.py | 1,200 | 3.734375 | 4 |
def invert_dict(d):
inverse = dict()
for key in d:
val = d[key]
if val not in inverse:
inverse[val] = key
else:
inverse[val].append(key)
return inverse
def invert_dict_imp(d):
inverse = {}
for key, val in d.iteritems():
inverse.setdefault(val, []).append(key)#just like histogram from wordabular... |
1d6e45ffafc23e9f43b66861ae6ffd1dd6f2592d | maa-targino/Python-Course | /Mundo_01/Desafios/desafio024.py | 349 | 3.828125 | 4 | print('ENCONTRA SANTO\n')
cidade = input('Entre com o nome da sua cidade: ')
santo = cidade.count('Santo',0,5)
santa = cidade.count('Santa',0,5)
sao = cidade.count('São',0,3)
if santo == 1 or santa == 1 or sao == 1:
print('Sua cidade é santa!!!')
elif santo == 0 and santa == 0 and sao == 0:
print('Sinto muito, ... |
a644940b1948a83ceb14afb8c1adfa2cea5f8669 | MoralistFestus/10days20projects-python | /Day 9/free-pdf/textfile_to_pdf.py | 475 | 3.8125 | 4 | # Python program to convert
# text file to pdf file
from fpdf import FPDF
# save FPDF() class into
# a variable pdf
pdf = FPDF()
# Add a page
pdf.add_page()
# set style and size of font
# that you want in the pdf
pdf.set_font("Arial", size = 15)
# open the text file in read mode
f = open("file.txt", "... |
e7a64a7591e9c2c55e29186b9b74cf9d7fb8b59f | ridersw/Karumanchi--Data-Structures | /regularTree.py | 1,274 | 3.734375 | 4 | class TreeNode:
def __init__(self, data):
self.data = data
self.children = []
self.parent = None
def addChild(self, child):
child.parent = self
self.children.append(child)
def getLevel(self):
level = 0
p = self.parent
while p:
level += 1
p = p.parent
return level
... |
c3f75b77c5d4644bcf0c8c71de08b4bdb9dc2218 | bpicnbnk/bpicnbnk.github.io | /array/451_frequencySort.py | 294 | 3.640625 | 4 | class Solution:
def frequencySort(self, s: str) -> str:
from collections import Counter
c = Counter(s)
s = ''
for (key, num) in c.most_common():
s += key*num
return s
s = Solution()
ss = "foo"
result = s.frequencySort(ss)
print(result)
|
f34a0c9c105b802e33f02f42a81daa63b2532332 | jackd/util3d | /voxel/brle.py | 5,672 | 4.0625 | 4 | """
Binary run-length encoding (BRLE) utilities.
Binary run length encodings are similar to run-length encodings (RLE) but
encode lists of values that can only be true or false. As such, the RLE can be
effectively halved by not saving the value of each run.
e.g.
[0, 0, 1, 1, 1, 0, 0, 1, 0]
would have a BRLE of
[2, 3,... |
dfadf44e71e2ac70aac701b0f549c2497dff9343 | Mohan110594/BFS-1 | /Binary_tree_traversal.py | 2,392 | 3.859375 | 4 | BFS traversal
Time complexity:O(n)
space complexity:O(n)
Ran on leetcode:Yes
problems faced: None
Code Description:
we do this using BFS by storing the level of each node at each traversal.when the length of the queue is equal to the level of the node we insert that specific node into the array of the specific level.
... |
8947933986e76531a1bdd2ed5f2e6bd740bf6cd5 | JDOsborne1/project-orwell | /perceptron.py | 845 | 3.90625 | 4 | import numpy as np
class Perceptron:
def __init__(self,weights,bias):
'''
Weights is expected to be an array of real numbers representing the weights
Bias is expected to be a real number quantifying how easy it is to return 1
'''
self.weights = weights
self.bias = bia... |
6a5d0d7d7e9b4eac8ebdc6122db9292846b24e52 | xiaochaotest/Local-submission | /automation_testing_day01/show_testing/python_basics/str_Test.py | 5,942 | 3.546875 | 4 | #!/usr/bin/env python
# -*- coding:utf-8 -*-
# Author:Peng Chao
import selenium
import sys
'''
1.str的操作
2.元组,列表,字典的操作
'''
'''
在单引号里面又包含了单引号的处理
'''
name1 = u'xiaochao,"你好",\'你在成都好吗?\''
print name1
def add():
'''
None
:return:
'''
name = u'小超'
age = 24
address = u'成都'
print u'我在%s,今年我%s岁,我的名字是%s'%(address,age,name)
... |
de6a224fc4a730b94b25861679992788c9ee58a4 | AdamZhouSE/pythonHomework | /Code/CodeRecords/2804/60632/233728.py | 153 | 3.953125 | 4 | formula = input('please input: ')
numbers = sorted(formula[::2])
result = ''
for number in numbers:
result = result + number + '+'
print(result[:-1]) |
051b6e0793655fa6644832912154f66123811202 | Christy538/Hacktoberfest-2021 | /PYTHON/Stack_array.py | 579 | 3.953125 | 4 | class Stack:
def __init__(self):
self.arr = []
self.length = 0
def __str__(self):
return str(self.__dict__)
def peek(self):
return self.arr[self.length-1]
def push(self,value):
self.arr.append(value)
self.length += 1
def pop(self):
popped_item = self.arr[self.length-1]
... |
cf4e7ad7e27dc8e4f218a8ce3c5a07dfb3600e38 | JackyTao/algorithm | /int2words.py | 655 | 3.71875 | 4 | # -*- coding: utf-8 -*-
f = ['One', 'Two', 'Three', 'Four', 'Five', 'Six', 'Seven', 'Eight', 'Nine',
'Ten', 'Eleven', 'Twelve', 'Thirteen', 'Forteen', 'Fifteen', 'Sixteen',
'Seventeen', 'Eighteen', 'Ninteen']
s = [
'Ten', 'Twenty', 'Thirty', 'Forty', 'Fifty',
'Sixty', 'Seventy', 'Eighty', 'Ninty'
]
... |
103cea041e7e3e908e365ad55d9a56478db7ff7e | hidirb/Hangman | /Hangman.py | 8,808 | 3.5 | 4 |
import random
import time
import os
import sys
words_list = [
"jawbreaker",
"jaywalk",
"jazziest",
"jazzy",
"jelly",
"jigsaw",
"jinx",
"jiujitsu",
"jockey",
"jogging",
"joking",
"jovial",
"joyful",
"juicy",
"jukebox",
"jumbo",
"kayak",
"kazoo",
... |
80172bb564d324435841d6f3aaa0b71ebdb6c3b7 | chason-hu/luffy | /01开发基础/第一章-Python基础语法/课后练习/07LoginSimulation.py | 843 | 3.890625 | 4 | #!/usr/bin/env python
# -*- coding:utf-8 -*-
# i.
username = input("请输入用户名:")
password = input("请输入密码:")
if username == "seven" and password == "123":
print("登录成功!")
else:
print("登录失败!")
# ii.
chance = 3
while chance > 0:
username = input("请输入用户名:")
password = input("请输入密码:")
if username == "... |
4e733b1cbb5377886fa2cdd1d07b91d71456938a | kenpos/LearnPython | /正規表現とか色々/vowelMatch.py | 543 | 3.5625 | 4 | #[]で特定の文字集合のみをマッチさせる
import re
#特定の文字マッチング
vowelMatch_regex = re.compile(r'[aeiueoAEIOU]')
#検索し,パターンマッチした奴を全部抽出する
mo1 = vowelMatch_regex.findall('RoboCop feed eats baby food. BABY FOOD')
print(mo1)
print()
#特定の文字以外マッチング
vowelMatch_regex = re.compile(r'[^aeiueoAEIOU]')
#検索し,パターンマッチした奴を全部抽出する
mo1 = vowelMatch_regex.f... |
d927d9616714926438688184ad4c789b90d49aa6 | Symforian/University | /Python/List 3/sudan.py | 459 | 3.5625 | 4 | sud = {}
def sudan(n, x, y):
key = str(n) + " " + str(x) + " " + str(y)
if(n == 0):
return x+y
if(y == 0):
return x
if key in sud:
return sud[key]
val = sudan(n-1, sudan(n, x, y-1), sudan(n, x, y-1) + y)
sud[key] = val
return val
print(
sudan(0, 1, 1),
sud... |
da93e1559bb459035683e3064be454faa25449d8 | nbenjamin/python-workspace | /collection-basics/collections.py | 1,208 | 4.09375 | 4 | import random
# Dictionary
names = {'basic': '1997', 'fortran': '1997', 'c': '2000', 'c++': '2001', '.net': '2003', 'java': '2003',
'python': '2019'}
year = names.get('java')
if year is None:
print('Year is missing ')
else:
print('Year is ', year)
# Two Dimensional Array
menus = {
'Breakfast':... |
f19ee924713199a637902a9a6d5b3579dd9f3b7c | mkozigithub/mkgh_info_python | /20190111 FCSA Learning Time/Files/PythonBeyondTheBasics/10_exceptions_errors/median.py | 646 | 3.71875 | 4 | def median(iterable):
items = sorted(iterable)
if len(items) == 0:
raise ValueError("median() arg is an empty sequence")
median_index = (len(items) - 1) // 2
if len(items) % 2 != 0:
return items[median_index]
return (items[median_index] + items[median_index + 1]) / 2.0
... |
d733dd3f89722a714087eacb9bebbc27e774d738 | CheckiO-Missions/checkio-task-poker-dice | /verification/referee.py | 6,700 | 3.65625 | 4 | """
CheckiOReferee is a base referee for checking you code.
arguments:
tests -- the dict contains tests in the specific structure.
You can find an example in tests.py.
cover_code -- is a wrapper for the user function and additional operations before give data
in the user func... |
bdf4c0fbb518b4fffd8147439573a9a96cbc3e45 | marco8111/python | /exercicio2.7.py | 228 | 3.96875 | 4 | x = int(input("digite o numero :"))
divisores = 0
for i in range(1, x+1) :
if x % i == 0 :
divisores = divisores + 1
if divisores == 2 :
print("numero", x, "é primo")
else :
print("numero não é primo:")
|
c38b4027da74d7cee4bd55364b68b671769d01e3 | jahokas/Python_Workout_50_Essential_Exercises_by_Reuven_M_Lerner | /exercise_01_number_guessing/word_guessing_game.py | 1,098 | 4.25 | 4 | import random
'''
Try the same thing, but have the program choose a random word from the dic-
tionary, and then ask the user to guess the word. (You might want to limit your-
self to words containing two to five letters, to avoid making it too horribly
difficult.) Instead of telling the user that they should guess a s... |
d619b05dbc9bd77371ae794acec12498629f40db | belayashapochka/Programming | /Practice/10/Python/PY 1.py | 628 | 3.5625 | 4 | print("Введите число и диапазоны через пробел!")
s, l1, r1, l2, r2 = input().split(' ')
z = 0
s = int (s)
l1 = int (l1)
r1 = int (r1)
r2 = int (r2)
l2 = int (l2)
if s > (r1 + r2) | s < (l1 + l2):
print (-1, end = '')
else:
if (s - l1) >= l2:
if s <= (l1 + r2):
print (l1, s - l1, end... |
7b9909fdb5085fdbcdf975401e537b98c7de5de2 | Boomshakal/spider | /async_task/111.py | 230 | 3.53125 | 4 | import asyncio
import time
now = lambda: time.time()
async def do_some_work(x):
print('start:',x)
await asyncio.sleep(2)
print("waiting:", x)
start = now()
asyncio.run(do_some_work(2))
print("Time:",now()-start)
|
b85c387eaa32a9a2a185c4af1eb43865b79ab224 | orozmamatovaelnura/hw_06.06 | /ex3.py | 336 | 3.546875 | 4 | def func_compare(x,y):
total=0
for i in range(10):
if x[i]==y[i]:
total+=10
return total
x , y =input().split()
if x.isalpha and y.isalpha:
if len(x)==10 and len(y)==10:
print(func_compare(x,y))
else:
print('Inputs are too short or too long !')
else:
print('Inputs are not st... |
b911c54259a65d0af0d875a263f74512b1c05b1d | tainenko/Leetcode2019 | /python/260.single-number-iii.py | 1,250 | 3.71875 | 4 | #
# @lc app=leetcode id=260 lang=python
#
# [260] Single Number III
#
# https://leetcode.com/problems/single-number-iii/description/
#
# algorithms
# Medium (57.80%)
# Likes: 1043
# Dislikes: 84
# Total Accepted: 118.7K
# Total Submissions: 202.5K
# Testcase Example: '[1,2,1,3,2,5]'
#
# Given an array of numbers... |
1460b604a769a7b6c3fed028205ffba39b45c654 | neelybd/Character_Remover | /BN_Char_Remover.py | 4,815 | 3.984375 | 4 | import pandas as pd
from tkinter import Tk
from tkinter.filedialog import askopenfilename, asksaveasfilename
def main():
print("Program: Char Remover")
print("Release: 0.1.1")
print("Date: 2019-03-26")
print("Author: Brian Neely")
print()
print()
print("This program reads a csv file and wi... |
5431216eecdd45d9eab158b943e6d9131ed89bde | wuyxinu/Plane | /plane/code/bee.py | 1,682 | 3.75 | 4 | #bee.py
import flying
import random
import config
import pygame
#蜜蜂类
class Bee(flying.Flying):
"""
蜜蜂类:
1.包含一个__init__
a)使用bee_count(index)来记录蜜蜂的数量
b)获取蜜蜂的x, y坐标,坐标的获取是根据游戏的窗口随机产生的
c)width 和 height是根据图片的宽高获取的
d)tag 属性,是用来删除图片的
2.蜜蜂的移动方式
def step(self, canvas)
a)蜜蜂在x,y方向都可以移动,所以都要考虑
-X :要判断蜜蜂的速度和移动方向... |
335997f1d50db17b49aaa1da524f38a56b518e43 | DustinYook/COURSE_COMPUTER-ENGINEERING-INTRODUCTION | /PythonWS/FinalExam/test0713_1.py | 801 | 4 | 4 | # 1) 딕셔너리 값 설정하기
d = {}
d['price'] = 100
print(d)
d = dict(price= 100) # 이거 틀림
print(d)
# 2) 리스트에 값 넣기
l = list()
for i in range(0, 10, 1):
l.append(i)
l.reverse()
print(l)
# l = list()
# for i in range(9, 0, -1):
# l.append(i)
# l.reverse()
# print(l)
# 3-1) 정규표현식을 이용하여 추출하기
import re
str = 'width="40" nam... |
4c869ac88da357802de81d3cf90fa773e7dd72c3 | namtruc/catalogue_lfds | /fct_tk.py | 682 | 3.53125 | 4 | import pandas as pd
from tkinter import Tk
from tkinter.filedialog import askopenfilename
def choix_fichier (File):
#input("\nAppuyer sur Entree pour choisir le fichier du catalogue francais non modifie\n")
xl = pd.ExcelFile(File)
if len(xl.sheet_names) > 1 :
print ("\n---Les differents feui... |
baecd21f3a6f5e09c274fda976723b735dbf241b | Mahima-M-A/Engineering-Course-ISE | /Semester 5/Scripting Languages Lab/Python Programs/FileProgram.py | 1,373 | 3.859375 | 4 | import os,sys
from functools import reduce
wordLen = []
dic={}
if(len(sys.argv) != 2):
print("Invalid Arguments")
sys.exit()
if(not(os.path.exists(sys.argv[1]))):
print("Invalid File Path")
sys.exit()
if(sys.argv[1].split('.')[1] != "txt"):
print("Invalid File Format. Only TXT files allowed")
sys.exit()
#to... |
9ee7ec2ac0be1febd69e638868dabeb2aa65050d | vrajdalal07/PRACTICAL-1-2-AND-3 | /frame_label_entry.py | 442 | 3.96875 | 4 | from tkinter import *
root = Tk()
def display():
if ent1.get() == "":
print("Please enter your name: ")
else:
print("Name: " + ent1.get())
ent1.focus()
l1 = Label(root, text="Enter name")
frame = Frame(root)
l1.grid(row=0, column=0)
frame.grid(row=0, column=1)
ent... |
37b53aaf9287e3a156df132b43e59b10bab10160 | hugh225/learnPython | /Python3/grammer/thread.py | 581 | 3.8125 | 4 | import time, threading
def loop():
print("thread %s is running..." % threading.current_thread().name)
n = 0
while n < 5:
n += 1
print("Thread %s >>> %d" % (threading.current_thread().name, n))
# time.sleep(1)
print("Thread %s ended." % threading.current_thread().name)
print("Thread %s is running.... |
2a66d0741498a45ffc28cb3d3d236feb9deabe53 | emanoelmlsilva/ExePythonBR | /Exe.Funçao/Fun.04.py | 127 | 3.859375 | 4 | def positivoNeg(n):
if n > 0:
return "P"
else:
return "N"
arg = int(input("Digite o numero: "))
print(positivoNeg(arg))
|
c0d7aac22f4526a0dfc4fa657714a81bfb387b87 | yiswang/LeetCode | /reverse-bits/reverse-bits.py | 1,850 | 4.03125 | 4 | #!/usr/bin/python
# -*- coding: utf-8 -*-
###############################################################################
#
# Author: Yishan Wang <wangys8807@gmail.com>
# File: reverse-bits.py
# Create Date: 2017-02-14
# Usage: reverse-bits.py
# Description:
#
# LeetCode problem 190. Reverse Bits
#
#... |
e99b15bfe666e962f840f35d4eb397817c2c2d0f | whitneysteward/css_practice | /how.py | 52 | 3.75 | 4 | def reverse(x):
print(x[::-1])
reverse('hello')
|
24536a212489ba37ee83b20db99de91010709372 | heke12345/learngit | /test0608.py | 2,967 | 3.625 | 4 | # # x=int(input("快点输入: "))
# # if x<0:
# # print("no negative allowed")
# # elif x==0:
# # print("zero")
# # else:
# # print("太棒了,都是大于零!")
# item="ball"
# color="red"
# sentence=("Claire‘s %s is %s"%(item,color))
# print("Claire's {0} is {0}".format(item,color))
# pets=("Claire")
# petss=("hahha")
# PETS=... |
f414b9f2e4d21e1efad04de82066c9d60dfe8a97 | bytesweaver/python_prictise | /ex29.py | 368 | 4.15625 | 4 | people = 20
cats = 30
dogs = 15
if people < cats:
print("Too many cats! The world is doomed!")
if people > cats:
print("people > cats")
if people < dogs:
print("people < dogs")
if people > dogs:
print("people > dogs")
dogs += 5
if people < dogs:
print("people < dogs")
if people >= dogs:
print("people >= dogs"... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.