blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
0f64cc1e90527fdcc0bcb77eb85c9f6d8c2e59c5 | rwehner/rl | /homework/Python3_Homework01/src/test_adder.py | 752 | 3.75 | 4 | '''
Created on Nov 19, 2013
@author: rwehner
Test the adder() function of the adder.py module
'''
import unittest
from adder import adder
class Test(unittest.TestCase):
def test_adder_failures(self):
"""
Test input that is expected to make adder()
fail.
"""
... |
d592a1b2c594fadb1cf66a573a1d93e593fb3cda | rwehner/rl | /homework/Python3_Homework09/src/centipede.py | 687 | 4.15625 | 4 | """
homework project for Lesson 09:
use magic methods
"""
class Centipede:
def __init__(self):
object.__setattr__(self, "stomach", [])
object.__setattr__(self, "legs", [])
def __call__(self, arg):
self.stomach.append(arg)
def __str__(self):
retu... |
f50bb13e9b07eb4a19142237e313168990eea6fe | rwehner/rl | /homework/Python3_Homework11/src/property_address.py | 2,075 | 3.890625 | 4 | """
homework lesson 11: add logging to homework from lesson 10
"""
import logging
import re
LOG_FILENAME = 'property_address.log'
LOG_FORMAT = "%(asctime)s - %(levelname)s - %(funcName)s - %(message)s"
DEFAULT_LOG_LEVEL = "info"
LEVELS = dict(debug=logging.DEBUG,
info=logging.INFO,
... |
6e01f0bb173ad59c1e516cd476c0fa2c75b93072 | CaseyJames669/Adv_Python | /BladowCasey.grades/grades.py | 5,519 | 4 | 4 | # file: grades.py
# author: Casey Bladow
# Student grades program
'''
This scripts takes an input file of student grades and outputs their name,
average scores, and final score.
'''
# Opens the input and output files
inFile = open('grades.csv','r').readlines()
outFile = open('grades.grd','w')
def numOfQuizzes(data)... |
ffc7843000c3272a5f5b7b1b888d7df08081436d | yashmate/Cryptographhy-and-Network-Security | /CSS Experiment One.py | 3,836 | 3.828125 | 4 |
alphabet_list=[chr(i) for i in range(ord('a'),ord('z')+1)]
number_list=[str(i) for i in range(1,27)]
alphabet_to_number=dict(zip(alphabet_list,number_list))
number_to_alphabet=dict(zip(number_list,alphabet_list))
def caesar_cipher(string,key):
new_string=[]
for char in string:
char_number=alphabet_to... |
e3e6f105d5b23940814aade0cf4763348363995a | jiyudonggithub/-Machine-Learning | /Demo/DecoratorDemo.py | 414 | 3.5 | 4 | # -*- coding: utf-8 -*-
# @Time : 2020/9/3 19:28
# @Author : Jiyudong
# @FileName: DecoratorDemo.py
# @Software: PyCharm
'''
装饰器就是一个闭包,本质上是一个返回函数的函数
'''
# 简单的装饰器
def outer(func):
def inner(age):
if age < 0:
age = 0
func(age)
return inner
@outer
def say(age):
print("sunck... |
1d205bb0aa7febcf1c40c7fedcb04aa4fbb90d82 | jiyudonggithub/-Machine-Learning | /com/oak/test/Function.py | 1,715 | 4.1875 | 4 | # -*- coding: utf-8 -*-
# @Time : 2019/7/19 10:09
# @Author : Jiyudong
# @FileName: Function.py
# @Software: PyCharm
tuple1 = (1, 2, 3)
tuple2 = ('a', 'b', 'c')
tuple3 = tuple1 + tuple2
print(tuple3)
# num = int(input("请输入一个数:"))
# print(8 / 2)
# for i in range(2, num + 1):
# if num % i == 0:
# if i != nu... |
2023da1fd8556934358f8ea03f3987e1eca5c1c5 | bgxcpku/pythonproject | /misc/galvanize/Q1.py | 3,187 | 4.5625 | 5 | """
From the Galvanize problem set:
The challenge is to create a text content analyzer. This is a tool used by writers to find statistics such as word and sentence count on essays or articles they are writing.
Write a Python program that analyzes input from a file and compiles statistics on it.
The program should out... |
650c27d6d07727018ef0627e60a3f9dce516f324 | marco-cruzmaya/MYP-proyecto1 | /src/EventosChat.py | 1,553 | 3.5 | 4 | from enum import Enum
"""
Class EventoChat:
Enumeración donde se especifica cada evento del protocolo.
"""
class EventoChat(Enum):
IDENT = "IDENTIFY"
STATUS = "STATUS"
USERS = "USERS"
MSG = "MESSAGE"
PUBLICMSG = "PUBLICMESSAGE"
CREATEROOM = "CREATEROOM"
INVITE = "INVITE"
JOINROOM = ... |
1412de86ca22fdec2241556414586702e596dcb0 | fatmtly892/Python-Program-to-Convert-Binary-Number-to-Decimal- | /Python Program to Convert Binary Number to Decimal .py | 307 | 4.03125 | 4 | #!/usr/bin/env python
# coding: utf-8
# In[ ]:
#Taking a binary number input
binary = list(input("please enter a binary number: "))
d_num = 0
for i in range(len(binary)):
digit = binary.pop()
if digit == '1':
d_num = d_num + pow(2,i)
print("The Decimal Number is ", d_num)
# In[ ]:
|
12c31dbaeca01946838a9b18ed92e05fb971f583 | ArelaVka/lens_helper | /main.py | 3,206 | 3.71875 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Simple Bot to reply to Telegram messages.
This program is dedicated to the public domain under the CC0 license.
This Bot uses the Updater class to handle the bot.
First, a few handler functions are defined. Then, those functions are passed to
the Dispatcher and register... |
cc6898b8f46fec7d42e78199f8a9e2b9264d6ac6 | Weibo-Hu/CFD-Post | /source/timer.py | 615 | 3.765625 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Jun 14 19:04:17 2018
This class is a context manager which show the running time of a code block.
@author: weibo
"""
import time
class timer():
def __init__(self, message):
self.message = message
def __enter__(self):
self... |
5218495b4f6aba6e8c71fe5cad7e477ee4c6a984 | kanzul12/cp19_voice_detector | /Task -01/1.py | 150 | 3.9375 | 4 | s1=input("enter first string: ")
s2=input("enter second string: ")
a=list(set(s1)and set(s2))
print("The common words are: ")
for i in a:
print(i) |
d6d6e816eb215bef03b895c6e2afba156d58e7f1 | An-ling-TS/maze | /maze/py_/Maze_generation.py | 1,695 | 3.65625 | 4 | #迷宫生成脚本
#Maze_generation.py
#Prime迷宫生成算法
import random
import pygame
from py_.GLOBAL import *
class Maze:
LEN=0#迷宫长度--- 行
WID=0#迷宫宽度| 列
def __init__(self,length,wid):
self.LEN=length
self.WID=wid
#self.wall_01=pygame.image.load(r'G:\python_pro\maze\resource\picture\wall\wall_01.png')... |
b5180a2361b54193490b8825d6cfc3a4557df4e6 | standemdem/simplon-orange | /neural_net/oopFromScratch/activationLayer.py | 879 | 3.90625 | 4 | from layer import Layer
class ActivationLayer(Layer):
'''
inherit from base class Layer
add the activation part giving the output of every layer
'''
def __init__(self, activation, activation_prime):
'''
initialize the activation parameters
:params: activation = activation function of the layer
:params: ac... |
738a97a7393ebbc1354862df4d39c2d8e2759b4a | Hassan8521/alx-higher_level_programming-1 | /0x03-python-data_structures/5-no_c.py | 182 | 4.0625 | 4 | #!/usr/bin/env python3
"""
removes all characters c and C from a string
"""
def no_c(my_string):
new = [x for x in my_string if x != 'c' and x != 'C']
return "".join(new)
|
73f2da67df3867b89f494b8b0aed9f19d6313431 | Hassan8521/alx-higher_level_programming-1 | /0x0A-python-inheritance/2-is_same_class.py | 383 | 3.875 | 4 | #!/usr/bin/python3
"""My module"""
def is_same_class(obj, a_class):
"""checks if it is exact the same
Args:
obj(any) = the object to check
a_class(type) = the class to match the type with
Return:
True if the object is exactly an instance
otherwise False
"""
... |
ecef4ca12a3fd2fc6d1d304ed70d638b43010881 | HenriqueCSJ/Python-Lessons | /Dictionaries/game_dictionaries.py | 2,021 | 3.953125 | 4 | locations = {0: "You're sitting in front of the computer learning Python.",
1: "You are standing at the end of a road before a small brick building",
2: "You are at the top of a hill",
3: "You are inside of a building, a well house for a small stream.",
4: "You are in... |
f69a925087923c50977a8370935239e94f43c2b4 | HenriqueCSJ/Python-Lessons | /Loops/forloops.py | 378 | 3.640625 | 4 | # for i in range(1, 20):
# print("i is now {0}".format(i)) # i = index
number = "9.445.342.777.908.999.567"
cleanNumber = ''
for i in range(0, len(number)): # len = comprimento de uma string
# print(number[i])
if number[i] in "0123456789":
cleanNumber = cleanNumber + number[i]
newNumber = int(c... |
76a713fc3bb66fef6b2be738efa76ad14edac80e | HenriqueCSJ/Python-Lessons | /ML-Course/Matplotlib1.py | 943 | 3.65625 | 4 | import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(0, 5, 11)
y = x**2
list(zip(x, y))
plt.plot(x,y)
plt.xlabel("X axis")
plt.ylabel("Y axis")
plt.title("Ttitle here")
plt.subplot(1, 2, 1)
plt.plot(x, y, "r")
plt.subplot(1, 2, 2)
plt.plot(y, x, "b")
# OO
fig = plt.figure()
axes = fig.add_axes([0.1, 0... |
1b6bc1d9cd0b15e7ec12de02585165637d100f11 | HenriqueCSJ/Python-Lessons | /Dictionaries/jogo_ptbr.py | 1,361 | 3.875 | 4 | # -*- coding: iso8859-1 -*-
import os
import sys
from random import randint
locais = {0: "Você está na frente do computador aprendendo Python.",
1: "Você está parado no fim de uuma estrada, na frente de um prédio de tijolos.",
2: "Você está no topo de uma colina.",
3: "Você está dentro de... |
4df1ea0e82190c22984458a5d0899aad426bc42d | HenriqueCSJ/Python-Lessons | /Dictionaries/joins.py | 313 | 3.609375 | 4 | myList = ["a", "b", "c", "d"]
newString = ""
# for c in myList:
# newString += c + ", "
newString = ", ".join(myList)
print(newString)
letters = "abcdefghijklmnopqrstuvwxyz"
newString = ", ".join(letters)
print(newString)
numbers = "1234567890"
newString2 = " Mississippi, ".join(numbers)
print(newString2) |
2e232c143435de66a76c392634c80b5b309456a9 | HenriqueCSJ/Python-Lessons | /Challenges/challenge2.py | 1,967 | 4.4375 | 4 | # Create a program that takes an IP address entered at the keyboard
# and prints out the number of segments it contains, and the length of each segment.
#
# An IP address consists of 4 numbers, separated from each other with a full stop. But
# your program should just count however many are entered
# Examples of the in... |
67d76ed14e02bafc159b58fc355b91b4e8dc4afa | quisitor/CMIT-135-40D-WEEK4 | /multiplication_table.py | 819 | 3.953125 | 4 | """
:Student: Craig Smith
:Week-4: Loops
:Module: guess_the_number
:Course: CMIT-135-40D (Champlain College)
:Professor: Steve Giles
:Author: Craig Smith
Purpose
-------
The program prints a formatted multiplication chart for numbers 1-9 to the terminal
Constraints
-----------
1. Chart should reflect numbers 1 to 9
... |
4f6c3db33150fba1d1241ca861d7b6ba50923544 | jmhaefner/Numbers | /collatz.py | 413 | 3.90625 | 4 | import sys
iterator = int(sys.argv[2])
k = int(sys.argv[1])
print('Collatzing', k)
def collatz(n):
if n % iterator == 0:
return n/iterator
else:
return 3*n+1
return (iterator+(n % iterator))*n+(iterator-(n % iterator))
i = 0
imax = 100
while not k == 1 and not i >= imax:
k = colla... |
505ba3d68dad07c3c3e1c415cdaa58514e2d2e8f | quangnhan/PYT2104 | /Day11/nhomtien/nguoimau.py | 368 | 3.625 | 4 | class NguoiMau():
def __init__(self,age,money,year,interest):
self.age = age
self.money = int(money)
self.interest = int(interest)
self.year = int(year)
def say_hi(self):
print(f'naam nay em {self.age} ngon hong')
def tinh_lai_kep(self):
print(f'so tien l... |
88b1e5c44f168e789ec408e9d70f2da26da69a1d | fractalis/hackerrank | /problem-solving/Implementation/bon-appetit.py | 516 | 3.65625 | 4 | #!/bin/python3
# https://www.hackerrank.com/challenges/bon-appetit/problem
# Complete the bonAppetit function below.
def bonAppetit(bill, k, b):
itms = bill[:k] + bill[k+1:]
billTotal = sum(itms)/2
if billTotal == b:
print("Bon Appetit")
else:
print(int(b-billTotal))
if __name__ == '_... |
e939cb7231302715ef33e727ab8564fd461e8295 | fractalis/hackerrank | /python/nested-list.py | 567 | 3.890625 | 4 | # https://www.hackerrank.com/challenges/nested-list/problem
from collections import defaultdict
if __name__ == '__main__':
scores = []
scores_dict = defaultdict(lambda: [])
for _ in range(int(input())):
name = input()
score = float(input())
ns = [name, score]
scores.appe... |
2b222652fc751eea06ddb1258b38a149604d742f | FREDY1969/tampa-bay-python-avr | /ucc/database/block.py | 15,312 | 3.796875 | 4 | # block.py
r'''The helper class for blocks of intermediate code.
A block of code is only entered at the top, and only exited at the bottom.
Thus, there are never any jumps into the middle of a block, or jumps out of
the middle of a block.
The code for each block is represented by a directed acyclic graph whose nodes... |
79f6f8cc21d83589ef01ffd42c7cbeacd787b0d3 | kevenLeandro/programacaoParaBancodeDados | /ExtremamenteBasico.py | 57 | 3.5625 | 4 | A= int(input(""))
B= int(input(""))
X=A+B
print("X =",X) |
a9c9b72279e517ba02b68d42fdfd0682f67a8e80 | jpavankumar/PracticePython3 | /fibonacci_generator.py | 206 | 3.9375 | 4 | #!/usr/local/bin/python3.4 -tt
def fibonacci(a,b):
while(True):
a, b = b , a + b
yield a
f = fibonacci(1,10)
for num in f:
if ( num > 10000 ):
break
print(num,end=' ') |
5d6cb197aa5e751072f1358c87dd0d69e07f090b | millsgt/oop-python | /Examples/example_7_class_attributes.py | 1,579 | 3.828125 | 4 | from enum import Enum
class Condition(Enum):
NEW = 0
GOOD = 1
OKAY = 2
BAD = 3
class MethodNotAllowed(Exception):
pass
class Bike(object):
count = 0
num_wheels = 2
def __init__(self, description, condition, sale_price, cost=0):
self.description = description
self.c... |
fb6040b36af45f2c6adbf4363786248ff046a69f | millsgt/oop-python | /Examples/example_9_getters_setters.py | 1,819 | 3.671875 | 4 | import random
from enum import Enum
class Condition(Enum):
NEW = 0
GOOD = 1
OKAY = 2
BAD = 3
class MethodNotAllowed(Exception):
pass
class Bike(object):
def __init__(self, description, condition, sale_price, cost=0):
self.description = description
self.condition = condition... |
869c52ce12dbc6e50d07ba3b05ec5ea9dfc517c7 | millsgt/oop-python | /Examples/example_5_methods.py | 1,235 | 3.671875 | 4 | """
Bike class for use in a retail shop
"""
from enum import Enum
class Condition(Enum):
NEW = 0
GOOD = 1
OKAY = 2
BAD = 3
class MethodNotAllowed(Exception):
pass
class Bike:
def __init__(self, description, condition, sale_price, cost=0):
self.cost = cost
self.sale_price = ... |
07037bc013ed81a8321a1c62f072cf35ab54e6c2 | mikkey21/testPython | /main.py | 775 | 3.984375 | 4 | # This is a sample Python script.
# Press Shift+F10 to execute it or replace it with your code.
# Press Double Shift to search everywhere for classes, files, tool windows, actions, and settings.
def Fibonacci(n):
# Check if input is 0 then it will
# print incorrect input
if n < 0:
print("Incorrec... |
ef5e63139d018f97ba0c80fcb574999f0dd38f70 | sichkar-valentyn/Lists_inside_Dictionary_in_Python | /Lists_inside_Dictionary_in_Python.py | 1,792 | 4.28125 | 4 | # File: Lists_inside_Dictionary_in_Python.py
# Description: Calculating the scores of sports team by using Lists inside Dictionary
# Environment: PyCharm and Anaconda environment
#
# MIT License
# Copyright (c) 2018 Valentyn N Sichkar
# github.com/sichkar-valentyn
# Reference to:
# [1] Valentyn N Sichkar. Lists... |
ed640b47f69e6dfc05a6c7d85ef1d9257d339e43 | tomGrose/python-data_structure-practice | /19_friend_date/friend_date.py | 787 | 4 | 4 | def friend_date(a, b):
"""Given two friends, do they have any hobbies in common?
- a: friend #1, a tuple of (name, age, list-of-hobbies)
- b: same, for friend #2
Returns True if they have any hobbies in common, False is not.
>>> elmo = ('Elmo', 5, ['hugging', 'being nice'])
>>> sauron... |
2eba1dbd4e7d58f67b1a5946e89c976e53ad1259 | zmoitier/lostinmsh | /lostinmsh/geometry/border.py | 3,273 | 3.5625 | 4 | """Class for boundary."""
from dataclasses import dataclass
from typing import Optional
from numpy.linalg import norm
from numpy.typing import NDArray
from .smallest_boundary import smallest_circle, smallest_rectangle
@dataclass(kw_only=True, slots=True)
class Border:
"""Border class.
Attributes
----... |
26116e62947f81cd5884937d4d46ab8e7a7b8119 | YerraboluHimajaReddy/LalithaClass | /LalithaPythonClass/All/boolean literals.py | 215 | 3.734375 | 4 | x = (1 == True) # 1==1 : true
y = (1 == False) # 0==1 : false
a = True + 4 # 1+4 =5
b = False + 10 # 0+10 =10
print("x is", x) # x is True
print("y is", y) # y is False
print("a:", a) # a: 5
print("b:", b) # b: 10
|
63a425f1c8092f69dd76249dfb007b8d20eab272 | YerraboluHimajaReddy/LalithaClass | /LalithaPythonClass/Functions/Python Default Arguments.py | 467 | 3.96875 | 4 | def greet(name, msg="Good morning!"):
"""
This function greets to
the person with the
provided message.
If the message is not provided,
it defaults to "Good
morning!"
"""
print("Hello", name + ', ' + msg)
greet("Lalitha")
greet("Lalitha","Have a nice day")
print(greet.__doc__)
#... |
104a5c7038014a3b7288590e127407903ae5b9f4 | YerraboluHimajaReddy/LalithaClass | /LalithaPythonClass/ConditionalStatements/Python if Statement.py | 242 | 4.1875 | 4 | from builtins import print
num =3
print(num) # 2
if num==2:
print(num) # 2
if num >0:
print(num) # 2
num = -1
if num > 0:
print(num, "is a positive number.")
print("This is also always printed.") #This is also always printed.
|
f6affe3bc8bb65cc21f0e2ea7fc2d3c0d0c3d2e1 | YerraboluHimajaReddy/LalithaClass | /LalithaPythonClass/OopConcepts/ChildClass.py | 623 | 3.515625 | 4 | # child class
from LalithaPythonClass.OopConcepts.Bird import Bird
class Penguin(Bird):
def __init__(self):
# call super() function
super().__init__()
super().whoisThis()
print("Penguin is ready")
def whoisThis(self):
print("Penguin")
def swim(self):
print(... |
aac6eef18a908e4c625d00ebbfe8b097cbdbd4f0 | YerraboluHimajaReddy/LalithaClass | /LalithaPythonClass/AdvancedDatatypes/Set Difference.py | 226 | 3.578125 | 4 | # Difference of two sets
# initialize A and B
A = {1, 2, 3, 4, 5}
B = {4, 5, 6, 7, 8}
# use - operator on A
print(A - B) #{1, 2, 3}
print(B - A) #{8, 6, 7}
print(A.difference(B)) #{1, 2, 3}
print(B.difference(A)) #{8, 6, 7}
|
adeb4f6dba3a7f452d253293512b29be109a71d7 | YerraboluHimajaReddy/LalithaClass | /LalithaPythonClass/Constructor/ConstructorExample4.py | 226 | 3.796875 | 4 | class Car:
# default constructor
def __init__(self):
self.wheels = 4
self.doors = 2
self.chairs = 2
obj1 = Car()
obj2 = Car()
print(obj1.doors) # 2
print(obj2.doors) # 2
print(obj2.wheels) # 4 |
7e1390418c2d874699b2a08bc9089ff4b4c207fe | YerraboluHimajaReddy/LalithaClass | /LalithaPythonClass/Functions/global KeywordExample2.py | 275 | 3.78125 | 4 | c = 1 # global variable
#def add():
# c = c + 2 # increment c by 2 : UnboundLocalError: local variable 'c' referenced before assignment
# print(c)
def add():
c=20
c = c + 2
print(c)
add()# 22
def add():
#print(c)
c = 15
print(c)
add()#15 |
c26532328aa2cac20eb5c63db50c771198ec6b13 | robotjandal/jigsaw | /jigsaw/fileIO.py | 4,547 | 3.5 | 4 | """ This file contains shared classes and functions.
* yamlFileIO returns the contents of the config.yaml file as a dict
* CSVFileIO is used to read from or write to a .csv file.
"""
import logging
import os
from pathlib import Path
import yaml
import csv
import numpy as np
import shutil
class CSVFileIO:
... |
de00e74fd5319fb38ef0a4eed8ede39de60f9bbb | Maya-hermes-Kali321/Booleans | /IsEqual.py | 382 | 3.90625 | 4 | print("first number")
first = input()
print("second number")
second = input()
print("third number")
third = input()
allOfTheNumbersAreEqual = first == second and second == third and third == first
print("All are equal:", allOfTheNumbersAreEqual)
anyOfTheNumbersAreEqual = first == second or second == third or third == f... |
67322edf03f0e7cb8f76562f4e9082610591a626 | amalko/Python-Project--Decimal-to-Binary-Conversion- | /decimal to binary conversion.py | 284 | 3.921875 | 4 |
x=[]
num= int(input("Enter a decimal number: "))
while num>0:
a=num % 2
x.append(a)
num= int(num/2)
print("Binary representation of the given decimal number is : ")
x.reverse()
l= len(x)
for i in range(l):
print(x[i], end='')
print()
|
b46c71377796e4350a6b94b35039e88759960d66 | agakshay/Python_Projects | /Bot saves princess.py | 819 | 3.859375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Thu Feb 25 22:04:40 2021
@author: akshay
"""
def displayPathtoPrincess(n,grid):
# Finding position of p and m
for x,row in enumerate(grid):
if 'p' in row:
p = (x, row.index('p'))
if 'm' in row:
m = (x, row.index('m')... |
38b1a5ce5e57d87c801dfa3b78d9dad59accec9b | br-anupama/vmware | /permutation.py | 371 | 3.953125 | 4 | #!/usr/bin/python
from itertools import permutations
def permutation_using_lib_fun(string):
res = [ "".join(p) for p in permutations(string)]
return res
try:
print "Enter a string to print in all permutation"
inp = raw_input()
res = permutation_using_lib_fun(inp)
print res
except Exception, e... |
4b062ae823b8be1fa87bab7f37d12620be9db0e1 | Williamsbsa/2048-Python | /Jogo2048.py | 26,832 | 3.9375 | 4 | #introdução ao jogo e tuturial
from random import randint, sample
print("=-"*30)
print(" >>>>>>>>>> Bem vindo ao 2048 !!!! <<<<<<<<<<")
print("-="*30)
def criarMatriz():
matrizTab = [0]*4 #ou matrizTab = [[0,0,0,0],
for cont in range(4): # [0,0,0,0],
matr... |
6b26201f70d1470083be9d617fb77324fcf4e759 | BBahoumda/CSIT-104 | /Collatz Problem.py | 255 | 4 | 4 | def collatz(n):
while n!=1:
print(n)
if n%2 == 0:
n = n // 2
else:
n= ((n*3) +1) // 2
def main():
n = int(input("Enter a number"))
collatz(n)
main()
|
d100594cd154c36194d1fcce97b6574f79719485 | adrianna-chang-shopify/learning-python | /Python Basics/4 - for_loop.py | 414 | 4.625 | 5 | # This is about the for loop
# Example of for loop with list
animals = ['Dog', 'Cat', 'Bear', 'Snail', 'Turtle', 'Lion']
for animal in animals:
print animal
# Like an enumerator - for x in a list, do something with x
# Example with a string
word = raw_input("Enter something: ")
for letter in word:
print "Gi... |
f60a295ce56095857f749e1a2ead24c5d3d9c137 | DanielNeira/Red-estocastica | /Norta.py | 15,658 | 3.5 | 4 | import numpy as np
import pandas as pd
from scipy.stats import norm, beta, expon, uniform, gamma, erlang, poisson
class Norta(object):
"""
This class contains the NORmal To Anything (NORTA) algorithm to produce vector with correlations in the dimensions.
Init:
matrix M (mxn), wich has n-dimensions... |
266af44d4690ab6d85a77b850bdf63d9dec511dd | rhine3/pysoundfinder | /pysoundfinder.py | 12,696 | 3.671875 | 4 | import pandas as pd
import numpy as np
import warnings
from matplotlib import pyplot as plt
def plot_solution(positions, u):
# Plot recorders as black circles
x_coords = positions['x']
y_coords = positions['y']
plt.plot(x_coords, y_coords,'ko')
# Plot solution as a red circle
plt.plot(u[0], u[... |
664e60dc91cc140a27283dd5bf8f597b5bfe8845 | ilyagz/Python-Practice | /53 - Max_Subarray.py | 536 | 3.796875 | 4 | # 53. Maximum Subarray
#Given an integer array nums, find the contiguous subarray (containing at least one number) which has the largest sum and return its sum.
class Solution(object):
def maxSubArray(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
sum = float("-inf"... |
2814fbb76c14cf556e626d9cec121eb319e2bee2 | ssolanki/algorithms | /python/checksum.py | 439 | 3.828125 | 4 | # problem: http://www.geeksforgeeks.org/write-a-c-program-that-given-a-set-a-of-n-numbers-and-another-number-x-determines-whether-or-not-there-exist-two-elements-in-s-whose-sum-is-exactly-x/
# trivial is sort
def checkSumInArray1(array,sum):
temp = array[:]
print temp.sort()
print array
def checkSumInArra... |
1a0cc0913f0adcd002e78e6bde97e1e1f64409de | MSJYYT/code | /data structure&algorithm-python/dict/AVL.py | 4,745 | 3.515625 | 4 | from tree import classtreeNode
from dict import binary_sort_tree
#首先把AVL树节点类定义为二叉树节点类的子类
#增加一个bf域,叶节点bf值为0
class AVLNode(classtreeNode.BinTNode):
def __init__(self, data):
classtreeNode.BinTNode.__init__(self,data)
self.bf = 0
#AVL树是一种二叉排序树,将这个类定义为DictBinTree的子类,初始化为空树
class DictAVL(binary_sort_tre... |
245481e792ee06871e9dbc77c5dc80e00f9912af | leigh90/zero-to-hero-python-Udemy | /Section13:AdvancedModules/collexions.py | 1,777 | 4.21875 | 4 | from collections import Counter
# use counter to count the number of instances of each element in a list and orders them in order of element with the highest number of appearances
mylist = [1,1,1,1,1,1,1,2,2,2,2,2,2,3,3,3,3,3,3,3]
print(Counter(mylist))
# returns a dictionary object with the elements being counted as ... |
e5f57e5e8ac1a72d2cee4001e667d97dbc476640 | leigh90/zero-to-hero-python-Udemy | /Section10:Errors&Handling/errors.py | 2,324 | 4.21875 | 4 | # ERROR HANDLING KEYWORDS
# TRY - Block of code attempted which may or may not lead to an erro
# EXCEPT - Block of code which will execute in case there is an error in the try block
# FINALLY - A final block of code to be executed, regardless of an error
# The try except block allows the code to run even after an error... |
5d7139705bea939a8b35cb7b73b79b3d3ded1487 | openworm/owmeta | /examples/NetworkInfo.py | 3,784 | 3.65625 | 4 | """
Get information about the network.
In this case, we are interested in a small set of neurons. We go through each of
the neurons and get connectivity information about each connection it has with
another cell.
This type of script could be useful for visualizing data, generating reports,
or any number programmatic ... |
4200e56709afbad43211fea4439f692f7a6f8351 | med7atdotnet/Information-Retrival-System | /dictionary_processing.py | 274 | 3.5 | 4 | dictionary = {
'u.s': 'usa',
'u.n': 'un',
'united states': 'usa',
'united nations': 'un',
'los angeles' : 'la',
'viet nam' : 'vietnam',
}
def dictionaryFormat(s):
for i in dictionary:
s = s.replace(i,dictionary[i])
return s
|
2163634f4b8f51c55e27f329093331af1cb9abab | BeanHubbleday/python | /challenge_4.py | 928 | 4.5625 | 5 | # Challenge 4
option = int(input("Do you need to know the speed you need to travel at to arrive at your destination in the required amount of time OR know the distance travelled currently? Enter 1 for Speed OR 2 for Distance: "))
if option == 1:
distance = int(input("How far, in miles, do you need to travel? Enter... |
49ddc859359c84a34ea8dee51ba349c8b0618fdc | prkirankumar/LearningPython | /OOPS/static_method.py | 3,263 | 4.375 | 4 | from datetime import datetime
class Employee:
EMPLOYEES_GRADES = {
'A': '2500',
'B': '3000',
'C': '3500',
'D': '4000'
}
def __init__(self, first_name, last_name, grade):
self.first_name = first_name
self.last_name = last_name
print("This is from con... |
e85a13c9889f779cb6c0a6b599252e23071565c2 | prkirankumar/LearningPython | /OOPS/method_overriding.py | 3,004 | 4.125 | 4 | '''
Method overriding : reimplementation of method inherited from the base class in the derived class
It has the same name as the method in the base class and same method signature
The implementation in the derived class replaces the implementation in the in the base class
'''
class Teacher:
def __init__(self,fi... |
9e7537c5e4c0e00ee9db139f14a4b66213eff307 | prkirankumar/LearningPython | /Basics/lists.py | 2,929 | 4.59375 | 5 | ''' ***** Lists *****
Unlike C++ or Java, Python Programming Language doesn’t have arrays. To hold a sequence of values, then, it provides the ‘list’ class.
A Python list can be seen as a collection of values.
To create python list of items, you need to mention the item... |
0a121a378f7fa4625d81c3cc524f21b7164c8f7b | prkirankumar/LearningPython | /Basics/functions_user_defined.py | 3,000 | 4.34375 | 4 | '''
We follow the same rules when naming a function as we do when naming a variable.
It can begin with either of the following: A-Z, a-z, and underscore(_).
The rest of it can contain either of the following: A-Z, a-z, digits(0-9), and underscore(_).
A reserved keyword may not be chosen as an identifier.
'''
def my_... |
023f719e11e99f6a7efb7ea8787d9a3b2439a9e6 | hsinha177/Python | /Name_greet.py | 319 | 4.03125 | 4 | #pgm for greeting you; only you have to enter yr name
import datetime
t = datetime.datetime.now()
curhr = t.hour
n = input("Enter your name : " )
if t.hour<12 :
print(f"Good morning {n}")
elif t.hour<16 :
print(f"Good afternoon {n}")
elif t.hour<20 :
print(f"Good evening {n}")
else :
print(f"Good night {n}")
|
6f065b569bbe96424f3b37af4e497324ee7ebfb3 | panguangze/whatshap | /whatshap/math.py | 782 | 4.25 | 4 | # This function was copied from Python 3.5’s statistics module.
# The StatisticsError was changed to a ValueError.
def _median(data):
"""Return the median (middle value) of numeric data.
When the number of data points is odd, return the middle data point.
When the number of data points is even, the media... |
d69fb441dfcfdd939261a68fb80839d0713f3d5f | root221/AI-for-Robotics | /search.py | 2,466 | 3.921875 | 4 | # ----------
# User Instructions:
#
# Define a function, search() that returns a list
# in the form of [optimal path length, row, col]. For
# the grid shown below, your function should output
# [11, 4, 5].
#
# If there is no valid path from the start point
# to the goal, your function should return the string
# 'fail'... |
b0339f52e4b18973d3dd40af49d090187157386e | jeremiahtenbrink/Sorting | /src/recursive_sorting/recursive_sorting.py | 1,709 | 4.125 | 4 | # TO-DO: complete the helpe function below to merge 2 sorted arrays
def merge(arrA, arrB):
elements = len(arrA) + len(arrB)
merged_arr = [0] * elements
i = 0
j = 0
k = 0
while i < len(arrA) and j < len(arrB):
if arrA[i] < arrB[j]:
merged_arr[k] = arrA[i]
i += 1
... |
aab8f930bd220b579ed58a49f6ea22bea8cb8df5 | xhlin1217/python | /18. Regular Expressions.py | 1,176 | 3.953125 | 4 | # Regular Expressions
import re
# match = re.search('hello', 'search pattern in hello world')
# print(match) # return the match value
# print(match.re.pattern) # return the match target
# print(match.string) # return the match string
# print(match.start()) # return the match target start index in the match string
#... |
c837800abd23e2651a2db24b9c6cdb1a98d5f9ef | kishorep07/ML-Experiments | /Classification/Logistic Regression.py | 3,083 | 3.84375 | 4 | """
#Logistic Regression (Used to predict probablity)
Action is discrete (Yes or No)
Instead of predicting wether Y or No, we will predict the probablity
Below and above Y&N are very likely to say No&Yes respectively
Substitute y=mx+b into the sigmoid function and solve to attain a smooth curve
Probablity(p_hat... |
67247fe8c13e07e6d85507e919908a7a7bc88804 | kishorep07/ML-Experiments | /Reinforcement Learning/Upper Confidence Bound.py | 2,688 | 4.09375 | 4 | """
Multi Armed Bandit Problem
Single Armed Bandit = Slot machine
How do u play them to maxmimize returns?
Each machine has a distribution associated with it, goal is to figure that out
regret: non optimal method
Modern App: Advertising (find which method is best)
Example:
multiple ads avail to disp to user, ... |
a8539ce097c792cbc4a9afc981c517b40398292f | ZhangNANPy/NowCoderPractice | /HasSubtree/HasSubtree.py | 1,114 | 3.796875 | 4 | # -*- coding:utf-8 -*-
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def HasSubtree(self, pRoot1, pRoot2):
if pRoot1 == None or pRoot2 == None:
return False
if pRoot1.val == pRoot2.val:
... |
475f79e76395e09c2b2639738c7c30ff109d4fab | dwebe003/algorithms | /is-anagram/anagram.py | 1,047 | 4.15625 | 4 |
def isAnagram(str1, str2):
# initial check of length. It is obvious that two strings of
# unequal length cannot be anagrams.
if len(str1) != len(str2):
return false;
# initialize an array of char values for each string.
# we will iterate through each string and increment
# whatever value is seen
hits1 ... |
2c80a98af5c9ac5dcadadfdd4f1097b9b7ef0b28 | nusk3r/Stacks | /StackwPyLists.py | 601 | 3.828125 | 4 | class Stack:
def __init__(self):
self.stack = []
def isEmpty(self):
return self.stack == []
def push(self, data):
self.stack.append(data)
return
def pop(self):
if self.isEmpty():
return -1
else:
return self.stack.pop(... |
e03dfa1ca0fb5931652cdc4a67d66552815de847 | dxab/Violent-Python-exercises | /cryptcracker.py | 2,208 | 4.15625 | 4 | import crypt
#This program takes a common password dictionary as dictionary.txt
#file and calculates the crypt() hashes along with a given salt
#it creates an output file of the saltes hashes called ohashes.txt
#it then takes password:combo input from a text file named
#breaches.txt and parses the hashes from it. Thes... |
2c904ff337080c986e07f8eb45d0986e11ef48dc | xopxop/Euler_Project | /Problem_002/main.py | 384 | 3.875 | 4 | def main():
solution = 0
x = fibonacci_generator(4000000)
for i in x:
print(i)
if i % 2 == 0: solution += i
print(f'solution: {solution}')
def fibonacci_generator(stop):
num1 = 1
num2 = 2
yield num1
yield num2
while num1 + num2 <= stop:
if num2 > num1:
num1 += num2
yield num1
elif num1 > num2:
... |
98901970ae9dbc40a1a495bd8ee633c9f460a5c6 | rectheworld/Bad_Toy | /Room.py | 1,687 | 3.59375 | 4 | import pygame
#This is your class Olivia
#from room_logic import Room_Logic
class Room():
def __init__(self,room_name, image_file,exit_list = None):
""""
self.exits holds the tupis Ie ________________
Add bottom exits
"""
self.room_name = room_name
self.image = pygame.image.load(image_file).convert... |
284f242aa54464202ae86b572ebbcd6fb65c16c1 | sealio-io/tacoPy | /index.py | 1,589 | 4.21875 | 4 | tacos = []
# Taco Class
class Taco():
def __init__(self,customer,meat,topping):
self.customer = customer
self.meat = meat
self.topping = topping
def finalyzeOrder(self):
taco = self.meat, "and" ,self.topping
tacos.append(taco)
print("Hey",self.customer... |
ee063fb96ec45455da98b7ad7f6cca3cdf588129 | google/or-tools | /ortools/linear_solver/samples/linear_programming_example.py | 2,382 | 3.5 | 4 | #!/usr/bin/env python3
# Copyright 2010-2022 Google LLC
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law ... |
451169f9acf67d4c90304633d2c2d15611a87de8 | NguyenThao1912/CyberSecurity | /Ma_Khoi_Hien_Dai/des.py | 17,734 | 3.640625 | 4 | import binascii
from numpy.compat import unicode
from tabulate import tabulate
from textwrap import wrap
def bintohex(string):
return str(hex(int(str(string), 2))[2:])
class BinString(str):
"""
Native Python str extension to validate binary-numbers-only strings and
support for some bitwise operations... |
1e3c3920688aa05e86a2fe66abc4deb601d12468 | bboatright013/python_data_structures | /39_find_greater_numbers/find_greater_numbers.py | 774 | 4.53125 | 5 | def find_greater_numbers(nums):
"""Return # of times a number is followed by a greater number.
For example, for [1, 2, 3], the answer is 3:
- the 1 is followed by the 2 *and* the 3
- the 2 is followed by the 3
Examples:
>>> find_greater_numbers([1, 2, 3])
3
>>> find_great... |
eab8f04d854657c1eda98760f95799dc9e658dc1 | bboatright013/python_data_structures | /05_reverse_string/reverse_string.py | 348 | 3.890625 | 4 | def reverse_string(phrase):
"""Reverse string,
>>> reverse_string('awesome')
'emosewa'
>>> reverse_string('sauce')
'ecuas'
"""
rev = []
for char in phrase:
rev.append(char)
print(rev)
rev.reverse()
print(rev)
reverse = ''.join(rev)
print(reve... |
ea90e5fb3458f7a86b5db1368ff39d9954a3022f | Apra001/games | /tile_set.py | 1,920 | 4.09375 | 4 | import pygame.image as pi
"""
A tile set is a single image with multiple tiles in it, organized into rows and columns. The TileSet class loads a tile
set into memory and supports addressing and retrieving tiles by index. For example, suppose that there is a tile set
image that is 40 x 20 pixels wide, with 10 x 10 tile... |
3917b570e5840c9be11c39901e64064d3bbb116d | anton-shum/Neo-Simulator | /src/Value.py | 385 | 3.5 | 4 | from enum import Enum, auto
class ValueType(Enum):
ASCII = auto()
Number = auto()
class Value:
def __init__(self, name):
self.name = name
self.type = self.__get_type(name)
def __get_type(self, name):
if name.lower() in ['a', 'ascii', 'asci']:
return ValueType.ASCII... |
7cad4567d1f690c4c8b82b994b4a05987d40a530 | iandupzyk/datautils | /datautils/utils/dateutils.py | 1,276 | 3.65625 | 4 | import time
import calendar
DATEINTFORMAT = "%Y%m%d"
HOURINTFORMAT = "%Y%m%d%H"
class datetime(object) :
def __init__(self, dt) :
pass
def epoch(ms=False) :
"""
Return the current number of seconds from the epoch (1970-01-01 00:00:00)
If ms is specified to be True, then the epoch returned is ... |
0ae1b21ef99d689aab484cf1fe0017d369b3becf | aichaitanya/Python-Programs | /stack.py | 2,081 | 3.59375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Wed Apr 17 12:00:19 2019
@author: Patil
"""
a = []
def printstk():
for i in a:
print(i)
def push(a):
ele=int(input('Enter element : '))
a.append(ele)
def pop(a):
if(top!=-1):
print(a.pop(),'Popped')
else : print('Sta... |
ce500177746dce25a6ecef7b10f0622131d13f65 | aichaitanya/Python-Programs | /calculator.py | 951 | 3.65625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Tue Apr 16 20:15:38 2019
@author: Patil
"""
a = int(input('Enter Number 1 : '))
b = int(input('Enter Number 2 : '))
ch=1
while(ch==1):
print('1. Add 2. Sub 3. Mul 4. Div 5. Mod 6. Exp\n ')
o = input('Enter Option : ')
if o=='+':
print('Add : '... |
1e2fced3e6ef3e7e6769c38b24f38a24c2b214fe | Indrajith1446/Python_console-games | /_3_black_jack.py | 5,020 | 3.640625 | 4 | import random
suits = {"Hearts","Diamonds","Clubs","Spades"}
ranks = {'Two','Three','Four','Five','Six','Seven','Eight','Nine','Ten','Jack','Queen','King','Ace'}
values = {'Two':2,'Three':3,'Four':4,'Five':5,'Six':6,'Seven':7,'Eight':8,'Nine':9,'Ten':10,'Jack':10,'Queen':10,'King':10,'Ace':11}
playing = True
... |
75389d3d9faf5dfa7fad88fca58353d0787ccda8 | shrenik-jain/HackerRank-Solutions | /1.Python/03.Strings/011.AlphabetRangoli.py | 642 | 3.984375 | 4 | '''
Question : You are given an integer, N.
Your task is to print an alphabet rangoli of size N.
size 3
----c----
--c-b-c--
c-b-a-b-c
--c-b-c--
----c----
Link : https://www.hackerrank.com/challenges/alphabet-rangoli/problem
'''
i... |
3bdc6e9a978b8b4bebe3a795c2296afa43719ae2 | shrenik-jain/HackerRank-Solutions | /1.Python/03.Strings/013.TheMinionGame.py | 400 | 3.625 | 4 | def minion_game(string):
p1 , p2 = 0 , 0
n = len(string)
for i in range(n):
if string[i] in "AEIOU":
p1 += n - i
else:
p2 += n - i
if p1 > p2:
print("Kevin" , p1)
elif p2 > p1:
print("Stuart" , p2)
else:
print("Dra... |
630b2617b7e9bd5ac3ae295addd5dc94c6fe7a02 | shrenik-jain/HackerRank-Solutions | /2.Problem Solving/02.Implementation/006.MigratoryBirds.py | 1,000 | 4.1875 | 4 | '''
Question : You have been asked to help study the population of birds migrating across the continent.
Each type of bird you are interested in will be identified by an integer value. Each time a particular
kind of bird is spotted, its id number will be added to your array of sightings.
... |
50deb4267a25a50d0e4da09a3d0d98b9ae140b1c | shrenik-jain/HackerRank-Solutions | /2.Problem Solving/01.Warmup/006.PlusMinus.py | 701 | 3.734375 | 4 | '''
Question : Given an array of integers, calculate the ratios of its elements that are positive, negative, and zero.
Print the decimal value of each fraction on a new line with 6 places after the decimal.
Link : https://www.hackerrank.com/challenges/plus-minus/problem
'''
def plusMinus(arr):
pos , n... |
e2496f9becf95468d6a3295a8d27ed30647c7eb2 | shrenik-jain/HackerRank-Solutions | /1.Python/06.Itertools/003.Combinations.py | 389 | 3.875 | 4 | '''
Question : You are given a string S. Your task is to print all possible combinations, up to size k, of the string in lexicographic sorted order.
Link : https://www.hackerrank.com/challenges/itertools-combinations/problem
'''
from itertools import combinations
s,k = input().split()
for i in range(1 , int(k) + 1):... |
11be7697ff02253c0b421d79a0c5d1ce0a55b33a | shrenik-jain/HackerRank-Solutions | /2.Problem Solving/01.Warmup/007.Staircase.py | 286 | 4.34375 | 4 | '''
Question : Write a program that prints a staircase of size n.
Link : https://www.hackerrank.com/challenges/staircase/problem
'''
def staircase(n):
for i in range(1,n+1):
print(str("#"*i).rjust(n))
if __name__ == '__main__':
n = int(input())
staircase(n)
|
aa1f63db7444dcdfe7d5e894bdbf02c36c01a874 | shrenik-jain/HackerRank-Solutions | /1.Python/05.Math/002.FindAngleMBC.py | 322 | 4.0625 | 4 | '''
Question : You are given the lengths AB and BC.
Your task is to find angle MBC (angle theta, as shown in the figure) in degrees.
Link : https://www.hackerrank.com/challenges/find-angle/problem
'''
import math
a = int(input())
b = int(input())
print(round(math.degrees(math.atan(a/b))), u'\N{DEGREE SIGN}' , sep=''... |
700481bd55045cc0e162d904b760ef1c522f78f2 | edanik90/pythonStack | /python/fundamentals/functionIntermediate2.py | 1,287 | 4.0625 | 4 | # 1 Update Values in Dictionaries and Lists
x = [ [5,2,3], [10,8,9] ]
students = [
{'first_name': 'Michael', 'last_name': 'Jordan'},
{'first_name': 'John', 'last_name': 'Rosales'},
{'first_name': 'Mark', 'last_name': 'Guillen'},
{'first_name': 'KB', 'last_name': 'Tonel'}
]
sports_directory = {
'ba... |
3f4dcd7b86d00b49c1e295d9ef73f332c526b443 | edanik90/pythonStack | /python/OOP/storeAndProducts/products.py | 651 | 3.578125 | 4 | class Product():
def __init__(self, name, price, category):
self.name = name
self.price = price
self.category = category
def __repr__(self):
return self.name + self.category + str(self.price)
def update_price(self, percent_change, is_increased):
if is_increased... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.