blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
30765bdaaefcb7f69840ebcce56057d7b37e803d | sinystr/hackbulgaria | /week01/task_12_count_vowels.py | 316 | 3.90625 | 4 | # universal function for finding the summ of apearances
# of members of array of characters in a string
def count_characters(str, characters):
sum_vowels = 0
for i in characters + characters.upper():
sum_vowels += str.count(i)
return sum_vowels
def count_vowels(str):
return count_characters(str, "aeioyu")
|
bbfd4aabaa3ca6697aeca1f38e8352edd0a688eb | sinystr/hackbulgaria | /week02/is_prime.py | 464 | 3.828125 | 4 | from sum_digits import make_valid
from sum_of_all_devisors import sum_of_all_devisors
def is_prime(number):
number = make_valid(number)
if(number == 1):
return False
# If it's a prime number (has 2 devidors - 1 and the number)
# we return true
elif(sum_of_all_devisors(number) == number + 1... |
39071f1bebd011d86d65310e64d3f7f238ecdcf6 | sinystr/hackbulgaria | /week02/task_1_count_words.py | 230 | 3.78125 | 4 | def count_words(arr):
unique_arr = []
words_dict = {}
for i in arr:
if i not in unique_arr:
unique_arr.append(i)
for i in unique_arr:
words_dict[i] = arr.count(i)
return words_dict
|
80d92151a93d699cabdb1c9dea6db7e50d781b22 | sinystr/hackbulgaria | /week01/task_23_nanexpand.py | 287 | 4.1875 | 4 | def nan_expand(n):
nan_string = ""
#if n == 0, we return the empty string
if(n == 0):
return nan_string
# for adding "Not a " n times
for i in range(0,n):
nan_string += "Not a "
# and we close with just NaN, so the string make sense
nan_string += "NaN"
return nan_string
|
2cc62a227bbf04f9f38b3a1b1724e336083dba7c | PimvR/afvinkopdrachten | /afvink2/afvink2.4.py | 491 | 3.59375 | 4 | item1 = float(input('prijs van item 1'))
item2 = float(input('prijs van item 2'))
item3 = float(input('prijs van item 3'))
item4 = float(input('prijs van item 4'))
item5 = float(input('prijs van item 5'))
subtotaal = item1 + item2 + item3 + item4 + item5
print('de producten zonder belasting kosten',subtotaal, 'euro')
... |
1145774779737dcb7425a70e1f45ac55d9852ba6 | BrandonHills/cs181-s18-practicals | /P2/classification_starter.py | 22,532 | 3.71875 | 4 | ## This file provides starter code for extracting features from the xml files and
## for doing some learning.
##
## The basic set-up:
## ----------------
## main() will run code to extract features, learn, and make predictions.
##
## extract_feats() is called by main(), and it will iterate through the
## train/test ... |
ed59bd79f27010d280152a9537241c00ffea7e26 | sumon3255/Python-Tutorials-1 | /tuts16/25 fILE IO BASICS.py | 622 | 3.65625 | 4 | #Ram is a volatile
#volatile is when you shut down Your Computer ALl Data will be vanished
#Hardisk is non volatile
#non volatile is data will save in Your computer memory.you put all these things it will be save forever
#File Io Basics
"""
"r"- Open file for reading-default
"w"- Open file for Writing
... |
0b4832b7b339c95ef69da795060a8d4b582fcf60 | sumon3255/Python-Tutorials-1 | /tuts15/ex.py | 537 | 4.1875 | 4 |
# This program is developed by Ravikant Asoliya
num1 = float(input("Enter first number : "))
operation = input("Enter operator : ")
num2 = float(input("Enter second number : "))
if operation=="*":
if num1==45 and num2==3:
print("555")
else:
print(num1*num2)
elif operation=="+":
... |
2dc7c09006eb5e1f0a720b3dcb0b53737d05a42f | ErikaYazminDionisio/Graficaci-n-de-figuras-con-n-lados | /Ejercicio BREyDDA.py | 1,243 | 4.0625 | 4 | from matplotlib import pyplot as plt
import turtle as vic
import matplotlib.pylab as pl
def poligono():
lados = int(input("Ingrese la medida de la circunferencia, \n ejemplo--> 100: "))
n = int(input("Ingrese el número de lados de la figura: \n"))
for i in range(n):
vic.forward(lados)
... |
493264b09370d0a3b70d1a5f2507b64109e95be5 | PLBMR/pythonNetworksGUI | /Source_And_Supports/For_Running_Term_Project/structClass.py | 2,045 | 3.859375 | 4 | ######################################################
# Structs (save in structClass.py (do not save in struct.py!))
######################################################
# Here we use 'struct' in the classic sense:
# http://en.wikipedia.org/wiki/Struct_%28C_programming_language%29
# Note that this is not the sam... |
211385c7cfdbca9a8e2b5dc48b25c0b7da40ee05 | ericchen12377/CS61A_LearningDoc | /06-Iteration/lab02/lab02/lab02.py | 1,949 | 4.34375 | 4 | """Lab 2: Lambda Expressions and Higher Order Functions"""
# Lambda Functions
def lambda_curry2(func):
"""
Returns a Curried version of a two-argument function FUNC.
>>> from operator import add, mul, mod
>>> curried_add = lambda_curry2(add)
>>> add_three = curried_add(3)
>>> add_three(5)
... |
61512495901202d28b1b1088f50c25cff727f827 | ericchen12377/CS61A_LearningDoc | /14-Mutable Values/14.py | 1,848 | 3.703125 | 4 | def date_demos():
from datetime import date
today = date(2020, 2, 24)
freedom = date(2020, 5, 12)
str(freedom - today)
today.year
today.strftime('%A, %B %d')
type(today)
def string_demos():
"Hello".lower()
"Hello".upper()
"Hello".swapcase()
hex(ord('A'))
print('\a')
... |
4942dcaef60e714ab1bef85bad6150f4ef077b6c | SebZalewskiK/Python_ejercicios | /Poo/clases_abstractas_SOLID_DIP/furnace_DIP_example.py | 3,156 | 3.515625 | 4 |
# ejemplo Principio de Inversion de Dependencias de SOLID
# libro Agile Principles, Patterns and Practices in C#
# ejemplo furnace pag. 209
from abc import ABCMeta, abstractmethod
# clases abstractas (metaclases) que componen el sistema de calefaccion
class Calefaccion(metaclass = ABCMeta):
def __init__(self):
... |
b7b18741bd56b0f87f3b40ae37f00a526a4f0a4b | SebZalewskiK/Python_ejercicios | /dirigida-por-eventos-GUI/chapter_7/ejemplo_7-23.py | 1,710 | 3.890625 | 4 | # Extending Class Components
# extendemos la clase Hello y redefinimos su comportamiento
# ver clase Hello en gui6.py o ejemplo 7-20
from tkinter import *
from gui6 import Hello
class HelloExtender(Hello):
# no es necesario pack() porque se ejecuta en el constructor (iniciador) de la superclase
def make_widgets... |
23784220592c90aa7d9c911d2fa0897bbb650e99 | SebZalewskiK/Python_ejercicios | /dirigida-por-eventos-GUI/chapter_8/ejemplo_8-5.py | 4,303 | 3.703125 | 4 |
"""
pop up three new windows, with style
destroy() kills one window, quit() kills all windows and app (ends mainloop);
top-level windows have title, icon, iconify/deiconify and protocol for wm events;
there always is an application root window, whether by default or created as an
explicit Tk() object; all top-level wi... |
80be94c0c3ace64ca419129673fd77280b8fb35a | SebZalewskiK/Python_ejercicios | /dirigida-por-eventos-GUI/chapter_8/ejemplo_8-16.py | 567 | 3.9375 | 4 |
# Message
'''
The Message widget is simply a place to display text. Although the standard showinfo
dialog we met earlier is perhaps a better way to display pop-up messages, Message splits
up long strings automatically and flexibly and can be embedded inside container widg-
ets any time you need to add some read-only ... |
127a8b7443690c83d27e6671fa832e37824a988e | SebZalewskiK/Python_ejercicios | /Procedimental/Unidad_3_ Listas_y_ operaciones_sobre_listas/codigo/unirListas.py | 290 | 3.984375 | 4 | # encoding: UTF-8
def unirListas(listaP, listaQ):
for elemento in listaQ:
if elemento not in listaP:
listaP.append(elemento)
# else:
# el elemento ya existe en la listaP y no lo añadimos
return
listaA = [1, 2, 3]
listaB = [3, 4, 5]
unirListas(listaA, listaB)
print listaA |
af00b5fe7f5efd8fc6606701dba5de957ed2f479 | SebZalewskiK/Python_ejercicios | /Procedimental/Unidad_3_ Listas_y_ operaciones_sobre_listas/problem_set_3/08-Sudoku_resuelto.py | 4,566 | 4.25 | 4 | # encoding: utf-8
# THREE GOLD STARS
# Sudoku [http://en.wikipedia.org/wiki/Sudoku]
# is a logic puzzle where a game
# is defined by a partially filled
# 9 x 9 square of digits where each square
# contains one of the digits 1,2,3,4,5,6,7,8,9.
# For this question we will generalize
# and simplify the game.
# Define a... |
08d272ad37ffa3295608ca0549a921b65f688e8c | SebZalewskiK/Python_ejercicios | /dirigida-por-eventos-GUI/chapter_8/ejemplo_8-11.py | 1,416 | 4.5 | 4 |
# Letting users select colors on the fly
from tkinter import *
from tkinter.colorchooser import askcolor
def setBgColor():
(triple, hexstr) = askcolor()
if hexstr:
push.config(bg=hexstr) #LEGB scope rule
print(triple, hexstr)
root = Tk()
push = Button(root, text='Set Background Color', command=setB... |
247d938f25c1367d28ba2e73c709d28f143d8a02 | SebZalewskiK/Python_ejercicios | /Procedimental/Unidad_2_procedimientos_e_instrucciones_de_control/codigo_regla_LEGB.py | 2,360 | 4.59375 | 5 | # Extractos de codigo del libro Learning Python 5th Ed. by Mark Lutz
# Chapter 17: Scopes
# GLOBAL SCOPE
# Global names are variables assigned at the top level of the enclosing module file.
# Global names must be declared only if they are assigned within a function.
# Global names may be referenced within a function... |
6ec0eebd4798e6bf90bbd34c2af5323cdfa3f8dc | Terry5066/pythonlearning | /inheritance2.py | 738 | 3.875 | 4 | class person:
def __init__(self,fname,lname):
self.firstname=fname
self.lastname=lname
def printname(self):
print(self.firstname,self.lastname)
x=person("terence","mpofu")
x.printname()
class student(person):
pass
class student(person):
def __init__(self,fname,lname):
... |
f49f475fe8097d25063fc8534c085bfd45a718c3 | AlexLZM/Medium-Problems | /permutationUnique.py | 724 | 3.84375 | 4 | # Given a collection of numbers, nums, that might contain duplicates, return all possible unique permutations in any order.
def permutationUnique(nums):
q = collections.deque([[]])
nums.sort() # sort an break will handle the duplicates
for num in nums:
for j in range(len(q)):
old = q.po... |
392aac8cc61099dbda51fbca9ced8786f845b27f | AlexLZM/Medium-Problems | /mergeSort.py | 777 | 4.125 | 4 |
def mergeSort(arr):
'''
return a sorted array
'''
# base case
if len(arr) == 1:
return arr
mid = len(arr)//2
# divide the array into 2 sub arrays and sort them separately
L = mergeSort(arr[:mid])
R = mergeSort(arr[mid:])
i = j = 0
temp = []
# mer... |
e9ec4ae2bac51f5c2534c83b80ffd84e1fd8bb1a | miclis/SpaceFox | /SpaceFox/SpaceFox.py | 31,729 | 3.625 | 4 | """
This program is a space shooter game created using pygame library in Python3.
Player flies a spacship and tries to avoid getting hit by rocks. He can use
laser gun to smash enemies or simply outmaneuver them.
Ship's shields can last several hits, but the bigger the stone is the more
shield hit point player loses.
M... |
f14a9646efaa834bd6f627818e36b8deacae716f | anantprakash17/leetcodeSolutions | /NonDeacreasingArray.py | 1,131 | 3.84375 | 4 | class Solution:
def checkPossibility(self, nums: List[int]) -> bool:
#Loop through the list looking for number that breaks the order
for i in range(len(nums)-2):
if nums[i] > nums[i + 1]:
#It is possible that the order can be fixed by changing the number at
... |
d7c1c79c6e926086db2f4b873092595dc2de4cc9 | ludivine-o/module_python_algo | /diamond.py | 541 | 3.8125 | 4 | ch_let = ord(input("choisir une lettre : "))
lettre = ord('a')
ligne_debut = ((ch_let-97)*'.' + str(chr(lettre)) + (ch_let-97)*'.')
# 1ere ligne
print(ligne_debut)
pc = ch_let-1-97
pm = 1
lettre += 1
# lignes debut
while lettre != ch_let:
print(pc*"." + str(chr(lettre)) + pm*"." + str(chr(lettre)) + pc*".")
pc ... |
2f11829e885678356d40beebaf21a516239b5a48 | Raghu-N-Yadav/python_codes | /canYouCount-hackerEarth.py | 808 | 4.125 | 4 | '''
You are given a string s consisting of lowercase English letters and/or '_' (underscore).
You have to replace all underscores (if any) with vowels present in the string.
The rule you follow is:
Each underscore can be replaced with any one of the vowel(s) that came before it.
You have to tell the total number of d... |
fbcf56badbd5eaf34c9ef939df4b475548009356 | Raghu-N-Yadav/python_codes | /creat_list.py | 457 | 4.34375 | 4 | #creating list
list1 = []
print(list1)
list2 = ['raghu','n','yadav']
print(list2)
#multi dimensional list
list1 =['raghu', 'N',['yadav']]
print(list1)
#adding elements to the list using appened , insert and extend
list3 = []
list3.append(1)
list3.append(2)
print(list3)
#insert uses position to insert any elements
li... |
9ceb0a21cfdbb007f9588ed63e213902493db941 | Raghu-N-Yadav/python_codes | /check_prime.py | 441 | 4.25 | 4 | #checking either a number is prime or not
x = int(input('enter a number'))
rem = int(x / 6)
a = (6 * rem) + 1
print(a)
b = (6 * rem) - 1
print(b)
if x == a or x == b:
print('it is prime')
#break
else:
print('it is not prime')
#break
'''else:
print('not a prime number')
for i in range(2,x+1):
i... |
c1875e7b9d3a95cf665bb970952a56f9d08b46cf | Raghu-N-Yadav/python_codes | /tuple.py | 351 | 4.40625 | 4 | #creating a tupe
tuple1 = ()
print(tuple1)
#tuple of string
print(('raghu', 'n', 'Yadav'))
#tuple of list
print(tuple([1,2,3,4]))
#nested tuple
tuple1 = ('my','name ')
tuple2 = (11,9,1111)
tuple3 = (tuple1, tuple2)
print(tuple3)
#****can not delete or update items from a tuple
#accessing elements from a tuple... |
33c0837cf0ef2e77d61974339fae532408f968dc | Raghu-N-Yadav/python_codes | /digit_sum.py | 253 | 3.859375 | 4 | #adding digits of a number
n = input('enter a number :: ')
lenght = len(n)
mylist = []
for i in n:
mylist.append(i)
sum = 0
for i in range(0,lenght):
x = int(mylist.pop())
sum =sum + x
print('sum of the digits is ::', sum)
#print(mylist)
|
a4a7ae588188657030e36fc1f6e6a8f2e3347226 | Raghu-N-Yadav/python_codes | /devisStairCase.py | 388 | 3.984375 | 4 | #recursive way to climb satirs
def stepPerms(n):
arr = [0]*(n+2)
arr[0] =1
arr[1] =1
arr[2] = 2
for i in range(3,n+1):
arr[i] = arr[i-3]+arr[i-2]+arr[i-1]
return arr[n]
# if (n ==1 or n ==0):
# return 1
# elif(n == 2):
# return 2
# else:
# return stepP... |
8dc197e235ae64588854483c9efc12ea61c15cc6 | mahirmaruf/Complete-Python-3-Bootcamp | /07-Errors and Exception Handling/test_cap.py | 683 | 3.78125 | 4 | import unittest #First need to import the unittest (inbuilt)
import cap # imports the py script that we are testting
class TestCap(unittest.TestCase): #inherit from unittest.TestCase, inheritence of OOP
# Number your tests
def test_one_word(self):
text = 'python'
result = cap.cap_text(text... |
a4a7513554c3dba75c91d5902ef29fa925a01769 | zjthom3/tictactoe | /tictactoev2.py | 6,803 | 3.5 | 4 | # Global startup variables
import random
import board
import gameplay
import dialogs
# Board Functions
newBoard = board.newBoard
printBoard = board.printBoard
boardCoords = board.boardCoords
# Gameplay Functions
setPiece = gameplay.setPiece
resetPiece = gameplay.resetPiece
setComputerPiece = gamepla... |
f17319c170f418ca4852c98115c546969e6ab334 | birdmw/Light_Money | /flask example/go_matt.py | 11,650 | 3.6875 | 4 | # Go Base Game Class
# Author: Matthew Bird
# date: 10/5/2018
from copy import deepcopy
from math import floor
from random import choice
class Game:
def __init__(self, board_size=19, rules=None):
"""
The Game class is for playing go. There is only one method for now, "play".
:param boar... |
2363c0bc5cf22cc7e6d4ee6badf84cd20359520b | LiangTsao/MLServer | /mlserver/batching/shape.py | 911 | 3.578125 | 4 | from functools import reduce
from operator import mul
from typing import List
class Shape:
"""
Helper class to manipulate shapes.
"""
def __init__(self, shape: List[int]):
self._shape = shape.copy()
def to_list(self) -> List[int]:
return self._shape.copy()
def copy(self) -> ... |
f2259f531a3726fd2f8d6a78e92269f4eba6117d | simran-03/Sales_Management | /sales.py | 5,290 | 3.765625 | 4 | import pandas as pd
from datetime import date
import csv
def main():
print("1. User 2. Manager 3. Exit")
c = input("Enter Choice : ")
if c == "1":
user()
elif c == '2':
p = input('Enter Password : ')
if p == '123... |
bd563125bed574fc8a960a059c6666fa838dba81 | ToyVo/PygamePhysics | /Vec2.py | 5,076 | 3.84375 | 4 | import math
from typing import Tuple
class Vec2:
# initialization in two different ways
def __init__(self, x: Tuple[float, float] or float = (0, 0), y: float = None):
if y is None:
try:
if len(x) == 2:
self.x: float = x[0]
self.y: flo... |
7cd395dc2de840674eaf96492cce7f6074586aec | ShailjaSrivastava/30-Days-of-Code-Python | /Day6-Let'sReview.py | 430 | 3.515625 | 4 | # Enter your code here. Read input from STDIN. Print output to STDOUT
T=int(input().strip())
len_S=[]
for i in range(T):
S=input().strip()
len_S.append(S)
for i in len_S:
str1=[]
str2=[]
str =list(i)
for j in range(len(str)):
if j % 2 == 0 :
str1.appe... |
4c9dd5ca4b5fb2f07fda90913eecc89a4ebe0bab | wizardrs18/WzhLeetcode | /LeetcodePy/easy/RearrangeTheArray.py | 262 | 3.515625 | 4 | from typing import List
def shuffle(nums: List[int], n: int):
list1 = nums[:n]
list2 = nums[n:]
list3 = []
for i in range(0, n):
list3.append(list1[i])
list3.append(list2[i])
return list3
class RearrangeTheArray:
pass
|
f57ff247cdd06bf90ff33c01178fd5471c6ba65e | louay-075/CyberBlindTech-python-lessons | /lesson4-comments.py | 258 | 3.625 | 4 | # hello
# this is a variable called name
name = 'louay'
# this is a variable called lastname
lastname = 'eloudi'
"""
this is a multiline comment!
we will print out these two variables
name
lastname
using python
"""
print name
print lastname |
ebf49cc973781244334357520f6b318947331214 | federicopratto/Algoritmos-y-Programacion-1---TP-1 | /2- Programa/funciones_validacion.py | 2,418 | 3.828125 | 4 | #Esta funcion verifica si el pseudonimo ingresado para un nuevo usuario es valido.
def validar_pseudonimo(pseudo, datos_usuarios):
if pseudo in datos_usuarios:
print("\n* ¡El nombre de usuario ingresado ya se encuentra en uso. Por favor seleccione otro! *\n")
return True
else:
prueba = p... |
68136e2cb5fa8431938c303813106dcfe6bd783b | jclin61/pythonEverybody | /chapter8/8.5.py | 870 | 3.859375 | 4 | # fname = raw_input("Enter file name: ")
# if len(fname) < 1 : fname = "mbox-short.txt"
# fh = open(fname)
# count = 0
# for line in fh:
# line = line.strip()
# if line != '':
# words = line.split('\n')
# for word in words:
# word = word.split()
# if word[0]!= 'From' :
# ... |
e6b2b29e3ff16444fd8854b2f09757b65c42baf3 | juneyochen/sc-projects | /stanCode_Projects/boggle_game_solver/largest_digit.py | 1,506 | 4.5 | 4 | """
File: largest_digit.py
Name: June-Yo Chen
----------------------------------
This file recursively prints the biggest digit in
5 different integers, 12345, 281, 6, -111, -9453
If your implementation is correct, you should see
5, 8, 6, 1, 9 on Console.
"""
def main():
print(find_largest_digit(12345)) # 5
pr... |
541e709a2aa9e0a10aafef021dab547b8721aac4 | manofmountain/LeetCode | /409_LongestPalindrome.py | 832 | 3.515625 | 4 | # 22.86%
import collections
class Solution(object):
def longestPalindrome(self, s):
"""
:type s: str
:rtype: int
"""
c = collections.Counter(s)
res, odd = 0, False
for _, num in c.items():
if num % 2 != 0:
odd = True
... |
482ad2023f21c4440bcc4544ddeedc5ccc3957ed | manofmountain/LeetCode | /275_H-Index_II.py | 527 | 3.609375 | 4 | ##96.59%
class Solution(object):
def hIndex(self, citations):
"""
:type citations: List[int]
:rtype: int
"""
if not citations:
return 0
left, size, index = 1, len(citations), 0
right = size
while left <= right:
mid =... |
517e4b682e6b12974385b9c23201af4bebefd1d0 | manofmountain/LeetCode | /513_FindBottomLeftTreeValue.py | 924 | 3.796875 | 4 | # 40.9%
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
#from collections import deque
class Solution(object):
def findBottomLeftValue(self, root):
"""
:type root: Tre... |
5b94fb7b9c42fb9291513076fe9e91fe1777e08b | manofmountain/LeetCode | /328_OddEvenLinkedList.py | 842 | 3.78125 | 4 | # Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
###72.01%
class Solution(object):
def oddEvenList(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
if not head o... |
7622c9e20bd50343beabdf4ec6badf49bba5224e | manofmountain/LeetCode | /384_ShuffleAnArray.py | 659 | 3.515625 | 4 | ##The traditional way
import random
class Solution(object):
def __init__(self, nums):
self.nums = nums
def reset(self):
return self.nums
def shuffle(self):
ans = self.nums[:] # copy list
for i in range(len(ans)-1, 0, -1): # start from en... |
1956a921b83714f43b20617efd70c87624b08dd5 | manofmountain/LeetCode | /020_ValidParentheses.py | 1,177 | 3.796875 | 4 |
#Solution from LeetCode
class Solution:
# @return a boolean
def isValid(self, s):
stack = []
dict = {"]":"[", "}":"{", ")":"("}
for char in s:
if char in dict.values():
stack.append(char)
elif char in dict.keys():
if sta... |
1bc86e9b51c7e83d9fbbbafca2445aac56fd157b | Vanna-M/nirvana | /db_builder.py | 900 | 4 | 4 | import sqlite3 #enable control of an sqlite database
import csv #facilitates CSV I/O
f="discobandit.db"
db = sqlite3.connect(f) #open if f exists, otherwise create
c = db.cursor() #facilitate db ops
#make table the first
q = "CREATE TABLE students (name TEXT, age INTEGER, id INTEGER)"
c.execute(q) #r... |
3b6cc05c24ff129132ba8d9f70513c0836d9262d | lxb1991/neukg | /DataEngine/data.py | 2,637 | 3.890625 | 4 | # coding=utf-8
# --------------------------------------------------------------------
# 用到的数据对象
class Const(object):
"""
const 类. 变量赋值后不可改变
"""
def __setattr__(self, key, value):
if key in self.__dict__:
raise(self.ConstError, 'Const变量 不可赋值')
else:
self.__d... |
4fc00cb108da12e3c29dcaa8ae5f80410e537c8a | CykAlex/python_study | /1.py | 1,045 | 3.625 | 4 | x=16
ans=0
while ans*ans<=x:
ans +=1
print(ans)
##x=10
##ans=0
##if x >= 0:
## while ans*ans < x:
## ans +=1
## #print('ans = ',ans)
## if ans*ans != x:
## print(x,'is not a perfect square')
## else:
## print(ans)
##else:
## print(x,'is a negative number')
##x=10
##i=1
##wh... |
bd3b8b5243af9d92ff06005b30272b434226e69e | scurry222/holbertonschool-higher_level_programming | /0x0A-python-inheritance/3-is_kind_of_class.py | 325 | 3.953125 | 4 | #!/usr/bin/python3
"""
3-is_kind_of_class : 1 function
"""
def is_kind_of_class(obj, a_class):
"""Checks if object is a subclass of class
Args:
obj (obj:`object`): any object
a_class (class): any class
"""
if issubclass(type(obj), a_class):
return True
return F... |
080ecd289b1546d9685141995814429237570cb1 | scurry222/holbertonschool-higher_level_programming | /0x0B-python-input_output/8-load_from_json_file.py | 284 | 3.75 | 4 | #!/usr/bin/python3
import json
"""
8-load_from_json_file : 1 function
"""
def load_from_json_file(filename):
""" Creates an object from a json file
Args:
filename (obj : 'str') name of file
"""
with open(filename) as f:
return json.load(f)
|
1f204c83b3c9e77edf7809c98014b525dc229f9b | DavidZeLiang/algorithm_questions | /quick sort/quick_sort.py | 675 | 3.75 | 4 | def quicksort(lst, l, r):
if l >= r:
return
pivot = lst[(l + r) >> 1]
i = l - 1
j = r + 1
while i < j:
while True:
i += 1
if lst[i] >= pivot:
break
while True:
j -= 1
if lst[j] <= pivot:
break
... |
2be5cee51614e19f45691968602a5717d173e34e | Ravino/python | /Ekaterina/sumlowFiveElemArray.py | 691 | 3.859375 | 4 | import numpy as np;
print ("Генерация массива\n");
arr = np. random. randint (0, 10, 100);
print ("\n\nПечать исходного массива\n");
for i in arr:
print (i);
print ("\n\nПоиск последних пяти элементов массива меньше пяти и расчёт их суммы\n");
#Перевернули массив для удобства работы
#Задали счётчик
#Задали... |
2bbf01ac5477de456b1d10325b648765f5a58094 | StephenRebel/ICS3U-League-of-Invaders-game | /gamefiles/instructionsMenu.py | 2,576 | 3.625 | 4 | #Instructions Menu
def instructions():
import main
from main import pygame, window, big_font, med_font, title_font, back_ground, BLACK, RED, DARK_GR, LIGHT_GR, WHITE, screen, size, menu_select_sound, enemy_img, ball_img
#Handles a quit event
for event in pygame.event.get():
if event.type == pyg... |
648da285e4b8ecde503a25e01b71e9a43614db0d | MBoucher28/PythonCodeS17 | /Mod.py | 2,028 | 3.890625 | 4 | #Module functions for other programs
import random
#get int input from user
def IntInput(s):
print s,
num = int(raw_input())
return num
#get string input from user
def StringInput(i):
print i,
inpt = raw_input()
return inpt
def randomincreasing(n,x,y):
n = n + random.randrange(x, y)
... |
fd71356a81acdcb40ef28bba2a664046670725a0 | conjonorama/Advent-of-Code-2020 | /day_03.py | 1,037 | 3.5625 | 4 | # Part 1
t = []
with open('input_03.txt') as f:
for line in f.readlines():
t.append(line.strip())
# for i in range(len(t)):
# print(len(t[i]))
x = 0
trees = 0
for i in t[1:]:
# print(i)
x += 3
if x >= 31:
x -= 31
if i[x] == '#':
trees += 1
print(trees)
# Part 2
... |
48d610973e90fa6659ffcb5382edbe653e1c1c0f | zayedAlmansoori/Game_test_01 | /peeps/person.py | 319 | 3.609375 | 4 | #! usr/bin/env python3
class Person:
def __init__(self, name):
"""
base person class
:param name:
"""
self.name = name
def __str__(self):
"""
:return: string
"""
assert isinstance(self.name, object)
return f'name: {self.name}'
|
6c3e035f3601469f4930730237c0722d0abbd7fd | DanielTangnes/PythonWebScraper | /main.py | 1,562 | 3.640625 | 4 | """
This code is made to check the price of a product, and send you an email if the price is below a certain value.
im really new to programming and coding, so you probably wanna change some of the code.
"""
import requests
from bs4 import BeautifulSoup
import smtplib
import time
URL = 'enter link'
headers... |
9692863850f2afda8d25cf8150a0c08187c03b18 | biagiom/ml-malware-analysis | /code/naive_bayes_text.py | 22,160 | 3.5 | 4 | """
This file contains an implementation of the Naive Bayes classifier machine learning algoritm and
it has been designed expecially for problems that involves text classification but it can be also
extended to other generic classification problems.
It has been also trained using the SMS Spam Collection... |
66c664c70845b740acbc04f6054bf30201d8c3da | AsemRadhwi/datacamp_python | /np_and_pd.py | 3,867 | 3.609375 | 4 | # Import pandas
import pandas as pd
import numpy as np
# Use pandas to read in recent_grads_url
recent_grads_url = 'https://s3.amazonaws.com/assets.datacamp.com/production/course_6060/datasets/recent_grads.csv'
recent_grads = pd.read_csv(recent_grads_url)
# Print the shape
print(recent_grads.shape)
# Print .dtypes
... |
b1a15db9843242b0f14fd24646fee5845bb25572 | Bar-Eli/Sigit | /Ex7.py | 1,002 | 4.34375 | 4 | """
Exercise 7:
decorate a function, saving its result saving time for future use.
"""
import time # used to simulate a complicated function (takes long time to run).
def decorate(func):
"""
Provide cache decorator for functions,
:param func: Function to decorate.
:return: The function decorat... |
46d84bc3db21ed03db57032b19409eee7c38a1d9 | rajasekaran36/GE8151-Problem-Solving-and-Python-Programming | /Lab/Ex 9 Matrix Multiplication/E9-Code.py | 333 | 3.5625 | 4 | mat_a = [[2,3,4],
[4,5,6],
[2,3,7]]
mat_b = [[4,5,6],
[6,7,8],
[2,3,4]]
res_m = [[0,0,0],
[0,0,0],
[0,0,0]]
for i in range(3):
for j in range(3):
for k in range(3):
res_m[i][j] = res_m[i][j] + (mat_a[i][k] * mat_b[k][j])
for row in res_m:
... |
86aec21657ec3fe2f6eb64379c9bdba080fc53f6 | rajasekaran36/GE8151-Problem-Solving-and-Python-Programming | /Examples/comp_list.py | 186 | 3.78125 | 4 | l = [fact**2 for fact in range(10) if (fact%2 == 0)]
print(l)
l = ["{}--{}".format(ele,"True") for ele in range(10) if (ele%2 == 0)]
print(l)
l = [ele**3 for ele in range(10)]
print(l) |
f397e8aa55b589371231a63e74e0208352b5a3e8 | rajasekaran36/GE8151-Problem-Solving-and-Python-Programming | /Lab/Ex 4 Finding Maximum in the list/E4-Code.py | 235 | 4 | 4 | alist = []
print ("enter any 5 numbers")
for i in range(5):
data = int(input())
alist.append(data)
max = alist[0]
for element in alist:
if (element > max):
max = element
print("Maximum in the list" ,alist,"is:",max) |
86c6f3707231d47354dfcbf6f7ff9e61c2d246f9 | rajasekaran36/GE8151-Problem-Solving-and-Python-Programming | /Examples/4_2_fibbi_rec.py | 126 | 3.609375 | 4 | def fibi(n):
if(n<=1):
return n
else:
return fibi(n-1)+fibi(n-2)
for i in range(5):
print(fibi(i)) |
932f374016d3a46345e786cb475d9d897a11a1d9 | rajasekaran36/GE8151-Problem-Solving-and-Python-Programming | /Examples/counting_variables.py | 235 | 3.59375 | 4 | name = "Rajasekaran"
d = {}
for char in name:
if (char in d):
d[char]+=1
else:
d[char]=1
uni_string = ""
for key in d:
if(d[key]==1):
uni_string = uni_string + key
print(uni_string)
d2 = {} |
7f35e523e249f1609a41f915cc64aac1373b7a2f | DynamicaLab/Dynamicalab | /dynamicalab/drawing/plots.py | 2,483 | 3.75 | 4 |
import numpy as np
def plot_spectrum(ax, matrix_generator,
n_networks=20,
nbins=100,
vals=[],
axvline_color="#ef8a62",
bar_color="#67a9cf",
normed=True,
xlabel=r"$\lambda$",
ylabel=r"$\rho(\lambda)$",
label_fontsize=13):
"""Plot an histogram of the density spectrum of a family of matri... |
b5f39be50c957cccfbca2e9611fa004ec099806c | BenWilop/PrisonersDilemmaTournament | /code/BenWilop/unanim045.py | 3,657 | 3.5 | 4 | import numpy as np
'''
We use a derivation of the TitForTat-Strategy to force the enemy into cooperating if he wants to maximize his overall
score. Moreover forgiving elements can be found in addition to counter measurements against detective and random strategies
We start with the state "detective_phase" that... |
955fe6216b6c8ce0350595af5c65b476d8bd5c1e | BenWilop/PrisonersDilemmaTournament | /code/ThatXliner/BEAT_HIM.py | 6,086 | 3.53125 | 4 | import random
import enum
class WhatHappened(enum.Enum):
just_told_on_him = "because they are nice and i need advantage"
nothing = None
told_on_him_again = "hope they won't care"
stay_silent_pls = "because they are angry"
stay_lie_pls = "ALWAYS"
def strategy(history, memory):
US = history[0]... |
f7b06a9c2366f3a81fd6534fa130894e970f117e | paralleldynamic/challenges | /codevent/2015/02/wrapping_paper_calculator.py | 604 | 3.75 | 4 | from functools import reduce
from operator import mul
def ribbon(l, w, h):
area = l * w * h
x, y = sorted((l, w, h))[:2]
return area + 2 * x + 2 * y
if __name__ == "__main__":
with open("input.txt", "r") as input:
present_dimensions = [tuple(int(d) for d in row.strip().split("x")) for row in... |
ea3f22f08c2db1b496c191be1c1b61f454a206bc | d-air1/TDD-Assignment | /calc/main.py | 8,923 | 3.625 | 4 | #!/usr/bin/env python
from flask import Flask
from flask import request, url_for
app = Flask(__name__)
def bmi_calc(height_ft, height_in, weight):
# validate input
try:
height_ft = int(height_ft)
except ValueError:
return "Invalid input for feet. Can't be over 8 feet tall or under 1 foo... |
09e5c7438e8eb96dca7c91763ac1ef8e14876e2f | d-air1/TDD-Assignment | /unit_tests/bmi/test_print_result.py | 796 | 3.71875 | 4 | import unittest
from print_result import print_result
class testPrintResult(unittest.TestCase):
#didn't need as many test with the print function
def test_with_string(self):
feed = "Something"
with self.assertRaises(TypeError) as exception_context:
print_result(feed)
se... |
46a8d894c96d4b305da0b3ae0bafd3307f4b702d | d-air1/TDD-Assignment | /unit_tests/retirement/test_print_result_2.py | 794 | 4.03125 | 4 | import unittest
from print_result2 import print_result2
class testPrintResult2(unittest.TestCase):
#testing results when age is 100 since this should be invalid the result is 30 but irrelevant
def test_with_age_100(self):
actual = print_result2(100, 30)
expected = "You'll be dead before you rea... |
8610eabab8a32217ec8bc228be8e58acbf41af64 | paigekm/Fruit-Bowl | /validations.py | 1,807 | 4.21875 | 4 | """Two validated versions of the get integer and get string functions."""
def get_validated_integer(message, min, max):
"""Get user input.
And tests that the length of the integer
is greater than our min and less than our maximum.
loops until an acceptable input is received
:param M: str
:pa... |
94cf8fc9603f4fd229a1946c8015cdcb571b27a9 | Funtaztic/Maximum-Complexity.py | /Maximum_Complexity.py | 2,946 | 3.8125 | 4 | print ('hello world')
# This will be the most complex program I have written so far.
# It will have:
# variables
# strings
# string manipulations
# .lower() .upper() .title() .capitalize()?
# methods
# booleans
# if-else statemens
# parameters
# comparison operators
# '<' '>' '>=' '<=' '==' '!='
#This will ... |
9169b2e8e7cf5c3f84b33e2ba6cfcb26f123abfd | KenshinTang/learn-python3 | /src/syntax/fun1.py | 569 | 4.03125 | 4 | #!/usr/bin/python
# -*- coding: utf-8 -*-
# 这是一个尾递归
# 尾递归是指,在函数返回的时候,调用自身本身,并且,return语句不能包含表达式。
# 这样,编译器或者解释器就可以把尾递归做优化,使递归本身无论调用多少次,
# 都只占用一个栈帧,不会出现栈溢出的情况。
# 但是python没有优化,所以还是会溢出
def x(n):
return x1(n, 1)
def x1(num, product):
if num == 1:
return product
return x1(num-1, num*product)
i = inpu... |
0a882483129fb6bc5b51d991e418f3eb041d703b | IdeaventionsAcademy7/chapter-1-part-1-beginnings-MiaKPup | /ch1_09.py | 438 | 4.28125 | 4 | # Name
# Problem #9
# Chapter 1 Problem Set Part 1
from time import sleep
num = int(input("Enter a number:"))
print("We are now adding 2 to your number.")
sleep(3)
num += 2
print("We are now multiplying your number by 3.")
sleep(3)
num *= 3
print("We are now subtracting 6 from your number.")
sleep(3)
num -= 6
print("W... |
03224cd587f94d3d2d176f7868bf8e7d804d2773 | LeonGustavo/exercicios_curso_em_video | /desafio81.py | 429 | 3.890625 | 4 | lista = []
cont = 0
while True:
n = int(input('Digite um número para incluir na lista '))
lista.append(n)
cont += 1
r = str(input('Quer continuar? [S/N]'))
if r in 'Nn':
break
print(f'Foram digitados {cont} números')
lista.sort(reverse=True)
print(f'A lista em forma decrescente é {lista}')
... |
9342bc00b41727e9250fdddf6589be921be90c9e | LeonGustavo/exercicios_curso_em_video | /desafio96.py | 166 | 3.609375 | 4 |
def area(a,b):
c = a*b
print(f'A área de um terreno {a}x{b} é de {c}m²')
a = float(input('LARGURA (M) '))
b = float(input('comprimento (M)'))
area(a,b)
|
6d8ddb852d20b98d236c13be4852dc83716595a6 | LeonGustavo/exercicios_curso_em_video | /desafio79.py | 312 | 3.96875 | 4 | lista = []
while True:
n = int(input('Digite um número para a lista '))
if n not in lista:
lista.append(n)
r= str(input('Quer continuar? [S/N]'))
if r in 'Nn':
break
print(F'Os valores digitados são {lista}')
lista.sort()
print(F'E os valores em ordem crescente são {lista}')
|
c130a4f62f322dbf80310674aa826bd41c49b084 | LeonGustavo/exercicios_curso_em_video | /desafio11.py | 230 | 3.875 | 4 | largura = float(input('Informe uma largura'))
altura = float(input('Informe uma altura'))
area = largura*altura
tinta = area/2
print(F'Você tem uma área de {area}m² e para pintá-la será necessário {tinta} Litros de tinta')
|
90a42981692d6f7ec68b398858427752d112f0d1 | LeonGustavo/exercicios_curso_em_video | /desafio50.py | 210 | 3.578125 | 4 | soma = 0
cont = 0
for c in range(1,7):
val = int(input(F'Digite o {c}* valor '))
if val % 2 == 0:
soma += val
cont += 1
print(F'Você informou {cont} números PARES e a soma foi {soma}') |
55ecf818a899dceea091bb9bb3a5d1a491850262 | LeonGustavo/exercicios_curso_em_video | /desafio49.py | 132 | 3.796875 | 4 | val1 = int(input("Fale o numero que você deseja saber a tabuada "))
for c in range(1,11):
print(F'{val1} * {c} = {val1 * c}') |
fa60f0de5b5e21033924f61ff3e8b578b334716d | LeonGustavo/exercicios_curso_em_video | /desafio57.py | 208 | 4.09375 | 4 | sexo = str(input("Informe o sexo (M ou F) ")).upper().strip()
while sexo not in 'MmFf':
sexo = str(input('Digite o sexo corretamente ')).upper()
print(F'{sexo}')
print(F'O sexo escolhido é {sexo}')
|
84a3de94aec502c0adaac924ef6b43ebd8681e1f | bnavalniy/PyClass | /homeWorks/2/Task3PeriodOfYear.py | 615 | 4.21875 | 4 | # 3. Пользователь вводит месяц в виде целого числа от 1 до 12.
# Сообщить к какому времени года относится месяц (зима, весна, лето, осень).
# Напишите решения через list и через dict.
input_month = int(input("Enter month number 1-12: "))
periods = dict(spring=[3, 4, 5],
summer=[6, 7, 8],
a... |
d13c7bcaffd4d6fb00b7bd6bb457b40d6abec442 | bnavalniy/PyClass | /homeWorks/7/3_Cell.py | 1,099 | 3.75 | 4 | class Cell:
def __init__(self, cells):
self.cells = int(cells)
def __str__(self):
return str(f"Quantity of cells: {self.cells}")
def __add__(self, other):
return self.cells + other.cells
def __sub__(self, other):
delta = self.cells - other.cells
return delta if... |
9cdbfd64354060f18a9fc46a80bc053eb8ddab7d | bnavalniy/PyClass | /homeWorks/5/Task5Sum.py | 901 | 4.25 | 4 | """
Создать (программно) текстовый файл, записать в него программно набор чисел, разделенных пробелами.
Программа должна подсчитывать сумму чисел в файле и выводить ее на экран.
"""
def write_to_file(file_name):
file = open(file_name, "w")
while True:
user_input = input("Write to file: ")
if... |
67e94d0d10c8181417731c36fa30566a6c86398b | bnavalniy/PyClass | /homeWorks/4/Task2Generator.py | 311 | 3.875 | 4 | """
Пример исходного списка: [300, 2, 12, 44, 1, 1, 4, 10, 7, 1, 78, 123, 55].
Результат: [12, 44, 4, 10, 78, 123].
"""
my_list = [300, 2, 12, 44, 1, 1, 4, 10, 7, 1, 78, 123, 55]
new_list = [next_el for el, next_el in zip(my_list, my_list[1:]) if next_el > el]
print(new_list)
|
99277062857fe9589987a548254b08e06cbcfde2 | bnavalniy/PyClass | /homeWorks/2/Task1ListOfTypes.py | 478 | 3.5 | 4 | my_list = [2,
4.05,
'Super',
5 + 6j,
[1, 2, 3],
["tran", 'zi', 'stor'],
(2.5, "Do", 'It', [1, 3, 5]),
{2, 5, 6, 7, 8, 2},
{'name': 'Dan', 'age': 18, 'isStudent': True},
dict(name='Radik', age=16, isStudent=False)]
for ind... |
e34453c6b0de1acdfde4cbe701aaeb98b73e3b39 | bnavalniy/PyClass | /homeWorks/1/Task2Time.py | 323 | 3.90625 | 4 | seconds_input = int(input("Enter time in seconds:"))
# Hours
hours = seconds_input // 3600
# Minutes
minutes = (seconds_input // 60) - (hours * 60)
seconds = seconds_input % 60
time_message = (
f"{hours:02}:"
f"{minutes:02}:"
f"{seconds:02}"
)
print(time_message)
print(f"{hours:02}:{minutes:02}:{seconds:02}... |
037735e4904b09df0147b74c85b555a3c0d0dbfe | KateLev/GoogleBooks_cs50web | /import.py | 958 | 3.515625 | 4 | import csv
import os
from sqlalchemy import create_engine
from sqlalchemy.orm import scoped_session, sessionmaker
# database engine object from SQLAlchemy that manages connections to the database
engine = create_engine(os.getenv("DATABASE_URL"))
db = scoped_session(sessionmaker(bind=engine)) # create a 'scope... |
22915c36fed4af0e6530af64c86abdebbd24f5f4 | DaniBackEndCapstone/ParsingCSVDataPython | /generators/prisoners_gender.py | 1,059 | 3.671875 | 4 | import csv
def get_gender_data_parse_into_lists(NumberPersonsCorrectionalFacilityBySexAndStatus):
"""
Method that will read from the CSV file titled NumberPersonsCorrectionalFacilityBySexAndStatus
and parse CSV data into lists by line
Author: Dani Adkins
"""
with open(NumberPersonsCorrectional... |
c5c2e0b8e40b67d7729d7897500bfee8d89027ab | GivemeHam/CodingTest | /src/programmers/level2/다리를지나는트럭.py | 562 | 3.5625 | 4 | from collections import deque
def solution(bridge_length, weight, truck_weights):
time = 0
bridge = deque([0]*bridge_length)
bridge_weight = 0
while truck_weights:
time += 1
bridge_weight -= bridge.popleft()
if bridge_weight + truck_weights[0] > weight:
bridge.appe... |
b7790c27647dc9b30fd878a4c99dc9cf575ea80a | michaltal/project3 | /strings/Ex_2_4.py | 355 | 4.03125 | 4 | sentence = input("enter sentence: ")
print(sentence)
# length
print(len(sentence))
# letters in location 3 to 6
print(sentence[3:7])
# convert to list and print first word 3 times
list1 = sentence.split(' ')
print(list1)
print(list1[0] * 3)
# print the sentence with first capital letter in every word
for word in l... |
270b38858246d5f9ac8fa44ca50c304c6dc43623 | michaltal/project3 | /package1/input_output.py | 216 | 4.0625 | 4 | #this program receives 2 numbers and adds them
a=int(input("enter number one: ")) # get value for a
b=int(input("enter number two: "))
print("hello",a,b,a+b)
print ("the result of "+str(a)+"+"+str(b)+"="+str(a+b)) |
ccdc7665ab6ac1429ac3b18ac6d61664d3171009 | michaltal/project3 | /package1/If_Example_4.py | 166 | 3.90625 | 4 | grade = int(input("enter grade: "))
name = input("enter name: ")
if grade>=70 and (name=="Michael" or name=="George"):
print("passed")
else:
print("failed")
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.