blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
8610e7891577aa5089617fc6e499d40a9f234d3d | Csson/py-bth-adventure | /tictactoe.py | 3,002 | 4.21875 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""Handles the tic-tac-toe games"""
from adventurehelpers import clear, say
import random
def show_tictactoe(toe):
"""Determine current state of tic-tac-toe game"""
return """
-------------
| {} | {} | {} |
-------------
| {} | {} | {} |
-------------
| {} | {}... |
dc3ccdec12d49e2f1707d25d7995574890f2a4a0 | Leahxuliu/Data-Structure-And-Algorithm | /Python/LeetCode2.0/Linkedlist/2.Add Two Numbers.py | 1,160 | 3.859375 | 4 | '''
Method:
Linkedlist --> int --> Linkedlist
Steps:
1. convert l1 and l2 to integers
a. traverse listnodes from l1 and l2
b. int =+ listnode.val * 10^n
2. calculate temp = int1 + int2
3. convert temp to ListNode
Time Complexity: O(N), N = max(m,n)
Space: O(N)
'''
# Definition for singl... |
45873beb20988f2a47a08b79c0deaca1be94decc | hoodielive/modernpy | /2020/archive/binary-search.py | 394 | 3.640625 | 4 | def binary_contains(gene: Gene, key_codon: Codon) -> bool:
low: int = 0
high: int = len(gene) - 1
while low <= high:
mid: int = (low + high)
if gene[mid] < key_codon:
low = mid + 1
elif gene[mid] > key_codon:
high = mid - 1
else:
return... |
a990ef2995682cabe31f86e64f304759caf3c73e | Dharani80/bestinlist-internship | /day5.py | 1,873 | 3.96875 | 4 | Python 3.9.5 (tags/v3.9.5:0a7dcbd, May 3 2021, 17:27:52) [MSC v.1928 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license()" for more information.
>>> n=4
>>> M=[855,5,2,74,33,]
>>> M=M*n
>>> print(M)
[855, 5, 2, 74, 33, 855, 5, 2, 74, 33, 855, 5, 2, 74, 33, 855, 5, 2, 74, 33]
>>> print('upd... |
f5a4006b5d913c6d6798b11fbf403a89a259fb18 | BEPCTA/Coding_Games | /n_ary_function.py | 485 | 4.21875 | 4 | # ---------------
# User Instructions
#
# Write a function, n_ary(f), that takes a binary function (a function
# that takes 2 inputs) as input and returns an n_ary function.
def n_ary(f):
"""Given binary function f(x, y), return an n_ary function such
that f(x, y, z) = f(x, f(y,z)), etc. Also allow f(x) = x."""
def... |
cf0bcfcf23f3a818d712d7de8e8a825af8b7cc59 | fernandoeqc/Project_Euler_Python | /dificuldade 5/3 - Largest prime factor.py | 471 | 3.75 | 4 | """ The prime factors of 13195 are 5, 7, 13 and 29.
What is the largest prime factor of the number 600851475143 ? """
numero = 600851475143
maxFator = 0
def divide(num):
divisor = 2
global maxFator
while (num % divisor != 0):
divisor+=1
if (divisor > maxFator):
maxFator = ... |
8f0f4eeddf40e2982a2fd67240e26c1ca77860c8 | liuxiang0/pi | /Gregory_Leibniz_pi.py | 3,167 | 3.53125 | 4 | #!/usr/bin/python
# -*- encoding: UTF-8 -*-
"""
Algorithms of Gregory-Leibniz series sum for calculating π
收敛极慢的 π/4=1-1/3+1/5-1/7+...
从 反正切函数泰勒级数展开获得
arctan(x) = x-x^3/3+x^5/5-x^7/7+...
令 x=1,得到:π/4 = summation((-1)**k/(2*k+1),(k,0,oo))
区别 sin(x) = summation((-1)**k * x**(2*k+1)/factorial(2*k+1),(k,0,oo))... |
d44af8a2e8befb3c9c500b305c6fc5f600197998 | tonylixu/devops | /algorithm/sorting/merge-sort.py | 1,201 | 4.28125 | 4 | # Mergesort is a divideand conquer algorithm
# which means we break the problem into sub-problems and
# find solution to sub-problems, and from the solution to
# sub-problems we construct a solution of the actual problem.
#
# Mergesort is a stable algorithm, it preserves the relative order
# of records with same key.
... |
087b3113ce491937eddfd37c0584ca12156ccb27 | Yasara123/Grade-Prediction-System | /final_SFT/UnitTesting/win_Help.py | 608 | 3.53125 | 4 | __author__ = 'Yas'
from Tkinter import *
from PIL import Image, ImageTk
root = Tk()
imageFile = "logo4.jpg"
logo = ImageTk.PhotoImage(Image.open(imageFile))
w1 = Label(root, image=logo).pack(side="right")
explanation = """By using this software you can increase the marks of your students.For that following functions c... |
bdfe1bc773f47eb21b509955aad38af53605ef8b | bing1zhi2/algorithmPractice | /pyPractice/algoproblem/Intersection_of_two_arr_349.py | 1,574 | 4.34375 | 4 | """
给定两个数组,编写一个函数来计算它们的交集。
示例 1:
输入: nums1 = [1,2,2,1], nums2 = [2,2]
输出: [2]
示例 2:
输入: nums1 = [4,9,5], nums2 = [9,4,9,8,4]
输出: [9,4]
说明:
输出结果中的每个元素一定是唯一的。
我们可以不考虑输出结果的顺序。
"""
class Solution(object):
def intersection(self, nums1, nums2):
"""
此解法很幼稚 官方答案说
:type nums1: List[int]
... |
3e2c18187040b0a46188af335e199d8c93b20ab2 | artorious/python3_dojo | /find_factors.py | 1,115 | 4.1875 | 4 | #!/usr/bin/env python3
'''Prints all the integers and their associated factors from 1-n'''
from custom_modules.get_positive_number_from_user import get_positive_num
print(__doc__) # Program Greeting
# init
count = 1 # Start from 1 (The numbers being examined)
value = int(get_positive_num()) # Get positive integer from... |
174b7bc473f02157e9d552bd54bee792779abd02 | IsabellaFSilva/Exercicios_Python | /EstruturaSequencial/EstruturaSequencial_6.py | 249 | 4.09375 | 4 | # -*- coding: utf-8 -*-
"""
Faça um Programa que peça o raio de um círculo, calcule e mostre sua área.
"""
r = int(input("Insira o raio do círculo: \n"))
pi = 3.14
a = pi * (r * r)
print("A área do circulo è: %.2f cm aproximadamente" %(a))
|
890c48343b178a3cdabb810722500fac2d92c1ba | imyoungmin/cs8-s20 | /W10/p1.py | 667 | 4 | 4 | """
Problem 1. 2D Barcode.
"""
import random
def twoDBarCode( n ):
"""
Create a 2D bar code.
:param n: Side length.
:return: A two dimensional random 2D code with * and spaces.
"""
code = ""
code += "+" + "-" * n + "+\n" # Header.
for _ in range( n ):
code += "|"
for _ in range( n ):
r = random.randr... |
ae5e8b24813c84e195bd63d38f6e6913d47e4776 | Alone-elvi/Learinig_Python_book_ex | /unittests/test_cities.py | 517 | 3.734375 | 4 | import unittest
from unittests.city_functions import get_city_country
class CityTestCase(unittest.TestCase):
def test_get_city_country(self):
city_country_name = get_city_country('mocsow', 'russia')
self.assertEqual(city_country_name, 'Mocsow Russia')
def test_get_city_country_populations(sel... |
5df1eaf8e03f0265d3320bae6b9d22ea2feb5191 | huyuan95/Learn-Python | /Python Crash Course/chapter15/random_walk.py | 1,129 | 4.25 | 4 | from random import choice
class RandomWalk():
""" a class to generate random walk"""
def __init__(self, num_points = 5000):
"""initiate attribute of random walk"""
self.num_points = num_points
# all random walk begins at (0, 0)
self.x_values = [0]
self.y_values = [0]
... |
b1786bf9070ecfd8cd3d306e241d7258b1ebfe71 | idanyamin/IMDB_review_classifier-Machine-Learning- | /menu.py | 7,542 | 3.671875 | 4 | """
author: Idan Yamin
"""
import graphs_and_results
import sklearn
import sklearn.linear_model
def ridge_menu(x_train, x_test, y_train, y_test):
"""
Opens the ridge menu
:param x_train: train data
:param x_test: test data
:param y_train: train labels
:param y_test: test labels
... |
b6d1801c521113a4bc960be245fe0e0564ec29a8 | krishxx/python | /practice/cp_sols/Pr26.py | 381 | 3.96875 | 4 | '''Question:26
Define a function which can compute the sum of two numbers.
Hints:
Define a function with two numbers as arguments.
You can compute the sum in the function and return the value.
Solution'''
def SumFunction(number1, number2):
return number1+number2
print (SumFunction(100000000000000000000000000000000... |
6977da6394d22e09c93cb5b2a717e310b8d8a0e1 | ChristopherHOliveira/Sistema-Biblioteca | /biblioteca.py | 4,906 | 3.59375 | 4 | # importando funções do SQLalchemy
from sqlalchemy import create_engine
from sqlalchemy.sql import text
# usando o banco de dados contido no arquivo 'bib.db', no formato SQLite
engine = create_engine('sqlite:///bib.db')
# definindo uma classe que herda todas as funcionalidades, métodos e atributos de Exception
clas... |
e12ec0b97218fc42be8f7823f582c0aa0142bc22 | ganqzz/sandbox_py | /algo/sorting/quick_sort.py | 767 | 3.84375 | 4 | # O(nlogn), in worst case O(n2)
# divide-and-conquer
def quick_sort(dataset, left, right):
i, j = left, right
pivot = dataset[(left + right) // 2]
while i <= j:
while dataset[i] < pivot:
i += 1
while dataset[j] > pivot:
j -= 1
if i <= j:
dataset[i]... |
13cadd8f3d8986a0bd1a336e227d414d77e398a9 | telescopeuser/AI_playground | /notebooks/exercises/src/text/jupyter_selection_table.py | 6,455 | 3.609375 | 4 | import pandas as pd
from ipywidgets import Button, HBox, VBox, Label
from ipywidgets import HTML
class SelectionTable:
def __init__(self, data, row_height=28, column_width=80, row_button_width=50, table_cell_paddings=8.16,
button_padding="0pt 0pt 0pt 0pt"):
"""
Class for creating ... |
83982198ded1472e4c930661ad2be006c38ae5a4 | cmcdowell/weatherpy | /weatherpy/image.py | 828 | 3.75 | 4 |
class Image(object):
"""
The image use to identify the RSS feed
Attributes:
height: The height of the image in pixels (int).
link: Link to Yahoo weather.
title: The title of the image (string).
url: The url of the image (string).
width: The width of the image in p... |
11ca7dfda12573ca31b74b402000ee5b449dd0af | satishvbs/Master-Thesis-17-18 | /find-all-Link-from-A-Page.py | 710 | 3.703125 | 4 | #Web scraping in python finding all links
'''
Some web links starts '#', some statrs with './' and rest proper link
task
Print all the links
1.if link starts with #, skip it
2.if link starts with ./ then replace ./ with 'https://' and print rest of the things
'''
import bs4
import requests
req_obj =requests.get('ht... |
edcee71a09fa5b9ee6b20558f284393a021e4220 | Bing-Violet/Code-Like-a-Girl | /python_tutorial/Session 2/if_statement.py | 210 | 4.0625 | 4 | #if statement demo
year = 2020
year_of_birth = input("Enter your year of birth:")
age = year - int(year_of_birth)
if age > 20:
print('Congratulations! You are an adult!')
else:
print("You're still young.") |
7f22d28adf9343de18ac73aa427bd4ed1f4cbfc8 | RongYu98/SoftwareDevHW | /IDK/lab.py | 1,347 | 3.734375 | 4 | import time
import quicksort
def wrapper( f ):
def inner( *arg ):
t1 = time.time()
funct = f(*arg)
t2 = time.time()
print "Time Taken for Function: ["+f.func_name+"] is " + str(t2-t1)
return funct
return inner
def foo( num1, num2, string):
return str(num1)+str(num2)... |
7750cda6e199021fcc158491e776c77daea9bee1 | 953250587/leetcode-python | /CatAndMouse_HARD_913.py | 7,686 | 4.125 | 4 | """
A game on an undirected graph is played by two players, Mouse and Cat, who alternate turns.
The graph is given as follows: graph[a] is a list of all nodes b such that ab is an edge of the graph.
Mouse starts at node 1 and goes first, Cat starts at node 2 and goes second, and there is a Hole at node 0.
During eac... |
073f78fc9c3f4652ab1b420580ec0a45f7972608 | vany-oss/python | /pasta para baixar/netcha/exr29 velocidade de caro.py | 394 | 3.796875 | 4 | velo = float(input('velocidade actual? '))
if velo > 80:
print('multado voce esxcedeu o limitite permitido')
multa = (velo -80 ) * 0.50
print('voce deve pagar a multa de {} euros'.format(multa))
print('bom dia faca uma boa conducao')
# pg que calcula a multa d caro se a velocidade permida for escnxcedida o valor d... |
268b22f60229f25a05575124a91dc7ddf3c02e5b | abhireddy96/Leetcode | /747_Largest_Number_At_Least_Twice_of_Others.py | 795 | 3.875 | 4 | """
https://leetcode.com/problems/largest-number-at-least-twice-of-others/
In a given integer array nums, there is always exactly one largest element.
Find whether the largest element in the array is at least twice as much as every other number in the array.
If it is, return the index of the largest element, otherwise ... |
b75b07d997e307ee9fee637c5a8b6c1dd412113a | kerxon/python-course-code | /file-handling/filehandling.py | 1,504 | 4.28125 | 4 | # r opens for reading only, pointer is placed at the beginning of the file. this is default mode
# r+ opens a file for both reading and writing. The file pointer is placed at the beginning of the file.
# w Opens a file for writing only. Overwrites the file if it exists.If the file doesn't exist, creates a new file
# w+... |
e101ad1c2d70ee89cb62e77da55ab3f5d02594fe | thomashirtz/leetcode | /solutions/1447-simplified-fractions.py | 543 | 3.9375 | 4 | from typing import List
class Solution:
def simplifiedFractions(self, n: int) -> List[str]:
answer = []
set_ = set()
for denominator in range(1,n+1):
for numerator in range(1,n):
if numerator/denominator<1 and numerator/denominator not in set_:
... |
5e5ac3a6e5aea7f803a66a4f2751e5ac551e647e | johnoro/Data-Structures | /binary_search_tree/binary_search_tree.py | 1,164 | 3.578125 | 4 | # each 'node' will be a B.S.T.
class BinarySearchTree:
def __init__(self, value):
self.value = value
self.left = None
self.right = None
def insert_to(self, value, direction):
if getattr(self, direction) is None:
setattr(self, direction, BinarySearchTree(value))
else:
getattr(self, ... |
639e6016b0fc13054ced217f35fd037d7ab082dc | coolczyk/szkolenie | /user_input.py | 91 | 4.15625 | 4 | variable = input ("What is your name?: ")
#variable = 5
print ("Hello " + variable + " !")
|
e142320cf537e5968d8c1a986801cf9a018fd71e | VivekMaran27/coding-practice | /python/trapping_rain_water_lc42.py | 1,037 | 3.609375 | 4 | class Solution:
def trap(self, height: List[int]) -> int:
maxSeenSoFar = 0
maxSeenRight = [None]*len(height)
maxSeenLeft = 0
numRainBlocks = 0
#Track the max value in right
for i in range(len(height)-1,-1,-1):
if(height[i] > maxSeenSoFar):
... |
902e1ceca9b14cf04982e7be9811fec0c0cc9e16 | Logavani16/python1 | /66.py | 117 | 3.734375 | 4 | vani=int(input())
for v in range(2,vani):
if vani%v==0:
print("no")
break
else:
print("yes")
|
0aa3a99e232fb3357bb4f24797c7f280bf611db7 | olukaemma/py | /testcode/temp.py | 490 | 3.765625 | 4 | #!/usr/bin/env python3
__author__ = 'Emmanuel Oluka'
'''using Templats in string'''
from string import Template
def Main():
cart = []
cart.append(dict(item='Coke', price=8, qty=2))
cart.append(dict(item='Sugar', price=10, qty=3))
cart.append(dict(item='rice', price=5, qty=5))
tmp = Template("$qt... |
c1bd4e46769be72961168f3566fff13d6b327a6a | michaelzap94/mz-python | /Concurrency/Async/10_yield_to_receive_data.py | 950 | 4.09375 | 4 | # SIMPLE
def greet():
# SUSPEND THE FUNCTION, BUT assign the value we receive to a variable ('friend')
friend = yield
print(f'Hello, {friend}')
try:
g = greet()
g.send(None) # Priming the generator: runs up to yield and then do:
g.send('Adam') # This is what goes into the 'yield' of the genera... |
d7494be4817349002aff937d8a33a6720e11fd8b | ArDrift/InfoPy_scripts | /9_het/8_dolgozatok.py | 824 | 4.03125 | 4 | #!/usr/bin/env python3
# A rendezéshez felhasználtam: https://docs.python.org/3/howto/sorting.html#key-functions
class Hallgato:
def __init__(self, neptun, nev, pont):
self.neptun = neptun
self.nev = nev
self.pont = pont
def __str__(self):
return "Név: {}, Neptun: {}, Pont: {}".format(self.nev, ... |
151ca015010ff7397e96505afe973ae2de610993 | Kunal352000/python_program | /c10.py | 97 | 3.625 | 4 | #print 1-10
for i in range(1,11):
print(i)
for i in range(1,11):
print(i,end=" ")
|
fbc89a2ae3c41b2673f6245c203c7f0f4b934b07 | joegle/grimoire | /python/simple.py | 183 | 3.859375 | 4 | #!/usr/bin/env python2
# return the sorted array
a = [2, 3, 1]
print sorted(a)
# in place sort returning None
a.sort()
# sort by a function key
a.sort(key=str.lower, reverse=True)
|
3a02e733d8faa8be72d66fd2b012711bff96b3b3 | Subhadarsini-10/Beg.-python | /beg-python.py | 7,801 | 4.28125 | 4 | #!/usr/bin/env python
# coding: utf-8
# <ol><p><b>math module</b></p></ol>
# In[3]:
import math
print(round(2.9))
# In[6]:
import math
print(math.ceil(2.9))
# In[7]:
import math
print(math.floor(2.9))
# In[8]:
x=2.9
print(abs(x))
# In[9]:
x=-2.9
print(abs(x))
# <p><b>if statements</b></p>
# In[3]... |
3f28b0768fa50df7d2f5b825cc64abc9fdfdcbbb | EhODavi/curso-python | /exercicios-secao07-parte1/exercicio35.py | 879 | 3.65625 | 4 | a = input('Informe o número a: ')
b = input('Informe o número b: ')
vetor_a = list(a[::-1])
vetor_b = list(b[::-1])
vetor_c = []
if len(vetor_a) <= len(vetor_b):
for i in range(len(vetor_b)):
vetor_c.append(vetor_b[i])
for i in range(len(vetor_a)):
vetor_c[i] = str(int(vetor_a[i]) + int(veto... |
5bef4ddce4a003404320fca7a0ffaf0239f93cbb | Aasthaengg/IBMdataset | /Python_codes/p02789/s253976007.py | 83 | 3.5 | 4 | n, m = [int(s) for s in input().split()]
ans = "Yes" if m == n else "No"
print(ans) |
153d539dd41961915c3d4de482d87c081b5d065f | adithyadn/DS-Algorithms | /Udacity-DS-Project1/Task1.py | 806 | 4.0625 | 4 | """
Read file into texts and calls.
It's ok if you don't understand how to read files.
"""
from functools import reduce
import csv
with open('texts.csv', 'r') as f:
reader = csv.reader(f)
texts = list(reader)
flatten_texts_list = reduce(lambda z, y: z + y, list(map(lambda lst: lst[:2], texts)))
with open(... |
7f1554d8d3737dce79a233eda24c93180e1c8eda | edt-yxz-zzd/python3_src | /nn_ns/graph2/bucket_sort/ChainFuncs.py | 983 | 3.8125 | 4 |
'''
example:
>>> mul = lambda x:x*2
>>> add = lambda x:x+2
>>> funcs = [mul, add]
>>> ChainFuncs(funcs)(3)
10
>>> apply(3, funcs)
8
>>> may_apply(3, [mul, None, add])
8
'''
__all__ = '''
ChainFuncs
apply
may_apply
filterout_None
'''.split()
def filterout_None(... |
6d071d3d524cc0722590f0507f5ed413ed0c2fb9 | ezbins/exec_python | /exec10.py | 1,510 | 3.984375 | 4 | #!/usr/bin/env python3
# coding: utf-8
import sys
prices = []
quantities = []
total_sum = 0
tax = 0
def checkNumberic(value):
if value.isnumeric():
return int(value)
else:
print("Please input numberic.")
sys.exit()
def calcu_total(prices, quantities):
global total_sum, tax
... |
698efe743d29b80f7a4c1c768c192211bbf9ea42 | aaryan325/Easy-to-use-calculator | /calculator.py | 3,277 | 3.671875 | 4 | import tkinter as tk
import tkinter.messagebox
root = tk.Tk()
root.title("Calculator By @AaryanSarda")
expression = ""
def add(value) :
global expression
expression += value
label_result.config(text=expression)
def clear():
global expression
expression = ""
label_result... |
89d7b2d75353ac4d05494bff27bd6c2426e8a7a0 | kirumalai/python | /player1.py | 113 | 4.21875 | 4 | def reverse(string):
string="".join(reversed(string))
return string
s=input()
print(reverse(s))
|
03016ee3901fdcbb8f2f7938887229af66d6e34c | Ayman-Yahia/CodingDojo-Python | /Python_Assignments/3.py | 129 | 3.796875 | 4 | def count_substring(string,sub_string):
count=string.count(sub_string)
print(count)
count_substring('ABSHIZLMSHIZ','HIZ') |
6b2b7ecb06f7702ff0836c9c5ec9ba60373fe24f | aswathiedayillyam/luminarpython | /flowcontrolls/loopingstmts/sumofnumbers.py | 115 | 3.59375 | 4 | limit=int(input("enter limit"))#10
#sum of 1 to 10
i=1
sum=0
while(i<=limit):
sum=sum+1
i+=1
print(sum) |
4b735f8a0cc6880967b629d05d895d882064831f | aditya8081/Project-Euler | /problem2.py | 410 | 3.734375 | 4 | x=0
y=1 #Starts with the two first fibonacci numbers
sum=0 # initializes a sum variable
while y < 4000000: # while the fibonacci term is less than 4 million
z=x+y # find the next term
if z%2 == 0:
sum += z # add it to the sum if it is even
x=y... |
759582d81c8b63cae27770c4683662f5a9ec8a45 | iyerikuzwe/Password-Locker1 | /credentials_test.py | 2,741 | 3.765625 | 4 | import unittest
from credentials import Credentials
class TestCredentials(unittest.TestCase):
'''
Test class that defines test cases for the credentials class behaviours.
'''
def setUp(self):
'''
Set up method to run before each test cases.
'''
self.new_credentials = Cr... |
3da168ec89c1b823ea198ab36fe84173438968c4 | terracenter/Python3-CodigoFacilito | /Scripts/Variables/Listas.py | 862 | 4.40625 | 4 | #Parentisis cuadrados significa listas
#Soporta cualquier tipo de datos.
myList = ["String", 15, 15.6, True]
print(myList)
print()
print()
#Pueden crecer o decrecer
#Agregar
myList.append(6) #Lo colca en la parte final
print(myList)
print()
print()
myList.insert(1, "Insert") #Agrega un elemento en una posicion dada
p... |
f3de2b4d8e496d458dc9a305b0274dd69bb7225e | hastorojas/prueba100 | /ejercicio_lista.py | 382 | 3.90625 | 4 | try:
lista=[]
cant = int(input('De que tamaño quieres tu lista: '))
i = 0
while i < cant:
valor = input('Agregue un nombre a la lista: ')
lista.append(valor)
i = i + 1
print('El listado es el siguiente: ')
print(lista)
except Exception as ex:
print('Hubo un problem... |
a8b46694da414165e907143e863ddf2171a03446 | sandipan898/crash-course-on-python-coursera-codes | /basic-syntax/expressions-variables/eg-4.py | 195 | 4.0625 | 4 | """
This code is supposed to display "2 + 2 = 4" on the
screen, but there is an error. Find the error in the
code and fix it, so that the output is correct.
"""
print("2 + 2 = " + str(2 + 2))
|
a6c955edfabaf3d952c98aa0886d0f346604c1a8 | adarsh0806/anProjects | /Projects/unit2/lesson1/project1/stats.py | 1,326 | 3.578125 | 4 | import pandas as pd
data = '''Region, Alcohol, Tobacco
North, 6.47, 4.03
Yorkshire, 6.13, 3.76
Northeast, 6.19, 3.77
East Midlands, 4.89, 3.34
West Midlands, 5.63, 3.47
East Anglia, 4.52, 2.92
Southeast, 5.89, 3.20
Southwest, 4.79, 2.71
Wales, 5.27, 3.53
Scotland, 6.08, 4.51
Northern Ireland, 4.02, 4.56'''
data = dat... |
51bfa70aa9921e4643ac6e66e07ad13d7dca15e5 | ravalrupalj/BrainTeasers | /Edabit/Profit_Margin.py | 636 | 4.09375 | 4 | #Profit Margin
#Create a function that calculates the profit margin given cost_price and sales_price. Return the result as a percentage formated string, and rounded to one decimals. To calculate profit margin you subtract the cost from the sales price, then divide by salesprice.
#Remember to return the result as a perc... |
9f30ad4ecba66e5da6cbd8126ac6da82175ef3c5 | Planetfunky/CodiGo | /Python/condicionales04.py | 231 | 3.71875 | 4 | weight = int(input('Weight: '))
metric = input('(L)bs or (K)g: ').lower()
if metric == 'k':
converted = weight / 0.45
print(f'You are {converted} kilos')
else:
converted = weight * 0.45
print(f'You are {converted} kilos')
|
6f17d70cdd29448a45dad0b6668b49e7e8484485 | CvetelinaS/pyladies | /02/heslo.py | 167 | 3.921875 | 4 | heslo = input('Zadej heslo:')
print (heslo=='cokolada')
if heslo =='cokolada':
print('Spravne! Racte dale!')
else:
print ('Spatne!')
print('ALARM!' * 3)
|
d67e64c0beb255a72d14317c94f399af905bb05a | mtahir08/pythonDemo | /level-01/question-4.py | 434 | 3.984375 | 4 | #####################
## -- PROBLEM 4 -- ##
#####################
# Given a string, return a string where for every char in the original,
# there are two chars.
# doubleChar('The') → 'TThhee'
# doubleChar('AAbb') → 'AAAAbbbb'
# doubleChar('Hi-There') → 'HHii--TThheerree'
def doubleChar(str):
# CODE GOES HERE
new... |
dff9eceb254322fb4b8b542a23a7952385c299f6 | daniel-reich/ubiquitous-fiesta | /EL3vnd5MWyPwE4ucu_3.py | 135 | 3.953125 | 4 |
def fibonacci(n):
numbers = [0,1]
for i in range(2,n+1):
numbers.append(numbers[i-2]+numbers[i-1])
return str(numbers[-1])
|
7c3f268041f3c315c0f7102122e4fb5b9bd77629 | samurai-yuji/word_count_test | /yuji_lib.py | 180 | 3.75 | 4 | import random
def make_word(size):
words="abc"
new=[]
for i in range(0,size):
i=int(random.random()*3)
new.append(words[i])
return "".join(new)
|
d69aee42e1b1dc808fa1659f265da13f291f4caf | andismail/python-basic | /py_native_datatype_string.py | 11,480 | 4.46875 | 4 | # +A string is a sequence of characters.
# A character is simply a symbol. For example, the English language has 26 characters.
# Computers do not deal with characters, they deal with numbers (binary). Even though you
# may see characters on your screen, internally it is stored and manipulated as a combination of 0's a... |
5fbf3aeebfc1b8b53745fcd9743f5760cf00a006 | CP-Unibo/sunny-cp | /src/features.py | 2,966 | 3.546875 | 4 | '''
Module for defining a feature extractor that computes the feature vector of a
problem. A feature extractor is simply a class that implements the static
method extract_features(args) to return the feature vector.
The default extractor is mzn2feat, but the user can define its own extractor by
simply implementing a co... |
30a1bf3451fe345ab820d5c89b6b729bf0039108 | okadakousei/Education-Project-for-newcomer | /submit/age_guess/age_guess_ogi.py | 606 | 3.515625 | 4 | b=50
for t in range (100):
print("are you older than "+str(b)+"?")
a=input("input yes or no:",)
if a=="yes":
for i in range (1,10):
c=input("are you older than "+str(d)+"? input yes or no:",)
d=50+b/2
if c=="yes":
print("you are "+str(d)+"!")
... |
5fddc4e911c443da36d12c1ef4dab0b6a02eb3d9 | matheusglemos/Python_Udemy | /Conceitos básicos de estrutura de dados e objetos em Python/Dicionarios/dicionario.py | 2,229 | 4.46875 | 4 | # Projeto em python 3 referente a aula 16 do Curso python da plataforma Udemy.
# Objetos
dados = {'nome':'Matheus','idade':'21','status':'namorando'}
d = {'anos':{'meses':{'dias':'minutos'}}}
dic_01 = {'chave_01':123,'chave_02':[12,23,33],'chave_03':['item0','item1','item2']}
dic_02 = {}
# Construindo um dicionário
#... |
de9de2f1e58fe6ca656375870f99ff650ade830f | Fox5113/Compression | /_compression.py | 274 | 3.578125 | 4 | #!/bin/python3
if __name__ == '__main__':
a = list(map(int, input("Введите список для сжатия ").split()))
count_zero = a.count(0)
while count_zero > 0 :
d = a.remove(0)
count_zero -= 1
a.append(0)
print(a) |
71393994164d88eb86be3e7b1f4bc80b39911673 | Amankhalsa/Aman_code-html-php-python | /preet/Loop/w3_nested_for_5.py | 163 | 3.765625 | 4 | '''
Created on Apr 22, 2021
@author: hp
'''
adj = ["red", "big", "tasty"]
fruits = ["apple", "banana", "cherry"]
for x in adj:
for y in fruits:
print(x, y) |
a623945ebbc5f46dc7588360ce161b3120ba641f | Danny-Dasilva/Search_Biopython | /split_sentence.py | 288 | 3.546875 | 4 | import re
s = """Mr. Smith bought cheapsite.com for 1.5 million dollars, i.e. he paid a lot for it. Did he mind? Adam Jones Jr. thinks he didn't. In any case, this isn't true... Well, with a probability of .9 it isn't."""
m = re.split(r'(?<=[^A-Z].[.?]) +(?=[A-Z])', s)
for i in m:
print(i) |
0cf5eb5894084e9f2faa115ebf380d406c1f20aa | MoAbd/codedoor3.0 | /student_id.py | 1,030 | 3.640625 | 4 | """
Given a school with a number of classes. Every class has a specific number of students in it. Students are sorted alphabetically inside classes and among them. Every student has a local id, which is his index in the class If we sort it alphabetically, and a global id which is its index among the school. ID’s always... |
ca0a127de2ac1a3c587125706520716e0b673633 | harshonyou/SOFT1 | /week4/Answer/week04exercise1.py | 1,638 | 4.4375 | 4 | # For the three exerices, you should refactor the code you wrote in week 3
# 1- Write a function sum_all(n) that returns the sum of the first n positive
# natural numbert. The function should return -1 if n<0.
def sum_all(n):
if n < 0:
return -1
total = 0
for value in range(n):
total += v... |
620e63b0c494ef42092870addb0ac24dd6ba769a | nitya108/leetcode | /max_path_sum_trees.py | 875 | 3.515625 | 4 | # Input: [-10,9,20,null,null,15,7]
# -10
# / \
# 9 20
# / \
# 15 7
# Output: 42
# 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 maxPathSum(self... |
295c8f77a7cc754862f64c1d0e45523867a64bd8 | osasanchezme/skyciv-pip | /src/skyciv/utils/helpers.py | 1,711 | 3.59375 | 4 | import copy
import types
def clone(dict: dict) -> dict:
"""Create a deep clone of a dictionary or array.
Args:
dict (dict): The dictionary to clone.
Returns:
dict: A clone of the input dictionary.
"""
return copy.deepcopy(dict)
def next_object_key(dict: dict) -> int:
"""Get... |
1628cf4017354ea88ac9dc42165b3f51074a1219 | amlinger/AdventOfCode | /2016/python/day02/part1.py | 2,961 | 4.28125 | 4 | """
Advent of code 2016 - Day 2, Part 1
Bathroom security
===
You arrive at Easter Bunny Headquarters under cover of darkness. However, you
left in such a rush that you forgot to use the bathroom! Fancy office buildings
like this one usually have keypad locks on their bathrooms, so you search the
front desk for the c... |
eda32f156fea6fd35c9e9916cbcc1ae08eff8a7b | MNikov/Python-Advanced-September-2020 | /Old/Python-Advanced-Preliminary-Homeworks/Tuples and Sets/02E. Sets of Elements.py | 427 | 3.671875 | 4 | def fill_sets(n, m):
n_set = set()
m_set = set()
counter = 1
for _ in range(n + m):
number = int(input())
if counter <= n:
n_set.add(number)
else:
m_set.add(number)
counter += 1
return n_set.intersection(m_set)
def print_result(result_set):
... |
de8970866d90269d318cf437fe50865482f25379 | supriyo-pal/Joy-Of-Computing-Using-Python-All-programms | /Push the zero.py | 346 | 3.78125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Wed Nov 4 11:10:47 2020
@author: Supriyo
"""
a = list(map(int,input("\nEnter the numbers : ").strip().split()))
def move_zero(num_list):
a = [0 for i in range(num_list.count(0))]
x = [ i for i in num_list if i != 0]
x.extend(a)
return(x)
call=move_zer... |
82cf112ca3c8154091d2c353f7430a2d1b76195e | petpetshoy/comp_272 | /lab_5/skeleton_TCPWebServer.py | 1,985 | 3.953125 | 4 | #import socket module
from socket import *
#choose a port from 1024 -> 65535 to listen on and
#assign to variable serverPort
#--TODO--
#Create TCP welcoming socket
#Notice the use of SOCK_STREAM for TCP
serverSocket = socket(AF_INET, SOCK_STREAM)
#Bind the port and prepare the socket to
#listen for clien... |
f891c7d4ee47dde1deec49529f383e8cc2006c17 | nitinsurya/MinorProjects | /NeuralNetworks/hw1/Test.py | 571 | 3.65625 | 4 | import random
import matplotlib.pyplot as plt
import numpy as np
def plotPoints( ):
list_of_lists = [[1, 2], [3, 3], [4, 4], [5, 2]]
x_list = [x for [x, y] in list_of_lists]
y_list = [y for [x, y] in list_of_lists]
# plt.plot([1,2], [2,3], 'or')
# plt.plot([1,2], [3,4], 'ob')
plt.scatter(1,2, ... |
0abf66bb1c93031d7b16a2e21436030010f30b40 | gaurihatode23/Assignment-1 | /Task1.py | 990 | 3.734375 | 4 | #Question1 of Task 1
a=10,;b=20.1;c='New York'
#Question2 of Task 1
d=(2j+3)
a,d=d,a
#Question3 of Task 1
x=20,y=30
Result=x
x=y
y=Result
Print("Value of x after swapping",x)
Print("Value of y after swapping",y)
#Question4 of Task 1
#python version2x
input1=raw_input("Enter a number of your choice")
print input1
#... |
fb46bb5c6776602d06d6a435f07588cc8e89efc5 | bharaththippireddy/pythoncoreandadvanced | /exceptionhandling/demo.py | 561 | 3.71875 | 4 | import logging
logging.basicConfig(filename="mylog.log",level=logging.DEBUG)
try:
f = open("myfile","w")
a,b = [int(x) for x in input("Enter two numbers:").split()]
logging.info("Division in progress")
c = a/b
f.write("Writing %d into file" %c)
except ZeroDivisionError:
print("Division by zero... |
3dc3e68014bc9ed42ad2ebcff660ba585c55e7da | GermanDZ/rt_robots | /robot_python/flopezluis.py | 1,043 | 3.84375 | 4 | players = ('0','X')
turn = 0
exit = False
board = {0:'-', 1:'-',2:'-', 3:'-', 4:'-',5:'-',6:'-', 7:'-',8:'-'}
win_combinatios= [[0,1,2], \
[3,4,5], \
[6,7,8], \
[0,3,6], \
[1,4,7], \
[2,5,8], \
[0,4,8], \
... |
4290a8106e898c02be9530053a9aa047d100b04d | ibby360/python-crash-course | /chapter5/alien_color#2.py | 243 | 3.75 | 4 | alien_color = 'red'
if (alien_color == 'green'):
print("You have just earned 5 points.")
elif (alien_color == 'yellow'):
print('You have just earned 10 points.')
elif (alien_color == 'red'):
print('You have just earned 15 points.') |
9514d89696ef8c8e0ccfdd3467f73b9617f7e5dc | lixiang2017/leetcode | /problems/2348.0_Number_of_Zero-Filled_Subarrays.py | 1,055 | 3.640625 | 4 | '''
Runtime: 1087 ms, faster than 78.80% of Python3 online submissions for Number of Zero-Filled Subarrays.
Memory Usage: 24.7 MB, less than 30.39% of Python3 online submissions for Number of Zero-Filled Subarrays.
'''
class Solution:
def zeroFilledSubarray(self, nums: List[int]) -> int:
ans = zero = ... |
e6134713c76a332044b89c8fbfb7e525c198185e | wangpeibao/leetcode-python | /easy/easy796.py | 754 | 3.9375 | 4 | '''
796. 旋转字符串
给定两个字符串, A 和 B。
A 的旋转操作就是将 A 最左边的字符移动到最右边。 例如, 若 A = 'abcde',在移动一次之后结果就是'bcdea' 。
如果在若干次旋转操作之后,A 能变成B,那么返回True。
示例 1:
输入: A = 'abcde', B = 'cdeab'
输出: true
示例 2:
输入: A = 'abcde', B = 'abced'
输出: false
注意:
A 和 B 长度不超过 100。
通过次数9,860提交次数19,695
'''
class Solution:
def rotateString(self, A: str, B: str... |
3fd0f6838262c699cc6e3cc363e07b122843f6cd | Evidlo/advent_of_code | /2019/2/2.py | 934 | 3.5 | 4 | #!/bin/env python3
# Evan Widloski - 2019-12-01
def compute(noun, verb):
intcodes = list(map(int, open('input', 'r').read().split(',')))
intcodes[1] = noun
intcodes[2] = verb
index = 0
while True:
if intcodes[index] == 1:
intcodes[intcodes[index + 3]] = (
in... |
e4ad992eb44abc0a4f8591071109486c3cf185b6 | NenadGvozdenac/Python | /Pocetak/strings.py | 356 | 3.765625 | 4 | def main():
stringNiz = []
unesi_elemente(stringNiz)
ispisi_elemente(stringNiz)
def unesi_elemente(strNiz):
brEl = int(input("Unesite broj elemenata: "))
for i in range(0, brEl):
strNiz.append(str(input(f"Unesite string element {i}: ")))
def ispisi_elemente(strNiz):
print(strNiz)
i... |
532811fae765c4d3183e64376a0e0c93af603671 | yaolizheng/leetcode | /328/even_list.py | 549 | 4.125 | 4 | from linked_list import LinkedList, print_list
def even_list(head):
prev = head
cur = head.next
while cur and cur.next:
tmp = prev.next
prev.next = cur.next
cur.next = cur.next.next
prev.next.next = tmp
cur = cur.next
prev = prev.next
return head
if __... |
0c5137671720fb3a5e7349f492eac1413a4fe3cf | jaivrat/python_codes | /learn/python_algo/test_iqr.py | 1,054 | 3.84375 | 4 |
import math
import os
import random
import re
import sys
#
def interQuartile(values, freqs):
# Print your answer to 1 decimal place within this function
data = []
for i in range(len(values)):
data.extend([values[i]]*freqs[i])
data.sort()
#print(data)
if len(data)%2==0:
# even
... |
2d5b8f920c10f93f115e55fdda099058ac90b8ab | capic/installeur | /scripts/lib/menu/menu.py | 5,156 | 3.609375 | 4 | # -*- coding: utf-8 -*-
"""
"""
import os
MAX_COMMAND_KEY_LEN = 5
MENU_COMMAND_TEMPLATE = '%5s -> %s'
COMMAND_EXIT = 'E'
#define Exceptions
class MenuError(Exception): pass
class MissingVoicesError(MenuError): pass
class DuplicateKeyError(MenuError): pass
def clear_console():
try:
# Windows
... |
18c8ffd2d5f6379ec7e3c57783f1b2204187e2ba | czacarias905/Lab-5 | /Lab5P2.py | 372 | 4.5 | 4 | #Cecilia Zacarias
#2/13/2020
#This program prints each number in a new line these number are 12, 10, 32, 3, 66, 17, 42, 99, 20
#This program also prints each number and its square on a new line.
numbers = [12,10,32,3,66,17,42,99,20]
for x in numbers:
print(x)
squared =[12,10,32,3,66,17,42,99,20]
... |
45824edd3ac4f2dd2f97d4307379d83d394c39b1 | hack9521/python3-projects | /sum_squares.py | 342 | 3.53125 | 4 | # sum_squares=[i**2 for i in range(1,101)]
# print(sum(sum_squares))
# # total=[i for i in range(1,101)]
# # 5050*5050--applicable but hard coded
# total_square= #(sum(total))**2
# print(total_square)
# diff=total_square-sum(sum_squares)
# print(diff)
def problem6(r): return sum(r)** 2- sum([x** 2 for x in r])
print(pr... |
db319b29b890297db1dbebe583c48235328d0d8e | Ammy-Pond/PythonAcademy | /multiples 3or5.py | 162 | 4.03125 | 4 | 3 multiples 3 or 5
def solution(number):
sum1=0
for i in range(number):
if i%3==0 or i%5==0:
sum1=sum1+i
return sum1
solution(10) |
7407c80656bfd4e350a7e60a2fb4fdf5b20fdae7 | Ekeopara-Praise/python-challenge-solutions | /Ekeopara_Praise/Phase 2/SET/Day56 Tasks/Task4.py | 269 | 4.46875 | 4 | '''4. Write a Python program to find maximum and the minimum value in a set.'''
set1 = {1, 2, 3, 4, 5, 6, 7, 8}
max_val = max(list(set1))
min_val = min(list(set1))
print("The maximum value in the set is: ", max_val)
print("The minimum value in the set is: ", min_val) |
b9ac8cd582463f1970dfc812bd7c278dbf6d6839 | vdv85/PyNEng | /3/Задание 3.9 не решено.py | 1,012 | 3.890625 | 4 | '''
Найти индекс последнего вхождения элемента с конца.
Например, для списка num_list, индекс последнего вхождения элемента 10 - 4; для списка word_list, индекс последнего вхождения элемента 'ruby' - 6.
Сделать решение общим (то есть, не привязываться к конкретному элементу) и проверить на разных списках и элементах.
Н... |
7eb2fa92a03e55a225218424f582c6b3a08f2fba | hy299792458/LeetCode | /python/92-reverseLinkedList.py | 672 | 3.71875 | 4 | # Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def reverseBetween(self, head, m, n):
m, n = min(m, n), max(m, n)
res = ListNode(0)
res.next = head
tail = res
... |
5b055dfac45a11c88fa356137410d80bc5db5aac | pguiffr62/Engineering_4_Notebook | /Python/stringsnloops.py | 160 | 4.03125 | 4 |
print("Write a simple sentence")
sentence = input(" ")
print(sentence.split('-'))
for letter in sentence:
print(letter)
|
5f7e810f56fb142f6d1ad68799dc8d4ef294785c | haripriya2703/KNN_Using_SmallWorldGraphs | /KNN_Classifier.py | 1,155 | 3.71875 | 4 | from KNN_Search import knn_search
def knn_classifier(knn_graph, distance_metric, d, m, k):
"""
:param knn_graph: existing graph
:param distance_metric: metric using which the nearest neighbors should be determined
:param d: new data point
:param m: number of searches to be performed
:param k: ... |
7c3251a556bc23ba25291ab119a0499c25cc1c09 | karenwsit/ToyProblems | /linked_lists/sum_lists.py | 2,427 | 3.859375 | 4 | #Exercise 2.5 of Cracking the Coding Interview
#You have 2 numbers represented by a linked list where each node contains a single digit. The digits are stored in reverse order such that the 1's digit is at the head of the list. Write a function that adds the 2 numbers and returns the sum as a linked list
##############... |
18ada1559c701e475ef0a50983a8eb6a977b97d7 | danielkim107/Codeforces_Practice | /CodeForces/Petya_And_Strings.py | 238 | 3.734375 | 4 | import sys
inf = sys.stdin
first_word = str(inf.readline()).lower().strip()
second_word = str(inf.readline()).lower().strip()
if first_word == second_word:
print(0)
elif first_word > second_word:
print(1)
else:
print(-1)
|
450968994c45e916935c317e24c3ab4f9bfa6a5d | LONG990122/PYTHON | /第一阶段/4. Python03/day04/day03_exercise/02_zhiyinshu.py | 1,142 | 4.28125 | 4 | # 2. 分解质因数,输入一个正整数,分解质因数:
# 如:
# 输入: 90
# 打印:
# 90=2*3*3*5
# (质因数是指最小能被原数整数的素数(不包括1))
def is_prime(x):
'''判断 x是否为素数'''
if x <= 1:
return False
for i in range(2, x):
if x % i == 0:
return False
return True
def get_prime_list(n):
'''此函数根据给定一个整数,返回此... |
32eaff1bfbf19a7d5216b2fcc8d590b7ba45f61f | keshavvinayak01/alorithms_cse | /numberToDecimal.py | 327 | 3.609375 | 4 | def toDecimal(n,b):
res = 0
multiplier = 1
while(n>0):
res += (n%10)*multiplier
multiplier *= b
n = n/10
return res
n,b = raw_input("enter the number and base to be converted to decimal").strip().split(' ')
n,b = [int(n),int(b)]
result = toDecimal(n,b)
print(result)
... |
f07a7cce8fc23ab14958ea7d5c8d48820b6b70e7 | erickgust/python-exercises | /mundo-01/ex028.py | 318 | 3.859375 | 4 | from random import randint
from time import sleep
print('Pensando... Um número entre 0 e 5...')
r = randint(0, 5)
p = int(input('Em qual número eu pensei? '))
print('PROCESSANDO...')
sleep(2)
if p == r:
print('PARABÉNS! Você acertou!')
else:
print('Não foi dessa vez! O número correto era {}!'.format(r)) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.