blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
3a448e5e06a0567d8e94364228315a05e77f3a3f | KostadinHamanov/HackBG-Programming101-3 | /week03/2-Retrospective/Fractions_test.py | 1,119 | 3.921875 | 4 | import unittest
from fractions import Fraction
class FractionTest(unittest.TestCase):
def setUp(self):
self.a = Fraction(1, 2)
self.b = Fraction(2, 4)
def test_is_instance(self):
self.assertTrue(isinstance(self.a, Fraction))
self.assertTrue(isinstance(self.b, Fraction))
... |
0b30f11faa64486634310a93db3aee9d47ecc71c | skaspy/pythonCollection | /amount_of_words_file.py | 152 | 4 | 4 | # Counting the amount of words in a text file
file = open(input('File name: '), 'r')
text = file.read()
output = text.split()
print(len(output))
|
6f5d10a2a589fa77aff58b35a46432256f58f203 | jamiejamiebobamie/Herd_Immunity | /Herd_Immunity_Project/logger.py | 5,563 | 3.90625 | 4 | class Logger(object):
'''
Utility class responsible for logging all interactions of note during the
simulation.
_____Attributes______
file_name: the name of the file that the logger will be writing to.
_____Methods_____
__init__(self, file_name):
write_metadata(self, pop_size, vacc... |
83d63125b3c9cfaf26037b1a0736d8ebf9032701 | nguy2261/portfolio | /PythonProject/gradeAnalyzer.py | 2,679 | 3.75 | 4 | from os import path
import math
import sys
def openfile():
fname = input("Enter filename: ")
count = 0
while not path.isfile(fname) and count < 2:
count += 1
fname = input("File not found. Please re-enter: ")
if path.isfile(fname):
opfile = open(fname,'r')
return opfile
else:
return None
#... |
9c45008a1ab3cdb30730fd0d91d5ab615ea29bbf | ivan-yosifov88/python_advanced | /list_as_stack_and_queues_exercise/fashion_boutique.py | 364 | 3.59375 | 4 | clothes_in_box = [int(number) for number in input().split()]
capacity = int(input())
rack = 1
clothes_for_current_rack = 0
while clothes_in_box:
clothes = clothes_in_box.pop()
if clothes_for_current_rack + clothes <= capacity:
clothes_for_current_rack += clothes
else:
clothes_for_current_ra... |
906848aea8fe923f6779d30ca6f549935bc06fa0 | anusharp97/Leetcode | /longestSubarray.py | 1,271 | 3.96875 | 4 | '''
1493. Longest Subarray of 1's After Deleting One Element
Given a binary array nums, you should delete one element from it.
Return the size of the longest non-empty subarray containing only 1's in the resulting array.
Return 0 if there is no such subarray.
Example 1:
Input: nums = [1,1,0,1]
Output: 3
Explanation: ... |
f13e406886053a811a91494788ad7edd3e21f46e | MinaPecheux/Advent-Of-Code | /2015/Python/day13.py | 4,178 | 4.125 | 4 | ### =============================================
### [ ADVENT OF CODE ] (https://adventofcode.com)
### 2015 - Mina Pêcheux: Python version
### ---------------------------------------------
### Day 13: Knights of the Dinner Table
### =============================================
from itertools import permutations
# [ ... |
5d08d5887bdbec0e53503488d9269b79d1c1754e | andres4423/Andres-Arango--UPB | /Numpy/Ejercicio19.py | 840 | 4.4375 | 4 | print("Write a NumPy program to get the unique elements of an array.")
print("Expected Output: Original array: [10 10 20 20 30 30] Unique elements of the above array: [10 20 30] Original array: [[1 1] [2 3]] Unique elements of the above array: [1 2 3]")
print("Escriba un programa NumPy para obtener los elementos únic... |
6cca3d87639c73171ce363ef55350fd64d95c3a7 | MattSi98/1110-Space-Invaders | /a7/Invaders/models.py | 14,172 | 3.8125 | 4 | """
Models module for Alien Invaders
This module contains the model classes for the Alien Invaders game. Anything that you
interact with on the screen is model: the ship, the laser bolts, and the aliens.
Just because something is a model does not mean there has to be a special class for
it. Unless you need something... |
9aed0e027cf4075bc17dec9df3230396d1251d18 | aayushmanntiwari/-AutomationwithPython | /Functions/Add.py | 772 | 3.515625 | 4 | import openpyxl as xl
# Add function
def Add():
wb = xl.load_workbook('') # write the spreedsheet(.xlsx) file name here you to Update
sheet = wb['Sheet1']
y = int(input("Enter the targeted row where value start: "))
z = int(input("Enter the target column where these value belong: "))
m = int... |
67f8d75315e3015d56024e9651be2c5fb347e214 | janlee1020/Python | /shapeCalculator.py | 2,086 | 4.3125 | 4 | #shapeCalculator.py
from math import pi
def rectArea(length, width):
area=length * width
return area
def circleArea(radius):
area=pi*radius*radius
return area
def welcome():
print("Welcome to the shape calculator!")
name=input("What is your name? ")
return name
def askDim... |
dcc8400d291da0c1f1d18801e9997c1858cf3454 | merlin0509/MiniProjects01 | /hangman.py | 671 | 3.828125 | 4 | def find(s, ch):
return [i for i, ltr in enumerate(s) if ltr == ch]
def hangman():
word="secret"
turns=len(word)
guess=["_" for i in range(turns)]
print(" You have ",turns,"turns")
print("Start guessing the word*****")
while(turns>0):
uchar=input("Enter guess \n")
turns=turns-1
if uchar not ... |
945ab29af0a66c1f38423affec72e58e22e2f778 | minwinmin/Atcoder | /ABC175/B.py | 1,248 | 3.671875 | 4 | """
三角形の成立条件
https://mathtrain.jp/seiritu
三角形の成立条件(存在条件):三辺の長さが a,b,c である三角形が存在する必要十分条件は,
a+b>c かつ b+c>a かつ c+a>b
http://physics.thick.jp/Mathematics_A/Section5/5-3.html
abs(L[i]-L[j])<L[k]<L[i]+L[j]
"""
def listExcludedIndices(data, indices=[]):
return [x for i, x in enumerate(data) if i not in indices]
N = int(i... |
0de144e280a53a01b0ffe4eb0bed3dd559fd5b27 | GigaVision/CrowdCountingTools | /cc_evaluate_tools.py | 1,365 | 3.734375 | 4 | import math
'''
Tool to calculate 3 metrics of crowd counting results.
The crowd distribution of this crowd counting task is represented by crowd number vector.
First, the whole image will be divided into 1x1, 4x4, 8x8 blocks.
After that, the number of human in each block will be estimated.
Finally, the crow... |
0ed4a67a26ddd7b7182f0d3fcfb5a9d42f740fc1 | jeffreytzeng/Dcoder | /easy/003. Learning User Input with Natural Numbers/sum_numbers.py | 90 | 3.8125 | 4 | integer = int(input())
total = 0
for i in range(1, integer+1):
total += i
print(total) |
0e8054f2045c8d185646e8969b1b94c9f13d1041 | Nahida-Jannat/testgit | /bubble_sort.py | 730 | 4.125 | 4 | # Bubble Sort Implementation
# n = 5
# for i in range(0, n):
# print('Loop 1: i-%d\n-----------' % i)
# for j in range(0, n-i-1):
# print('j-', j)
def bubble_sort(data_list):
n = len(data_list)
for i in range(0, n): # n=5 (0, 5) --> 0, 1, 2, 3, 4
print('Loop 1: i-%d\n-----'... |
6b1868571e93d4604d9e57f7b0d01f3b75f83e89 | nishantchaudhary12/Starting-with-Python | /Chapter 8/gasPrices.py | 3,506 | 3.734375 | 4 | #Gas Prices
def average_price_per_year():
file = open("GasPrices.txt", "r")
price = file.readline()
price = price.strip('\n')
price_dict = dict()
while price != '':
price_list = price.split(':')
year = price_list[0].split('-')
if year[2] in price_dict:
price_d... |
9b1472191a7e5334f2e93cb29e2e32c5509f5f75 | ShriBuzz/IW-PythonLogic | /Assignment I/Functions/15.py | 145 | 4.03125 | 4 | # Write a Python program to filter a list of integers using Lambda.
lis = [2,3,4,1,6]
even = list(filter(lambda x: x%2 == 0, lis))
print(even) |
2fa1202df4a280fb46cbf6f4c37efcfe097bb268 | scimaksim/Python | /tax.py | 953 | 4.4375 | 4 | # -----------------------------------------------------------------------------
# Name: Tip
# Purpose: Tip calculator
#
# Author: Maksim Nikiforov
# Date: 09/129/2016
# -----------------------------------------------------------------------------
"""
Tip calculator assuming an 8.75% tip rate
Pro... |
650aab5e0ee73a1ef99735fe82f4f23aea4e8ed1 | Jian-jobs/Jian-leetcode_python3 | /Solutions/165_ Compare Version Numbers.py | 3,187 | 3.96875 | 4 | '''
165. Compare Version Numbers
https://leetcode.com/problems/compare-version-numbers/
Compare two version numbers version1 and version2.
If version1 > version2 return 1;
if version1 < version2 return -1;
otherwise return 0.
You may assume that the version strings are:
non-empty and contain only digits and the . ch... |
c70e3556de2243ce710cc0e31b2e035e324b2371 | Minkov/python-oop-2021-02 | /inheritance/lab/stack.py | 420 | 3.71875 | 4 | class Stack:
def __init__(self):
self.data = []
def push(self, value):
self.data.append(value)
def pop(self):
return self.data.pop()
def peek(self):
return self.data[-1]
def is_empty(self):
return len(self.data) == 0
def __repr__(self):
return... |
f4d6433206f3ba0dfdea1af14baea7b98f58b596 | JuDa-hku/ACM | /leetCode/116PopulatingNextRightPointersinEachNode.py | 668 | 3.859375 | 4 | # Definition for binary tree with next pointer.
# class TreeLinkNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
# self.next = None
class Solution:
# @param root, a tree link node
# @return nothing
def connect(self, root):
if n... |
63322cf6e40e4efbf21c9116d11f5ffa24deb3dd | glushenkovIG/PythonTasks | /class/Poly-2.py | 17,293 | 3.609375 | 4 | import copy
import copy
class Fraction:
def __init__(self, x = '', y = 0):
if type(x) == Fraction:
self.a = x.a
self.b = x.b
elif x == '' and y == 0:
self.a = 0
self.b = 1
elif y == 0:
if '/' in str(x):
self.a, s... |
f22101e69a4d805d8852fdf0aa5e3d907a987cb1 | PrzemoPoz/p1 | /zjazd2/funkcje/slack5.py | 557 | 3.890625 | 4 | # Napisz program, który wczyta od użytkownika liczbę X, a następnie wyświetli TRÓJKĄT prostokątny o długości przyprostokątnej X,np.: 5 ->
# *
# * *
# * *
# * *
# * * * * *
def trojkat_prostokatny(x):
i = 1
while i <= x:
j = 1
napis = ''
while j <= x:
if i == x or j==1 ... |
2842f4bfd62fe8f900ad916c47f26259e66cf3af | Moreland-J/CS4099 | /cs4099/src/csvSort.py | 1,502 | 3.75 | 4 | import csv
db = []
def run():
readDB()
quickSort(1, (len(db) - 1))
writeCSV()
readDB()
def readDB():
# https://realpython.com/python-csv/
print()
with open('database/db.csv') as file:
reader = csv.reader(file, delimiter = ',')
count = 0
for col in reader:
... |
d1afc84041d9bc3259ab058f911f4babcc1ca6be | Santigre/Basic_pythons | /python/hero_game/hack_slash.py | 2,297 | 3.78125 | 4 | '''
Python 2
Author: Santiago Beltran
Going to make a text game where there is a hero
fighting off an infinante amount of monsters
'''
import random, hero_class
def start(hero = "", health = 10, attack = 3):
hero = intro_game(hero, health, attack)
smonster = intro_monsters(smonster = "", smheal... |
45ab6e9350008ba2139154efcf0efd8c37362a99 | typd/basicplib | /basicplib/util/timeutil.py | 710 | 3.640625 | 4 | import time
import datetime
#curr_time_int = lambda: int(time.time())
def curr_time_int():
return int(time.time())
def format_duration(duration):
if duration < 60:
return '0:{0:02d}'.format(duration)
elif duration < (60 * 60):
minutes = duration // 60
seconds = duration - (minutes... |
21f5f6eda4c9f566a71fa6e0bf10ff275e2b5b3e | RossMeikleham/DailyProgrammer | /Easy/Challenge227/Challenge227.py | 3,145 | 4.09375 | 4 | import math
from decimal import Decimal
def getPoint(s, n) :
if n > (s**2) or n <= 0 or (s & 0x1 != 0x1):
print("Error expected n > 0 and n < s^2, and s to be odd")
else:
#Obtain co-ordinates for center of the spiral
center = (s + 1) / 2
#Next obtain the "level" that the gi... |
0d5f75734fb927cfe4cf591d2af71e91ab0dddf1 | sevo/FLP-2020 | /5/cvicenie/sections/module_3.py | 3,072 | 4 | 4 | #
# Module 3. Simple exercises including I/O ( Input/Output )
#
# Simple exercises to use I/O functins and the `re` module.
# Documentation for input and output in python can be found in the following link.
# http://docs.python.org/2/tutorial/inputoutput.html
#
import re, time, random
# from module_1 import is_palindro... |
a8bcb0a86719ca5fde3b603af951445495d16fdd | AdamZhouSE/pythonHomework | /Code/CodeRecords/2533/60660/235296.py | 234 | 3.8125 | 4 | orgstr=input()[1:-1].split(',')
org=[int(orgstr[i]) for i in range(len(orgstr))]
odd=[]
even=[]
for num in range(len(org)):
if not org[num]%2==0:
odd.append(org[num])
else:
even.append(org[num])
print(even+odd) |
b7fd5bf1ef532bdb8e0b0eae5a69a19c54c9de82 | davidissimo/pythonProject1 | /Mood_checker.py | 207 | 3.84375 | 4 | mood = "uau" #Nervous
if mood == "happy":
print("It is great to see you happy!")
elif mood == "Nervous":
print("Take a deep breath 3 times.")
else:
print("I don't recognize this mood")
|
4e6923255b547a9ed4a34e70ea30b3be2251a4ea | ankitbrahmbhatt1997/Python-Datastructures-and-ALgorithms | /codility/sieve_of_eratosthenes/factorization.py | 613 | 3.609375 | 4 | def pre_factorization(n):
sieve = [0]*(n+1)
i=2
while i*i <= n:
if sieve[i] == 0:
if sieve[i] == 0:
k = i*i
while k <= n:
if sieve[k] == 0:
sieve[k] = i
k+=i
i+=1
return sieve
d... |
b57066bb9c770b831aa7c04e5a54fe3043d58a60 | sonam2905/My-Projects | /Python/Leetcode/88_merge_sorted_array.py | 658 | 3.828125 | 4 | class Solution:
def merge(self, nums1: [int], m: int, nums2: [int], n: int) -> None:
"""
Do not return anything, modify nums1 in-place instead.
"""
last = m + n - 1
while n > 0 and m > 0:
if nums1[m - 1] > nums2[n - 1]:
nums1[last] = nums1[m-1]
... |
a9c8f176519c63c8fc90c07fc244e903fd1bfb07 | aka5hkumar/python | /cb3157.hw3.q3.py | 735 | 4.34375 | 4 | print('Please input 3 values for the equation ax^2 +bx + c')
a = float(input('Enter value for a: '))
b = float(input('Enter value for b: '))
c = float(input('Enter value for c: '))
discriminant = b**2 - 4*a*c
root1 = -b / 2*a
#In calculus, the discriminant this tells us of nature of quadratic roots
if (a == 0 and b == ... |
c8a7bb8c1e4adeec219be47bc3f33d38eff47496 | dslachar/data-vis | /assignments/assignment1/assignment1.py | 3,201 | 3.828125 | 4 | # David LaCharite
import numpy as np
import pandas as pd
import math
# Part 1
print('-----------------------PART 1-----------------------')
# Read Elements CSV into a pandas data frame
df_elements = pd.read_csv('elements.csv')
# add ninth and tenth elements to dataframe
df_elements.loc[len(df_elements)]=['Fluorine',... |
39b1e5309b0c38cbfbc472a9cdbac8653ad61b12 | anshi9061/Python | /oops.py | 1,345 | 4.21875 | 4 | #class
class simple:
def hai(self):
print("hai")
a=simple()
a.hai()
#constructor
class welcome:
def __init__(self,name):
self.name=name
def display(self):
print("name:" +self.name)
x=welcome("Ansheena")
x.display()
#destructors
class world:
def __init__(se... |
93748cf25f84e647ef4c2ea60b54baa1e57a503b | SuYOUNGgg/JavaStudy | /Python/0525/test.py | 718 | 4.15625 | 4 | colors = ['white','red','green','blue']
print(colors)
colors.sort()
print(colors)
print(sorted(['white','red','green','blue']))
def mysort(x):
return x[-1]
print(mysort('white'),mysort('red'))
colors2 = ['white','red','green','blue']
colors2.sort(key=mysort)
print(mysort('white'),mysort('red'),mysort('green'),my... |
2e5747a1ef29105c0aa7acecbf41dbd6f1e84a8f | Lucakurotaki/ifpi-ads-algoritmos2020 | /Iteração FOR/Fabio 03/f03_q15_sequencia_n.py | 247 | 3.921875 | 4 | def main():
n = int(input("Digite um número positivo: "))
if n < 1:
print("Erro. Digite um número maior do que 0.")
else:
num = 1
for i in range(2, n+2):
print(num)
num += i
main()
|
051b7c8dedb0ece874975f10c4dd90fe8e23f13d | johnkim9/python_crash_course | /rivers.py | 1,353 | 4.28125 | 4 | rivers = {
'nile':'egypt',
'seine':'france',
'han':'korea',
'potomac':'us',
'rhine':'germany'
}
for name, country in rivers.items():
print("The " + name.title() + " runs through " + country.title() + ".")
#Nesting
alien_0 = {'color':'green','points':5}
alien_1 = {'color': 'yellow','points':10}
alien_2 = {'color... |
eca89a8874e72505a0b88ce26b133158ab22cfde | taylor-swift-1989/PyGameExamplesAndAnswers | /examples/minimal_examples/pygame_minimal_rotate_to_target_intersect_laser.py | 6,134 | 3.671875 | 4 | # pygame.transform module
# https://www.pygame.org/docs/ref/transform.html
#
# Shooting a bullet in pygame in the direction of mouse
# https://stackoverflow.com/questions/60464828/calculating-direction-of-the-player-to-shoot-pygame
#
# GitHub - PyGameExamplesAndAnswers - Move towards target - Move towards target Shoot ... |
ec01cb4afa6305f04c402a32589a857cf7844dcb | duochen/Python-Beginner | /Lecture05/Homework/solution04.py | 268 | 3.9375 | 4 | class Circle():
def __init__(self, r):
self.radius = r
def area(self):
return self.radius**2*3.14
def perimeter(self):
return 2*self.radius*3.14
c = Circle(8)
print(c.area()) # => 00.96
print(c.perimeter()) # => 50.24
|
a54b42d101997996c9cc029285c11510a1596a42 | rosemincj/PythonLearning | /regex.py | 951 | 3.859375 | 4 | import re
sample_str = 'an example word:cat!!'
match = re.search(r'word:\w\w\w', sample_str)
# If-statement after search() tests if it succeeded
if match:
# 'found word:cat'
print('found', match.group())
else:
print('did not find')
# found, match.group() == "iii"
match = re.search(r'iii', 'piiig')... |
57c5cefdff0bba9047bb990a0eb0eac75df1e508 | DCWhiteSnake/Data-Structures-and-Algo-Practice | /Chapter 2/Creativity/C-2.32.py | 483 | 3.578125 | 4 | import math
from Progression import Progression
class ProgressionEx(Progression):
def __init__(self, first = 65536):
"""Extends the Progression class
each value in the progression is the square root of the previous progression
"""
super().__init__(first)
self._count = 0
... |
21345b80a0e6c3748f8319b5b99683fed18ce6dd | dontbitme/lodowka | /lodówka.py | 2,511 | 3.640625 | 4 | # -*- coding: utf-8 -*-
class Lodowka(object):
def __init__(self):
self.products = []
self.temperature = None
self.status = False
def find_products_index(self, product_name):
for index in range(len(self.products)):
if self.products[index].name == product_name:... |
9a345fbace167725b8fdaf61cb761f12acea2283 | N66630/hyLib | /myFirst/015_class.py | 5,618 | 3.984375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sun Nov 12 23:11:58 2017
@author: Administrator
"""
print ('\nclass 用大寫字母開頭命名 (function 用小寫字母)')
class Turtle:
#屬性
color = 'green'
weight = 23
legs = 4
#方法
def climb(self):
print ('我正在爬')
def run(self):
print ('我正在跑')
def jump... |
10c0276024fec46d387d215db1d3d3b189fd6588 | EverydayQA/prima | /pytools/other/fsample/hello.py | 56 | 3.578125 | 4 | name = input('xxx')
print name
# print("Hello " + name)
|
b6084466d8570d3e36d426cac046451a9e49ad88 | Easyjuhl/ConsoleCardcasterDeck | /ConCardCast.py | 2,561 | 3.671875 | 4 | from random import randrange
from utils import CardlistWork
CardcasterLvl = int(input("What is your cardcaster level: "))
HandSizeMax = 1
MajArcPla = 2
if CardcasterLvl > 9:
MajArcPla = 8
elif CardcasterLvl > 7:
MajArcPla = 7
elif CardcasterLvl > 5:
MajArcPla = 6
elif CardcasterLvl > 3:
MajArcPla = 5
... |
e3fd15381b8f09265bbb34ea6f07390211645b7f | Sametcelikk/Edabit-Solutions-Python | /Medium/3-) Right Shift by Division.py | 713 | 4.71875 | 5 | """
The right shift operation is similar to floor division by powers of two.
Sample calculation using the right shift operator ( >> ):
80 >> 3 = floor(80/2^3) = floor(80/8) = 10
-24 >> 2 = floor(-24/2^2) = floor(-24/4) = -6
-5 >> 1 = floor(-5/2^1) = floor(-5/2) = -3
Write a function that mimics (without the use of >>... |
820917ba3285af00bf124db0e9bc6d9ed491cf9c | chaehyeon119/Python | /CollectionList/python05_12_CollectionList09_김채현.py | 369 | 3.765625 | 4 | #python05_12_CollectionList09_김채현
# 리슽트에 포함된 요소 x의 개수 세기(count)
a=[1,2,3,1]
print(a.count(1))
print('-'*15)
'''
리스트 확장(extend)
extend(x)에서 x에는 리스트만 올 수 이씅며 원래의
a 리스트에 x리스트를 더한다.
'''
a=[1,2,3]
a.extend([4,5])
print(a) #[1,2,3,4,5]
#a.extend([4,5])는 a+=[4,5]와 동일 |
75aff426166b04a8a72d4520aed1e938ee0afae3 | rubens-lavor/projeto-final-E.D.O. | /teste.py | 562 | 4 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Sep 17 09:45:28 2019
@author: rubens
"""
"""
faça um programa que leia um número qualquer
e mostre o seu fatorial"""
from math import factorial
f=factorial(5)
print (f)
""" outra forma """
fat=1
n=5
#n= int(input('digite um número para calcular o f... |
ee4de305c27cad23fa889eaf9d0e1ae76f868c47 | shwetakharche/Vlink-Codes- | /question2_shwetaKharche.py | 402 | 3.734375 | 4 | def Prefix( a):
length = len(a)
if (length == 0):
return ""
if (length == 1):
return a[0]
a.sort()
end = min(len(a[0]), len(a[length - 1]))
i = 0
while (i < end and
a[0][i] == a[length - 1][i]):
i += 1
pre = a[0][0: i]
return pre
if __name__ == "__main__":
List=[]
n=int(input())
for i in... |
cc2312f4db0a8a0e6faae7ad7065d66d89864c8d | eazapata/python | /Ejercicios python/PE3/PE3E2.py | 329 | 3.984375 | 4 | #PE2E2 Eduardo Antonio Zapata Valero
#Pida al usuario el espacio recorrido por un coche y el tiempo que ha tardado en
#horas y que calcule a qué velocidad media había realizado el recorrido.
km=float(input("Cuanto espacio ha recorrido en KM "))
tmp=float(input("Cuantas horas ha tardado "))
vel=(km/tmp)
print("La veloci... |
ba87b64ba49f151c62636b858f7cddacab0618e5 | mariuspodean/CJ-PYTHON-01 | /lesson_21/mapping_mihaela.py | 247 | 3.953125 | 4 | import itertools
items = [1, 2, 3, 4, 5]
def multiply(x):
return x * x
def add(x):
return x + x
my_list = list(map(lambda x: (add(x), multiply(x)), items))
my_new_list= list(itertools.chain.from_iterable(my_list))
print(my_new_list)
|
993902cd5cda4fb045be591cb08ab8fbbfa72389 | tenmilliondollars/PythonHW | /hw5.py | 257 | 3.5625 | 4 | a=input('Введите целые неотрицательные числа:\n')
a=a.strip()
a=a.split(" ")
for i in range(len(a)):
a[i]=int(a[i])
a=sorted(a)
b=1
for i in range(len(a)):
if b not in a:
break
else:
b=b+1
print(b) |
5b03ef61eccfff6df06c7eb422bf65dccea359d8 | luisoto076/Redes2017 | /practica1/Code/ScientificCalculator.py | 1,216 | 3.890625 | 4 | #! /usr/bin/env python
# -*- coding: utf-8 -*-
from Constants import Constants as cons
import Calculator
'''
Clase para la funcionalidad de la calculadora cientifica
Extiende a la clase Calculator
'''
class ScientificCalculator(Calculator.Calculator):
'''
Metodo que obtiene el resultado de la operacion solicita... |
78880c898ea3d72fd7ed8de75e6ad3d75b0291fa | qtvspa/offer | /List/linklist_base.py | 2,415 | 3.921875 | 4 | # -*- coding:utf-8 -*-
class ListNode(object):
""" 链表节点类 """
# p即模拟所存放的下一个结点的地址, 为了方便传参, 设置p的默认值为None
def __init__(self, data, p=None):
self.data = data
self.next = p
class LinkList(object):
"""
简单的单链表类
"""
def __init__(self):
self.head = None
# 链表初始化函数
... |
0eea426a667f15f23a6fcbb2362fb2e3766768f4 | ShowenPeng/vyper-by-example | /memo/events.py | 591 | 3.984375 | 4 | """
pseudo code to list all authorized addresses
python3 events.py
"""1
events = [{
"block": 1,
"addr": "0x01",
"approved": True
}, {
"block": 2,
"addr": "0x02",
"approved": True
}, {
"block": 3,
"addr": "0x03",
"approved": True
}, {
"block": 4,
"addr": "0x01",
"approved... |
20a0db86cd1177dce49b981c3a64e4511fea7d93 | daniellopes04/uva-py-solutions | /list5/10168 - Summation of Four Primes.py | 978 | 3.875 | 4 | # -*- coding: UTF-8 -*-
import math
def checkIsPrime(num):
s = int(math.sqrt(num))
for i in range(2, s + 1):
if (num % i == 0):
return False
return True
def getPrimes(num):
primes = [0, 0]
for i in range(2, int(num / 2) + 1):
if (checkIsPrime(i) and checkIsPrime(num - i)):
... |
82f454a01455f08fe95a0a41f5cb619e11114fb6 | SsmallWinds/leetcode | /codes/69_sqrtx.py | 824 | 4.375 | 4 | """
实现 int sqrt(int x) 函数。
计算并返回 x 的平方根,其中 x 是非负整数。
由于返回类型是整数,结果只保留整数的部分,小数部分将被舍去。
示例 1:
输入: 4
输出: 2
示例 2:
输入: 8
输出: 2
说明: 8 的平方根是 2.82842...,
由于返回类型是整数,小数部分将被舍去。
见图 newton.png, 牛顿迭代法
平方根即为方程 f(x) = x^2 + a 的正数解
不断的计算 下一个Xn, 即可慢慢逼近正确值
Xn+1 = Xn - f(Xn)/f'(Xn)
带入f(x) 可得
Xn+1 = Xn - (Xn - a / Xn) / 2 => X... |
4b25976982cfd87ed2830e860f7ab54c2d196500 | pradpalnis/Machine-Learning | /Python/Python_Example/Inheritance.py | 3,221 | 4.125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Tue Mar 5 12:40:05 2019
@author: PP00495588
"""
# A Python program to demonstrate inheritance
# Base or Super class. Note object in bracket.
# (Generally, object is made ancestor of all classes)
# In Python 3.x "class Person" is
# equivalent to "class Person(object)"
cla... |
a810350bc0e9c5c0c0d8e9c8248766da135c724f | fopineda/ShopTracker | /ShopTracker.py | 2,047 | 4.21875 | 4 | from array_queue import ArrayQueue
""" Tracks a shop's list of clients using a queue """
""" By Felipe Pineda 4/2/16 """
""" <fopineda95@gmail.com """
class ShopTracker:
def __init__(self):
self._listQueue = ArrayQueue()
def startDay(self):
""" Starts the day off by startin... |
f80ddc2e20cdff8fb0fb755368a81f2b6933cf2a | v0dro/scratch | /python_shizzle/roads-and-libraries.py | 1,337 | 3.765625 | 4 | import copy
# https://www.cs.cmu.edu/afs/cs/academic/class/15210-f14/www/lectures/mst.pdf
# graph can have many spanning trees, but all have|V|vertices and|V|−1 edges.
def make_adjacency_list(n, cities):
matrix = {}
for i in range(n):
matrix[i] = dict()
for i, j in cities:
matrix[i-1][j-... |
9ce753fba0f2840fd9b734b203bfe4da87aff978 | Lusarom/progAvanzada | /ejercicio94.py | 444 | 3.890625 | 4 |
from random import randint
SHORTEST = 7
LONGEST = 10
MIN_ASCII = 33
MAX_ASCII = 126
def randomPassword():
randomLength = randint(SHORTEST, LONGEST)
result = ''
for i in range(randomLength):
randomChar = chr(randint(MIN_ASCII, MAX_ASCII))
result += randomChar
return... |
6459c19c2fdaaa32029f071247093ae5c86cded9 | duanwenhuiIMAU/my_code | /al.py | 7,810 | 3.5625 | 4 | class Node:
def __init__(self,list = [],parent = None):
self.list = list
self.parent = parent
def up(self):
listchild = self.list.copy()
for i in range(len(listchild)):
if(listchild[i]==0 and i>2):
temp = listchild[i]
listchild[i] = lis... |
994d23b5f69d1fa674a609b9a3e2d88b37d7a8b0 | caiolucasw/pythonsolutions | /exercicio2.py | 490 | 3.828125 | 4 | def fatorial(numeros):
fatoriais = []
num = 1
lista = converteInteiro(numeros)
for i in lista:
for numero in range(1,i+1):
num *= numero
fatoriais.append(str(num))
num = 1
print(','.join(fatoriais))
def converteInteiro(lista):
listaInt = []
fo... |
f7a6b53e7eecd5911c1bf9e0929636f57325d65e | coder-hello2019/Stanford-Algorithms | /Week 3/quicksort1.py | 2,547 | 4.0625 | 4 | """
Implementation of quicksort for week 3 of Stanford's algorithms course, which also counts the number of comparison in the given quicksort iteration.
In this iteration (for part 1 of pset 3), the pivot is always the first element of the unsorted array.
"""
import random
def quicksort(unsorted):
if len(unsorte... |
f2a81481ccc9626de8b7718f99686bf8eae2a383 | PatrickNgare/Python-lati-game | /paridome.py | 128 | 4.15625 | 4 | name=input("enter a string")
name2=name[::-1]
if name==name2:
print("is a paridrome")
else:
print("is not a paridrome")
|
93427d777bc38e85449277c260b26d47f9c015f9 | Wbonney88/Tech-Academy-Projects | /Python/Item_62.py | 1,080 | 3.546875 | 4 | import datetime
class EST(datetime.tzinfo):
def utcoffset(self, dt):
return datetime.timedelta(hours=-4)
def dst(self, dt):
return datetime.timedelta(0)
class UTC1(datetime.tzinfo):
def utcoffset(self, dt):
return datetime.timedelta(hours=+1)
def dst(self, dt):
return... |
1abcbe7b77828f5f1b76d490e1ec548ea447ab11 | Aliena28898/Programming_exercises | /CodeWars_exercises/The falling speed of petals.py | 925 | 3.90625 | 4 | '''
When it's spring Japanese cherries blossom, it's called "sakura" and it's admired a lot. The petals start to fall in late April.
Suppose that the falling speed of a petal is 5 centimeters per second (5 cm/s), and it takes 80 seconds for the petal to reach the ground from a certain branch.
Write a function that re... |
f0618d37529d75675ca971edef5b41f12918c855 | jiangorbit/Rhymego | /seq_search.py | 507 | 3.828125 | 4 | #!/usr/bin/env python3
def sequence_search(sequence, target):
#for i in range(len(sequence)):
# if target == sequence[i]:
# return i
# else:
# return None
i = 0
while i <= len(sequence):
if target == sequence[i]:
return i
else:
i +... |
7a4eb01f16e2822c84f2a4fb531ef74dc11b0340 | minirgb2019/Classification_Titanic | /Classification Titanic2.py | 15,455 | 4.15625 | 4 | #!/usr/bin/env python
# coding: utf-8
# In[1]:
#Classification Project
# In this project you will perform a basic classification task.
# You will apply what you learned about binary classification and tensorflow to implement a Kaggle project without much guidance. The challenge is to achieve a high accuracy score wh... |
bbe1872a39d2710e533562a61ad3b6608aeef04c | Kawser-nerd/CLCDSA | /Source Codes/CodeJamData/11/31/5.py | 775 | 3.515625 | 4 | #!/usr/bin/env python3.1
from __future__ import division
import sys
def calc(numLines, line):
ok = True
while ok:
ok = False
for i in range(len(line)):
f = line[i].find("#")
if f >= 0:
if i == len(line) - 1 or f == len(line[i]) - 1 or line[i][f:f+2] != "##" or line[i+1][f:f+2] != "##":
print "Im... |
88867f5b67d62feabf85cf160b9f551a86c5e765 | Nisar-1234/Data-structures-and-algorithms-1 | /Heaps (or Priority Queue)/Running Median of an Integer Stream.py | 1,193 | 3.71875 | 4 | # User function Template for python3
global min_heap
min_heap = []
global max_heap
max_heap = []
class Solution:
def balanceHeaps(self):
if len(max_heap) > len(min_heap) + 1:
topElement = heapq.heappop(max_heap)
heapq.heappush(min_heap, -1 * topElement)
elif l... |
afa6d83c8fb677699211a0929bf5eaa8926c4afd | rubychen0611/LeetCode | /Problemset/word-pattern/word-pattern.py | 701 | 3.765625 | 4 |
# @Title: 单词规律 (Word Pattern)
# @Author: rubychen0611
# @Date: 2021-01-23 15:15:11
# @Runtime: 36 ms
# @Memory: 14.9 MB
class Solution:
def wordPattern(self, pattern: str, s: str) -> bool:
map1 = {}
map2 = {}
strs = s.split()
if len(pattern) != len(strs):
return False
... |
dc20c32cc670dba4af8170d57706ed3ad892f4dc | fwparkercode/ProgrammingPygame | /Problem Sets/ps_04.py | 3,521 | 4.40625 | 4 | '''
Chapter 04 Problem Set (21pts)")
Instructions: For each of the following, enter your answer below the numbered problem.
Ensure the code runs properly without errors. Make sure your file executes before you submit it!
If a single problem is not working properly, please comment it out of your code. If a question... |
63fcb32b1526fab64e6f405bed4356e724fe6f0d | aniketverma-7/CO_OS_LAB | /ROUND_ROBIN_ZERO_AT.py | 1,998 | 3.84375 | 4 | '''
Author : ANIKET VERMA
Enroll : 0827CO191012
FCFS with zero arrivial timw
takeInput() -> takes input form user
waiting() -> calculate total waiting time
turntime -> calculate turn around time
printData() -> print all process with waiting and turn around time in tabular form.
makecopy() -> make copy of list
... |
8404a23099a3bafc86f4f307cc3d01454e311757 | smohapatra1/scripting | /python/practice/start_again/2021/01252021/power_of_nums.py | 368 | 4.53125 | 5 | #Python Program to find Power of a Number
#Write a Python Program to find Power of a Number For Loop, While Loop, and pow function with an example.
from math import pow
def main():
a = int(input("Enter a number: "))
b = int(input("Enter the exonent value: "))
print ("{}' exponent of {} is : {}".format(b,a, ... |
03aa65c6c68842156f69587884694b48fc9c23d0 | AMY-ABOUGHAZY/udacity-bertelsmann-data-science-challenge-scholarship-2018 | /control_flow_lesson_25/while_loops.py | 1,459 | 4.4375 | 4 | # while Loops
# 1.Practice: Water Falls
# Print string vertical.
print_str = "Water falls"
# initialize a counting variable "i" to 0
i = 0
# write your while header line, comparing "i" to the length of the string
while i < len(print_str):
#print out the current character from the string
print(print_str[i])... |
748576177972b466ca45f6ce4b3ae97b245b78cb | martin-chobanyan/rl-playground | /scripts/maze_solver/main.py | 866 | 4.1875 | 4 | """A demo example for both the Dijkstra and Value Iteration solutions to a random maze"""
import matplotlib.pyplot as plt
from dijkstra import dijkstra_solution
from generate_maze import MazeGenerator
from maze_utils import plot_maze
from value_iter import MazeEnvironment, value_iteration_solution
if __name__ == '__... |
6477c735889aff7d2370ab8d4d6074b91c4be172 | Threesome2/pythonstudy | /Liaoxuefengbiji/D8.13/code12.py | 741 | 3.6875 | 4 | #code12.py
def trim(strs):
if strs=='':
return strs
i=0
while strs[i] == ' ':
if i == len(strs)-1:
return ''
i+=1
j=-1
while strs[j] == ' ':
j-=1
# print(i ,j)
str_trim=strs[i:len(strs)+j+1]
print(str_trim)
return str_trim
# strs=trim('... |
51b3b1f6b5e9fca80ee2acc0bb46d8ab92e89aeb | maicon-silva/vccode | /Lista de exercicios 1/Exercício 12.py | 592 | 4.15625 | 4 | # Crie um algoritmo que calcule a área de uma esfera, sendo que o comprimento do raio é informado pelo usuário.
# A área da esfera é calculada multiplicando-se 4 vezes pi e o raio ao quadrado.
# Mostra as informações necessáras a tarefa
print("Para efetuarmos o cálculo da área da esfera, precisamos saber o valor do ra... |
6b754d76bd200c2cdc55d7680dff90da33620545 | Arvindpawar0345/Rolling-dices-for-beginners | /Simple Code.py | 1,055 | 3.625 | 4 | import random
print('Welcome to Rolling Dies')
x="y"
while x=="y":
number = random.randint(1,6)
if number==1:
print('--------')
print('| |')
print('| 0 |')
print('| |')
print('--------')
if number==2:
print('--------')
print('| 0 ... |
2193e0c65a2795e490e4a8e7efd304f32162a52b | VaishnaviReddyGuddeti/Python_programs | /Python_Keywords/from.py | 190 | 3.640625 | 4 | # To import specific parts of a module
# Import only the time section from the datetime module, and print the time as if it was 15:00:
from datetime import time
x = time(hour=15)
print(x)
|
a6f61271c69408ce7a7a1360cdd0884a446fa52f | fdomuma/Password-tips | /interface.py | 1,627 | 3.625 | 4 |
from tkinter import *
import pandas as pd
root = Tk()
root.title("Password manager")
# Search feature
searchBox = Entry(root, width=50, borderwidth=5)
searchBox.insert(0, "Look for place!")
searchBox.grid(row=0, column=1, columnspan=2)
def searchPlace():
db = pd.read_csv("pass_db.csv", sep=";")
keys = searc... |
aabbb469f273f95d97f6fa28a768bc6dc9ccfb64 | xiaoxue11/machine_learning | /ex2/plotDecisionBoundary.py | 1,139 | 3.5625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Thu Nov 15 22:34:07 2018
@author: 29132
"""
from plotData import plotData
import numpy as np
import matplotlib.pyplot as plt
from mapf import mapFeature
def plotDecisionBoundary(theta,X,y):
plotData(X[:,1:3], y)
if X.shape[1] <= 3:
# Only need 2 points to def... |
12711bb519946f76b9b25258edac051ad3b4e321 | dantefung/Python-Codebase | /study_sample/test_scope.py | 1,406 | 3.84375 | 4 | r'''
作用域
在一个模块中,我们可能会定义很多函数和变量,但有的函数和变量我们希望给别人使用,
有的函数和变量我们希望仅仅在模块内部使用。在Python中,是通过_前缀来实现的。
正常的函数和变量名是公开的(public),可以被直接引用,比如:abc,x123,PI等;
类似__xxx__这样的变量是特殊变量,可以被直接引用,但是有特殊用途,
比如上面的__author__,__name__就是特殊变量,hello模块定义的文档注释也可以用特殊变量__doc__访问,
我们自己的变量一般不要用这种变量名;
类似_xxx和__xxx这样的函数或变量就是非公开的(private),不应该被直接引用,比如_abc,__a... |
10d86c8edcdf85ee0a9f0c4b2c6f78f76eb5fb62 | chris7seven/DU-Projects | /COMP-3006/Project 3/project3.py | 4,990 | 4.4375 | 4 | #Christopher Seven
#Project 3
import random
#The card game that will be implemented is blackjack. The player will be playing against a dealer, and will be able to decide to hit or stay
#Since the game is blackjack, the suits of each card will not be kept track of, as they will not be used
#A deal function is... |
965112f18693815fb9e59fd1040609e58d880d5f | sharda2001/Saral_AmaR | /day_1_task2_1.py | 428 | 4.09375 | 4 | year=int(input('enter the year '))
if year%4==0:
print("leap year")
if year%100==0:
print('century year')
if year%400==0:
print('century leap year')
else:
print('leap year')
# year=int(input("enter your year"))
# if year %4==0:
# if year%100==0:
# if year%400==0:
# print("sentury leap year")
# else:
# ... |
f8da4fd2c23d05b67f6f1c8e0f239e7b5e507487 | qmnguyenw/python_py4e | /geeksforgeeks/python/python_all/46_4.py | 2,514 | 4.53125 | 5 | Compute the inner product of vectors for 1-D arrays using NumPy in Python
Python has a popular package called NumPy which used to perform complex
calculations on 1-D and multi-dimensional arrays. To find the inner product of
two arrays, we can use the inner() function of the NumPy package.
> **Syntax:** nu... |
419e747f62e8c7acd8066c147be6f82f7e52585b | santhoshpemmaka/epamDS1 | /middle.py | 660 | 4.125 | 4 | # your task is to complete this function
# function should return index to the any valid peak element
# finding middle element in a linked list
def findMid(head):
# Code here
# firstly check the head is Nonereturn 0
if head == None:
return 0
# In case first and second assign to the head of the ... |
4c701cf7215e3e1d46950b6dad953b6d03639b08 | ArshanKhanifar/eopi_solutions | /tests/manual_tests/mtest_find_anagrams.py | 3,858 | 3.78125 | 4 | import collections
def find_anagrams(dictionary):
sorted_string_to_anagrams = collections.defaultdict(list)
for s in dictionary:
sorted_string_to_anagrams[''.join(sorted(s))].append(s) # join had to be used since sort returns list
return [group for group in sorted_string_to_anagrams.values() if l... |
54371fc70e5788498233030aac1467ca9ff7ef99 | kanxul/masterarbeit | /oops_basics_02.py | 741 | 3.859375 | 4 | # OOP in Pyhton
class My_Calc:
# Class Attributes/Variables
# Class Constructor/Initializer (Method with a special name)
def __init__(self, num1, num2):
# Object Attributes/Variables
self.num1 = num1
self.num2 = num2
# Methods
def total(self):
... |
1536fbd4c9f567227c01e219dac5e21b0931e5a6 | pratikoct15/PhythonDivideby3and5 | /main.py | 603 | 4.0625 | 4 |
def divideCheck(x):
if x % 3 == 0 and x % 5 == 0:
print('divisble by both 3 and 5')
elif x % 3 == 0:
print('divisble by 3')
elif x % 5 == 0:
print('divisble by 5')
else:
print('Number not divisble by 3 or 5')
def loopNum(x):
if ',' in x:
print('list')
... |
f7852bb7c98b76da9c85ae5b098a0ad1aa6b69c3 | Armando1234/python | /test.py | 498 | 3.53125 | 4 | from sys import getsizeof
# Generators provide data one item at a time
# This is a comment
#naive function - technical name
def stupidfunction():
pies = []
for _ in range(10000000):
pies.append("3.141592")
return pies
#lazy function - technical name
def smartfunction():
for _ in range(... |
65621a135fa3303b43776e9037e8bf5890cd9997 | GTxx/leetcode | /algorithms/096. Unique Binary Search Trees/main.py | 518 | 3.6875 | 4 | class Solution(object):
def numTrees(self, n):
"""
:type n: int
:rtype: int
"""
if n <= 1:
return 1
elif n == 2:
return 2
else:
res = [1,1,2]
for i in range(3, n+1):
total = 0
for ... |
7e329011debe7762aab71ef7684eeff83f0e7c2a | hechenkuan/code | /variables.py | 222 | 3.609375 | 4 | """ 变量
"""
# 整数
a = 1
print(a)
print(type(a))
# 浮点数
a = 1/3
print(a)
print(type(a))
a = a*3-1
print(a)
# 布尔值
a = True
print(a)
print(type(a))
# 字符串
a = '乐德学堂'
print(a)
print(type(a))
|
c4f4557cbb397639f7274b97fa3835435aea5fbf | harperpack/Harper-s-Practice-Repository | /media.py | 618 | 3.78125 | 4 | # This file contains code for the class Movie, which holds
# information about different movies. Class Movie shows
# key details about movies to a user.
import webbrowser
class Movie():
"""Class Movie holds information about different movies"""
def __init__(self, movie_title, movie_plot, movie_poster,... |
a1e289edfb9ddf639c97ab945b631edf99212f6f | sammersheikh/python | /numeric.py | 388 | 3.828125 | 4 | num = 1
num += 1 #equivalent to num = num + 1
print(abs(-3)) #absolute value (get positive number)
print(round(3.75, 1)) #round to nearest digit, second number means round to the first digit after the decimal
num_1 = '100'
num_2 = '200' #these are strings, not integers
num_1 = int(num_1) #prefacing with int() cas... |
4174fe9fb169f1d87f7dd71ca4f255a9adc21c20 | rafatmunshi/Data-Structures-Algorithms-using-Python | /BinaryTree.py | 2,909 | 3.8125 | 4 | class Node:
def __init__(self, key):
self.left = None
self.right = None
self.key = key
def preordertraversal(self):
print(self.key, end=' ')
if self.left:
self.left.preordertraversal()
if self.right:
self.right.preordertraversal... |
3030f393d868573217e8e85a09b413a38f0708ed | AndreasLH/3-ugers-projekt-Ham-n-spam | /clean_data_enron.py | 3,181 | 3.578125 | 4 | # -*- coding: utf-8 -*-
""" This code is meant to be used to clean a csv-dataset and make the
necessary normalization (punctuation, removing, stopwords etc.).
Finally it will export the clean dataset as a csv-file.
Link to dataset:
https://www.kaggle.com/karthickveerakumar/spam-filter/version/1
"""
# Import ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.