blob_id stringlengths 40 40 | repo_name stringlengths 5 127 | path stringlengths 2 523 | length_bytes int64 22 545k | score float64 3.5 5.34 | int_score int64 4 5 | text stringlengths 22 545k |
|---|---|---|---|---|---|---|
4187a292e3c29ab3b60d0912d32fc50123b4bf66 | garner007/url-classification-system-ml | /dataAnalysis.py | 1,290 | 3.515625 | 4 | """
This module runs some statistics on the dataset to show some descriptive information about it.
"""
import pandas as pd
from names import names
benign_describe = 'benign_describe.csv'
malicious_describe = 'malicious_describe.csv'
# Combined list of benign / malicious URLS after encoding an cleaning
deduped_url ... |
25b0e71f733522c277da1090ba834b97c16cf673 | sd17fall/softdes.web | /files/activities/geometry-classes/geometry_beyond_1.py | 612 | 3.515625 | 4 | """
SoftDes in-class exercise: Going Beyond #1
"""
from geometry import Rect
class Circle(object):
def __init__(self, x, y, r):
pass
def radius(self):
pass
def diameter(self):
pass
def area(self):
pass
def contains_pt(self, x, y):
pass
def stochastic_... |
93fbf23e1473c3a066f3947b6eac3d987e5f8eae | Funnylaksa/toto | /app.py | 5,507 | 4.0625 | 4 | ########################################
"""
Aim: To find out what is the minimum tickets of lottery tickets bought that guarantees at least a group 7 win.
This means at least 3 numbers should match against the winning ticket.
Tried to increase coverage:
1) Uniform Distribution of numbers in tickets
2) Limit how many ... |
ff0020378e4521727e26a70d4e1657ed17854576 | Bascil/python-data-structures-code-challenge | /17.py | 1,086 | 4.3125 | 4 | # Dictionaries
'''
Are key value pairs
Are associative arrays like Java Hashmap
Dicts are unordered
'''
x = {'pork' : 25.3, 'beef': 33.8, 'chicken': 22.4 }
print(x)
x = dict([('pork', 25.3), ('beef', 33.8), ('chicken', 22.4)])
print(x)
x = dict(pork = 25.3, beef = 33.8, chicken = 22.4)
print(x)
# Add or update
x['s... |
ad53d041ab4877c2d165d185438b230fb07a401a | Bascil/python-data-structures-code-challenge | /23.py | 592 | 3.953125 | 4 | # Wrapper class implementation
from collections import deque
class Queue():
def __init__(self):
self.queue = deque()
def enqueue(self, item):
self.queue.append(item)
def dequeue(self):
if len(self.queue) > 0:
return self.queue.popleft()
else:
return None
def __str__(s... |
7aefe6f77d2102cf62ebd063f4a2cf44664d446e | Bascil/python-data-structures-code-challenge | /12.py | 169 | 3.921875 | 4 | # Index - Returns the index of the first occurrence of an item
# String
x = 'hippo'
print(x.index('p'))
# List
y = ['pig', 'cow', 'horse', 'cow']
print(y.index('cow')) |
435f8065d87811616423a01a69d54d6a6dad40da | Bascil/python-data-structures-code-challenge | /10.py | 221 | 3.953125 | 4 | # Sorting - Returns a new list of sorted items in sorted order
# This does not however change the original list. Outbut is a list
# String
x = 'bug'
print(sorted(x))
# List
x = ['pig', 'cow', 'horse']
print(sorted(x))
|
9cc439f9f6b86e35505aa86c2188ebf41de9fce7 | vedk21/python-playground | /Intermediate/OOP/Inheritance/inheritance.py | 767 | 3.828125 | 4 | # Inheritance (parent - child classes)
class Car:
def drive(self):
print('driving a car')
class Mustang(Car):
def __init__(self, color):
self.color = color
def boost(self):
print('driving a car with boost')
class Camry(Car):
def __init__(self, color):
self.color = color
def navigation(sel... |
674c75a565efdf149d612db8fead1899d1e5336e | vedk21/python-playground | /Intermediate/OOP/Abstraction/abstraction.py | 710 | 4.1875 | 4 | # Abstraction (hiding the details of operation but availabling the interface open)
class Car:
def __init__(self, name, color, year):
self.name = name
self.color = color
self._year = year # _ represents it understood as private member
def drive(self):
print('driving {self.name} a car of color {self... |
ace401f39e8d5314a6a84234825eca852056d6ca | vedk21/python-playground | /Basic/functions/args_kwargs.py | 385 | 4.03125 | 4 | # multiple arguments and key-word arguments
def display_param(*args, **kwargs):
print(args) # it is a tuple of arguments
print(kwargs) # it is a dictionary of key-word arguments
display_param(1, 2, 3, 4, name = 'simon', age = 34)
# (1, 2, 3, 4)
# {'name': 'simon', 'age': 34}
# We can name those *args and **kwarg... |
8c46eec0e9ae2e09bee8b9fddd77c75a61fa0a99 | vedk21/python-playground | /Basic/data_types/lists.py | 2,771 | 3.984375 | 4 | # List type
l1 = [1, 2, 3, 4, 5, 6] # homogenous list
l2 = [1, 'str1', True, [2, 4, 'str2']] # heterogenous list
# Lists are mutable in nature
l1[2] = 10
print(l1) # [1, 2, 10, 4, 5, 6]
l2[1] = [4, 5, True]
print(l2) # [1, [4, 5, True], True, [2, 4, 'str2']]
# List slicing
l3 = [4, 5, 'str3', True, False]
l4 = l3[1:... |
8a7bdf1dc835dacf98eac0ec0c9c9dac27e70241 | vedk21/python-playground | /Basic/data_types/string.py | 955 | 3.765625 | 4 | # string type
st1 = "double quotes string"
st2 = 'single quotes string'
st3 = '''Multi
line string
'''
# string concatenation
print('first' + 'second') # 'firstsecond'
# type conversion
st4 = str(400) # '400'
# Escape characters
st5 = "I am writing double quote \" inside string" # 'I am writing double quote " inside ... |
f460cb46d83ecfb11eb589b67bbe6d4c257477e8 | vedk21/python-playground | /Intermediate/FunctionalProgramming/lambda_functions.py | 226 | 3.875 | 4 | # Lambda functions
from functools import reduce
# map using lambda functions
list1 = [1, 2, 3]
print(list(map(lambda item: item*2, list1))) # [2, 4, 6]
# reduce list
print(reduce(lambda acc, item: acc + item, list1, 0)) # 6
|
1e1288f39725fc77ec18081925f2df5d9bd4195b | vedk21/python-playground | /Intermediate/ErrorHandling/finally.py | 490 | 3.890625 | 4 | # Finally block
def calculate():
while True:
try:
age = int(input('Please enter your age: '))
100/age
except ValueError:
print('Please enter valid number')
except ZeroDivisionError:
print('Please enter positive number greater than zero')
else:
print('Thank you')
br... |
688c86d008a97e8e8e095e95c483b4d0a09563e6 | vedk21/python-playground | /Intermediate/OOP/methods.py | 877 | 3.859375 | 4 | # methods for class
class Car:
total = 0
def __init__(self, name = 'no_name', year = 'very_old', color = 'black'):
self.name = name
self.year = year
self.color = color
# increment total car count
Car.total += 1
@classmethod
def get_special_car_model(cls, color):
return cls('Special Sp... |
eaad49fd58a4ea79b2fac6af762de15df02a1725 | FlorianLehmann/programmation_fine | /sort/heapsort.py | 732 | 3.859375 | 4 | def parent(i):
return (i - 1) // 2
def left_child(i):
return 2 * i + 1
def right_child(i):
return 2 * i + 2
def heapify(lst):
start = parent(len(lst) - 1)
while start >= 0:
sift_down(lst, start, len(lst) - 1)
start -= 1
def sift_down(lst, start, end):
root = start
while left_child(root) <= end:
chi... |
6b4cb477095368545264b23a111da067824ed34c | FlorianLehmann/programmation_fine | /test/sort_test.py | 2,295 | 3.75 | 4 | import unittest
from generator import *
from sort import *
from sort.quicksort import pivot_functions, quick_sort
class SortTest(unittest.TestCase):
def test_should_sort_reverse_array(self):
numbers = [9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
expected = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
for algorithm ... |
2a418e7efe5e248cb112d21c28ae069fa3004af0 | takagotch/py1 | /PythonM_examples/examples/01/1.4.2-matplotlib_sample.py | 787 | 3.84375 | 4 | #各方程式を設定するためにNumPyをインポート
import numpy as np
# matplotlibのpyplotをpltでインポート
import matplotlib.pyplot as plt
# x軸の領域と精度を設定し、x値を用意
x = np.arange(-3, 3, 0.1)
#各方程式のy値を用意
y_sin = np.sin(x)
x_rand = np.random.rand(100) * 6 - 3
y_rand = np.random.rand(100) * 6 - 3
# figureオブジェクトを作成
plt.figure()
# 1つのグラフで表示する設定
plt.subplot(... |
600bb9211d37dbb4fc55b2f94a452faa77c72fbb | zoraj/coding_exercises | /sorting/quicksort.py | 2,374 | 4.09375 | 4 | # in place
def quicksort(l):
def quicksort_helper(l, first, last):
if first < last:
pivot = sort_and_return_partition(l, first, last)
# print l
# pivot is in place, so don't need to touch it anymore
quicksort_helper(l, first, pivot-1)
quicksort_he... |
2a9d1a7354fa5497afbba7a548d74b110a42f548 | RicardoG06/Camino-Machine-Learning | /Introduccion Pensamiento Computacional Python/Enumeracion_RaizCuadradaDeUnNumero.py | 391 | 3.734375 | 4 | from time import time
objetivo = int(input('Escoge un entero: '))
respuesta = 0
tiempo_inicial = time()
while respuesta**2 < objetivo:
print(respuesta)
respuesta += 1
if respuesta**2 == objetivo:16
print(f'La raiz cuadrada de {objetivo} es {respuesta}')
else:
print(f'{objetivo} no tiene una raiz exac... |
4d7a4ef60caafe1a88d80d7ec46df6d2a7eebae8 | tdodrtse/td2 | /tests.py | 485 | 3.75 | 4 | import unittest
from addition import *
class Tests(unittest.TestCase):
def test_int(self):
a=addition(1,1)
self.assertEqual(a,2)
def test_float(self):
a=addition(3.14,1.86)
self.assertEqual(a,5)
def test_str(self):
a=addition("at","choum")
self.assertEqu... |
a41a88a37887300d3191319eb0f256f1edeb1029 | abhisheklalnediya/ml-sentence-sentiment | /word_sentiment_finder.py | 1,182 | 3.921875 | 4 | # get data from file
file = open("data/movie_reviews.txt", "r")
data = file.read()
file.close()
# cut apart each review into a list
allreviews = data.split("\n")
# set up dictionary to hold ALL words and point values
sentiment = {}
for review in allreviews:
if(not len(review)): continue # some ... |
65a29be2c9343d0c380cb9b56db3d7aaaf45ff6e | MarciaAndrea/Marcia_lp22017vacation | /Marcia_python/exemplo_condicionais.py.py | 346 | 4 | 4 | idade = int(input("Informe uma idade maior que zero e menor que 120: "))
print(idade, "anos")
if idade >= 1 and idade <= 11:
print("Criança")
elif idade > 11 and idade <= 19:
print("Adolescente")
elif idade > 19 and idade <= 59:
print("Adulto")
elif idade > 59 and idade < 120:
print("Idoso")
else:
print(... |
5e15c5b362d3d6e47ee4da080aedd0cc046f13fa | lozhkinandrei/python-data-structures-algorithms | /tests/data_structures/test_tree.py | 1,644 | 3.703125 | 4 | import unittest
from data_structures.non_linear.tree import Node
class TestTreeMethods(unittest.TestCase):
def setUp(self):
self.tree = Node(1)
def test_insert_left(self):
self.tree.insert_left(2)
self.assertEqual(self.tree.left.key, 2)
self.tree.insert_left(3)
self.a... |
04d9b40838e43aeba0193553dbc35c03b15e4648 | lozhkinandrei/python-data-structures-algorithms | /tests/data_structures/test_queue.py | 1,108 | 3.796875 | 4 | import unittest
from data_structures.linear.queue import Queue
class TestQueueMethods(unittest.TestCase):
def setUp(self):
self.queue = Queue()
def test_enqueue(self):
self.queue.items = [2, 1]
self.queue.enqueue(3)
self.assertEqual(self.queue.items, [3, 2, 1])
def test_... |
5883ea786ca1d320a27f8115cb87501cb46b3274 | SatvikJayalwal/Apni_dictionary | /Apni_dictionary.py | 209 | 3.984375 | 4 | import os; os.system("cls")
dicty={"eagerly":"Exited","longings":"desire","Delightful":"lovely","pious":"Religious"}
inp=input("Enter the word to be searched : ")
print("The meaning of ",inp,":",dicty[inp])
|
104cc6f2a2c4044a905c748603f3998535f84b0f | taylorak/python-demo | /03-if-statement/if_statement.py | 767 | 4.1875 | 4 | '''
Working with if-then statements
'''
def if_else(correct):
"Checks if correct is true or not"
if correct:
print("true statement")
else:
print("false statement")
if_else(True)
if_else(False)
def check_nums(num1, num2):
'''
Checks which number is greater
'''
if num1 > n... |
3537e40b091533bfd9b801e150eed32a4065393d | Wenqi-Wu/BLB | /blb.py | 1,700 | 3.640625 | 4 | """Main class representing the BLB algorithm.
"""
import random
class BLB:
def __init__(self, num_subsamples=100, num_bootstraps=25,
subsample_len_exp=0.5):
self.num_subsamples = num_subsamples
self.num_bootstraps = num_bootstraps
self.subsample_len_exp = subsample_len_e... |
f325e2ecd71b06b20c57d57bcf31148c0d76cadf | joamho-luiz/notas-python | /cohdigo/aula07.py | 782 | 4.1875 | 4 | # DESAFIO 005
"""n1 = int(input('Digite um número inteiro: '))
print('Antes do {} temos {} e depois o {}.'.format(n1, n1-1, n1+1))"""
# DESAFIO 006
"""n2 = int(input('Digite um número inteiro: '))
print('{} elevado ao quadrado é: {}.'.format(n2, n2**2))
print('{} elevado ao cubo é: {}.'.format(n2, n2**3))
print('A rai... |
ec31d8792cb5ebf6b8970ef9a323691c11ef6e45 | mauriciogirardi/curso_python_3 | /python_do_zero/formatacao_string.py | 655 | 3.6875 | 4 | name = 'Mauricio Girardi'
age = 33
height = 1.70
"""
%d - Número inteiro
%f - Número fracionário
%s - String
'Meu nome é {}'.format(Maurcio)
"""
print('========== format ===========')
print('Meu nome é {} tenho {} anos e {:.2f} de altura'.format(name, age, height))
print(' ')
print('========== ... |
2e1e275dd7191f8b18fe73af0a8d7cde49c95289 | gaurangalat/SI506 | /Gaurang_DYU2.py | 1,163 | 4.3125 | 4 | #Week 2 Demonstrate your understanding
print "Do you want a demo of this week's DYU?\nA. Yes B. Not again\n"
inp = raw_input("Please enter your option: ") #Take input from user
if (inp =="B" or inp =="b"):
print "Oh well nevermind"
elif(inp == "A" or inp =="a"): #Check Option
print "\nHere are a few comic... |
8db034fea3cc39b02329ea5246f5a526caa3f88d | Ktulu1/Learning_Python3_The_Hard_Way | /ex20-1.py | 1,555 | 4.15625 | 4 | # import argv from library sys
from sys import argv
# setup variables for argv
script, input_file = argv
# define a function that prints the entire contents of the file
def print_all(f):
print(f.read())
# define a function that seeks to the begining of the file
def rewind(f):
f.seek(0)
# define a fuction th... |
9f04f14496b13a8a9b851f6758bf9b0dfb62c46a | Ktulu1/Learning_Python3_The_Hard_Way | /ex16.py | 1,209 | 4.28125 | 4 | # load argv from the sys library
from sys import argv
# define variables for argv
script, filename = argv
# echo some text with a varaible in it
print(f"We're going to erase {filename}.")
print("If you don't want that, hit CTRL-C (^C).")
print("If you want that, hit RETURN.")
# set the prompt
input("?")
# echo some... |
875a048dfc70c454833d06917579a7a5d8d7f674 | onekooo/6star1 | /练习/面向对象.py | 1,225 | 3.953125 | 4 | class Animal:
def __init__(self,name,age):
self.name = name
self.age = age
def eat(self):
print('{}在吃饭'.format(self))
def sleep(self):
print('{}在睡觉'.format(self))
def play(self):
print('{}在玩'.format(self))
class Persion(Animal):
def __init__(self,name,pets,... |
b2a99c57c07e9fe99781b8ccabde25d472946ad4 | onekooo/6star1 | /python_panda数据分析100/009创建一个dataframe.py | 223 | 3.5625 | 4 | import pandas as pd
#加载字典创建dataframe
df = pd.DataFrame(
{
"姓名":['张三','李四','王五','赵六'],
"性别":['男','女','男','女'],
"年龄":[18,19,20,21]
}
)
print(df) |
3f346a34f6783f8e0ce8c8ce41aca61c4c2992dd | onekooo/6star1 | /6star/week2/登陆.py | 222 | 3.640625 | 4 | name = 'maiya'
passwd = '123'
username = input('请输入用户名:')
password = input('请输入密码:')
if name == username.strip() and passwd == password:
print('登陆成功')
else:
print('登陆失败')
|
d3ac00a1ce993a103268ee14168793bfc64e5b53 | onekooo/6star1 | /python_panda数据分析100/002字典构造Series.py | 248 | 3.875 | 4 | '''
使用pandas
把字典转成Series对象
并输入到命令后
'''
import pandas as pd
# courses =["语文","数学","英语","计算机"]
grades={"语文":80,"数学":90,"英文":85,"计算机":100}
data = pd.Series(data = grades)
print(data) |
965edc6dd6bc2f7dede5092710a5e595a20dd231 | Mtowncoder/HomeConnect-Simulator | /functions.py | 786 | 3.640625 | 4 | import csv
import requests
import sys
import homeconnectapi
def name():
file = open("Appliance.csv", "a")
number = input("Date: ")
writer = csv.writer(file)
writer.writerow((name, number))
file.close()
return
def yorn():
ans = input("yes or no? ")
if ans != "yes":
sys.exit("re-enter") # re... |
5bd0098ccd782e0e872fcaf3e376bc32f764c553 | kafkaesc/cs373 | /examples/Functions.py | 3,403 | 3.515625 | 4 | #!/usr/bin/env python3
# ------------
# Functions.py
# ------------
import functools
import types
print("Functions.py")
def plus_1 (x, y) :
return x + y
def mult_1 (x, y) :
return x * y
assert type(plus_1) is types.FunctionType
assert type(mult_1) is types.FunctionType
assert hasattr(plus_1, "__call__")
... |
5932e1aaf1044bec593e2685693e313e4e4cfaad | B70-Yugal/python-lab | /pattern4.py | 244 | 3.703125 | 4 | '''
****
***
**
*
'''
n=eval(input('enter number of rows'))
for i in range(1,n+1):
print((n+1-i)*'*')
'''
****
***
**
*
'''
m=eval(input('enter number of rows'))
for i in range(1,m+1):
print((i-1)*' '+(m+1-i)*'*') |
0a96c8d20d9b856090af3c463828c30b471944b1 | jjenner689/Python | /algorithms_and_data_structure_questions/recursion_questions.py | 1,658 | 4 | 4 | # Write a recursive algorithm that goes into a nested hash structure and sums all key, value pairs - where the value is not a hash
test_hash = {1:2,3:{4:5}}
def sum_hash(hash_):
sum_ = 0
for i in hash_:
if type(hash_[i]) != type({}):
sum_ += i + hash_[i]
else:
sum_ += i +sum_hash(hash_[i])
return sum_
r... |
829d6bcfdd128252b10c5d02d6c8e4c6790dbd51 | jjenner689/Python | /json_weather_api/get_min_max_for_city.py | 3,105 | 4.59375 | 5 | '''
Open Weather Api is a json weather api to get weather data for most major cities.
In this exercise we are going to populate a small local database with all the min and max temperatures for last 16 days for a city.
We will use a json api to get the data, then store parts of that data in sqlite, which is small sql... |
af147d76ce3500f8d144f3a70f2081f16769c9dd | hiyuricu/NLTK | /1/1_23.py | 149 | 3.609375 | 4 | #!/usr/bin/python
# -*- coding: utf-8 -*-
import sys
import string
from nltk.book import text6
for w in text6:
if w.isupper():
print w
|
91e897c640fec0bb51c3a568d8c72abaa4cdfa81 | shrivastava-himanshu/Leetcode_practice | /findComplement.py | 395 | 3.71875 | 4 | def findComplement(num):
res = []
ori = []
out = 0
while num > 0:
rem = num % 2
#print(rem)
num = num // 2
ori.append(rem)
if rem == 0:
res.append(1)
else:
res.append(0)
print(ori[::-1])
print(res[::-1])
for i in range(l... |
97c6e3c57af4951e4df40ab2e8df1bb4b4ea2647 | shrivastava-himanshu/Leetcode_practice | /ClimbingStairs.py | 134 | 3.734375 | 4 | def climbStairs(n):
#fibonacci
x,y = 1,1
for i in range(2,n+1):
x,y = y, x+y
return y
print(climbStairs(30)) |
83a40b4361268233dbfd4be23d6daf622a1d44e4 | shrivastava-himanshu/Leetcode_practice | /number_of_1_bits.py | 168 | 3.9375 | 4 | def hammingWeight(n:int) -> int :
c = 0
while n != 0:
c += n % 2
n = n // 2
return c
print(hammingWeight(00000000000000000000000000001011)) |
80cf96a905b177e4a87fce7ed2cc321678671fcb | shrivastava-himanshu/Leetcode_practice | /Add_digits.py | 436 | 3.796875 | 4 | def add_digits(num: int):
sum = 0
if num < 10:
return(num)
else:
for i in str(num):
sum += int(i)
return(add_digits(sum))
# return sum
'''
Method # 2 :
def add_digits(num: int):
sum = 0
for i in str(num):
sum += int(i)
if sum < 10:
return(... |
f8ff9a3190b6da70543c2bf6caa202250c6e9080 | shrivastava-himanshu/Leetcode_practice | /MaxConsecutiveOnes.py | 668 | 3.546875 | 4 | """
def maxOnes(nums):
count,i = 0,0
max_count = 0
while i<len(nums):
if nums[i] == 1:
count +=1
elif nums[i] != 1:
count =0
if count > max_count:
max_count = count
i += 1
print(max_count)
maxOnes( [])
"""
"""
Clever solutions
Usi... |
5f6971736989c752154e8dc55fed6b803702fd3c | shrivastava-himanshu/Leetcode_practice | /wordPattern.py | 492 | 3.765625 | 4 | def WordPattern(pattern,s):
s_list = s.split()
my_set = set()
my_dict = {}
if len(pattern) != len(s_list): return False
for i in range(len(pattern)):
x = pattern[i]
y = s_list[i]
if x in my_dict:
if my_dict[x] != y:
return False
else:
... |
1eaff75f9a70606294df052482769dd5387ffe93 | frankligy/exercise_codes | /machineLearning/gridSearch.py | 3,628 | 3.5625 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Aug 14 12:11:31 2020
@author: ligk2e
"""
from sklearn.datasets import load_iris
from sklearn.neighbors import KNeighborsClassifier
from sklearn.model_selection import cross_val_score
import matplotlib.pyplot as plt
### Normal cross validation and use... |
e72dd13bcddea385e7c3dfa6707a48661c720fec | mfehrenb/refactor_challenge_python | /src/code.py | 3,055 | 3.625 | 4 | from enum import Enum
class Package:
def __init__(self):
self.pieces = []
self.count = 0
def add_piece(self, text):
self.pieces.append(f"{self.count}: {text}")
self.count += 1
def remove_piece(self, pos):
del self.pieces[pos]
def __str__(self):
return... |
c08424ab10a927ae95a118596b0d5822170326a8 | shanmugaacharan/Mycaptaintask1.py | /task4.py | 239 | 3.875 | 4 | mylist1=[12,-7,5,64,-14]
mylist2=[12,14,-95,3]
print("mylist1 output:")
for ele in mylist1:
if ele >= 0:
print(ele, end=",")
print("\n")
print("mylist2 output:")
for ele in mylist2:
if ele >= 0:
print(ele, end=",")
|
68ad62719e9fe0a5e3500baab933e242dcf2b11f | TheCodingWizard-911/PythonMiniProject | /Assignments/Assignment_1/q1.py | 628 | 3.703125 | 4 | print("\nAt first the man takes the goat with him to the other side of the river leaving the tiger and grass behind with the grass and goat being protected.\n")
print("Then he comes back alone and takes the grass to the other side of the river, after that he takes the goat from the other bank with him to protect the g... |
bea8d2434937aba490d0a4d77a95bb613e9add05 | TheCodingWizard-911/PythonMiniProject | /Assignments/Assignment_3/shapes.py | 2,122 | 3.71875 | 4 | class Shapes:
def __init__(self):
self.dimensions = 1
def get_dimensions(self):
return self.dimensions
def set_dimensions(self, dim):
self.dimensions = dim
class Triangle(Shapes):
def edges(self):
print("\nTriangle has 3 edges")
def vertices(self):
... |
d596223634586066092563303a0916d6a327c9db | elirud/eitn41_adv_websec | /Assignments HA1/Assignment1/B1_Luhns.py | 1,286 | 3.578125 | 4 | with open("test.txt", "r") as f:
data = f.read().splitlines()
answer = []
for number in data:
print(number)
double_x = None
check_sum = 0
for character in number[-2::-2]:
if character == 'X':
double_x = True
continue
if int(character) * 2 < 10... |
0bfdb60a9dec120d82829d5286bdaaf565609d98 | unaj-fundamentos/felipe-morales-parciales-resueltos | /2020-com16-R1.py | 4,423 | 3.96875 | 4 | # ¡SE RECOMIENDA LEER EL EXAMEN COMPLETO Y LUEGO ELABORAR UNA ESTRATEGIA PARA SU RESOLUCIÓN!
# 1) Programar en Python (20 puntos):
print("Ejercicio 1a")
# a) Pedir el ingreso de los 4 números de una tarjeta de débito y/o de crédito e imprimir dicha información
# con el siguiente formato: **** **** **** 9999 (9999 r... |
fdaae9577fa0821a143ca185cc1019d03bcf5202 | Nathnos/probabilistic_battleships | /game/board_setup.py | 1,920 | 4.1875 | 4 | """
Main game functions
"""
import numpy as np
from game.game_tools import (
get_direction,
get_boat_size,
get_random_direction,
get_random_position,
)
def can_place(grid, boat, position, direction):
"""
grid : numpy array
boats : represented by an integer
position : tuple (x, y)
... |
5677ce2d3b8f9d0a4ccd7810aac8c59c47e5c8cb | arnab-arnab/Python-Course | /06.Chapter 6/Question 3.py | 351 | 3.921875 | 4 | comment=input("Enter the text\n")
if("make a lot of money" in comment):
spam= True
elif("buy now" in comment):
spam= True
elif("click this" in comment):
spam= True
elif("subscribe this" in comment):
spam= True
else:
spam= False
if(spam is True):
print("This text is spam")
else:
... |
9c6bc83c9fadeb891e5e0ae49868bfc04449d224 | arnab-arnab/Python-Course | /08.Chapter 8/Question 2.py | 171 | 3.859375 | 4 | def c_to_f(temp):
x=(9*temp+160)/5
return x
taapman=int(input("Enter temperature in celsius:\n"))
y=c_to_f(taapman)
print("Temperatuer in fahrenheit scale is:",y) |
221c0daa1d412fc285fd01b8386202029931e2d0 | arnab-arnab/Python-Course | /06.Chapter 6/Question 4.py | 211 | 4.15625 | 4 | text=input("Enter the text:\n")
a=len(text)
print("Length is:",a)
if(a<10):
print("The length is less than 10")
if(a>10):
print("The length is greater than 10")
if(a is 10):
print("The length is 10") |
909ad248874f4f381d0c8dd1a3f01759c9b29a58 | arnab-arnab/Python-Course | /10.Chapter 10/06_Static Method.py | 444 | 3.65625 | 4 | class Employee:
company="Google"
def getSalary(self):
print(f"Salary of employee working in {self.company} is {self.salary}")
@staticmethod
def greet(): # Here we do not need to use self as we are using static method
print("Good morning sir")
@staticmethod
def time():
... |
f1e5cca8210d307dbe84e01717b19d11ee7298f9 | arnab-arnab/Python-Course | /04.Chapter 4/Question_3.py | 403 | 4.25 | 4 | print("Enter three elements to be stored in tuple")
a1=input("Enter the 1st element: ")
a2=input("Enter the 2nd element: ")
a3=input("Enter the 3rd element: ")
tupl=(a1,a2,a3)
print(tupl)
print("Which of the element of the tuple would you try to change\n")
print("0\t1\t2\n")
a4=input("Enter the index value from th... |
f8e073b9d700379a53ffad32708d8a7103c4b137 | arnab-arnab/Python-Course | /10.Chapter 10/07_Constructor.py | 748 | 3.8125 | 4 | class Employee:
company="Google"
def __init__(self,name,salary,subunit): #<-- Constructor
print("Employee is created")
self.name=name
self.salary=salary
self.subunit=subunit
def EmployeeDetails(self):
print(self.name)
print(self.salary)
print(self.s... |
c060c670f2494566f64d0f358c0f35d144d2ad36 | arnab-arnab/Python-Course | /07.Chapter 7/Question 6.py | 118 | 4.21875 | 4 | num=int(input("Enter the number :\n"))
c=1
for i in range(1,num+1):
c*=i
print("The factorial of the number is",c) |
6002071aa47b871e3cfb4121562fcc334392ebf3 | arnab-arnab/Python-Course | /05.Chapter 5/02_Dictionary_Methods.py | 1,239 | 4.375 | 4 | myDict={
"Fast":"In a quick manner",
"Arnab":"A coder",
"Marks":[1,2,5],
"Li":(3,44,6),
"Number": 5,
"anotherDict":{"Devesh":"Doggy",
"Sneha":"Bitch",
"Deborshi":"Cow",
"Sex_Position":69
}
}
# DICTIONARY METHODS
pri... |
6c0b01f2cf2ccc45ad959cbbe9311df8df83b255 | arnab-arnab/Python-Course | /04.Chapter 4/Question_2.py | 295 | 3.9375 | 4 | m1=input("Enter marks of student 1 :")
m2=input("Enter marks of student 2 :")
m3=input("Enter marks of student 3 :")
m4=input("Enter marks of student 4 :")
m5=input("Enter marks of student 5 :")
m6=input("Enter marks of student 6 :")
m_list=[m1,m2,m3,m4,m5,m6]
m_list.sort()
print(m_list) |
c0b244a93875fcbef00a01dc2cc2ddd17c8b33e3 | arnab-arnab/Python-Course | /05.Chapter 5/Question_2.py | 189 | 3.71875 | 4 | print("Enter 8 numbers")
a1=input()
a2=input()
a3=input()
a4=input()
a5=input()
a6=input()
a7=input()
a8=input()
b=set()
b={a1,a2,a3,a4,a5,a6,a7,a8}
print("The unique numbers are")
print(b) |
ac4c5923a1c5b7069a0b142f01f1261b91f9fe1a | arnab-arnab/Python-Course | /10.Chapter 10/04_Attributes.py | 335 | 3.96875 | 4 | class employee:
company="google"
salary=100
harry=employee()
rajni=employee()
# harry.salary=300
# rajni.salary=400
print(harry.salary)
# <--- Both will print 100 since no instance attribute is given the class attribute will be considered
print(rajni.salary)
# Instance attribute gets the ... |
7edb376678fb9e3a64e821b0f5fee8beab517875 | arnab-arnab/Python-Course | /08.Chapter 8/03_factorial.recursion.py | 585 | 4.375 | 4 | '''
fact=int(input("Enter the number till which you need factorial:\n"))
product=1
for i in range(1,fact+1):
product=product*i
print(product)
*****************************A NORMAL FACTORIAL PROGRAM ABOVE*********************************
'''
def fact_recr(n):
if(n is 1 or n is 0):
return 1
return n... |
0d77c0bb3f382fe342c3b56a1e5796d19a0df5cd | arnab-arnab/Python-Course | /YOUTHOOB/yt.practice4.py | 534 | 3.765625 | 4 | # **********MULTIPLE INHERITANCE********* #
class a1:
def assign_value_1(self,a):
self.a=a
def show_value_1(self):
print(self.a)
class b1:
def assign_value_2(self,b):
self.b=b
def show_value_2(self):
print(self.b)
class derieved(a1,b1):
def assign_value_3(self,c... |
60dec9f55d8e0110c5dcd26e324cc4729cd3b7fe | CarlosDLA26/PythonScripts | /password_generator.py | 375 | 3.59375 | 4 | # Password generator with Python
import random
def password_generator(size=10):
password = []
characters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789{}[]/!#$~%&()=?¿¡+*"
for i in range(size):
password.append(random.choice(characters))
return "".join(password)
def main():
print(passw... |
85eb5b9984baeb1b2085980d2b2b2f7e6d6c9da0 | lukasz-komorowski/magisterka | /Kod/reading_data.py | 801 | 3.96875 | 4 | from pandas import read_csv
def get_all_from_csv(fileName):
# get columns with names from csv
# Data Kurs
# 0 2002-01-02 2.3915
# 1 2002-01-03 2.4034
# 2 2002-01-04 2.3895
# 3 2002-01-07 2.3726
# 4 2002-01-08 2.3813
return read_csv(fileName, parse_dates=[0])
def get_d... |
874a8cafb5b2142e5c11c91cf5014dc27abdcd07 | JacobDowns/filterpy | /filterpy/kalman/tut/tut_util.py | 1,004 | 3.515625 | 4 | import numpy as np
from itertools import combinations, product
from scipy.misc import comb
def generate_fully_symmetric_set(n, vals):
"""
Generates a fully set of symmetric points of dimension n with
values given in vals.
Parameters
----------
n: int
Dimension of points in fully sy... |
604c039aaa2d0d3891eb81409a6fafecb0d64db3 | nabdelgu/Practice-Programs | /python programs/DrawShapes/src/DrawShapes/CircleSquare.py | 789 | 3.921875 | 4 | import turtle
__author__="Noah Abdelguerfi"
__date__ ="$Dec 27, 2014 10:57:10 PM$"
"""
# method draws a square incriments heading
# continues until it reaches 360 degrees
"""
def draw_circle_with_squares():
degrees = 0
squareCircle = turtle.Turtle()
squareCircle.shape("turtle")
squareCircle.colo... |
acb8fa4480965f9d09b7252001c391439450150b | sreeramch/Learn-Python | /first.py | 340 | 4 | 4 | # First python example using python 3.8
# Note that the print has the python 3 format with "()"
#
# Example shows how to invoke the main function.
# Also prints the current python version using the sys library.
import sys
def main():
print("Hello World!")
print("Python version: %s" % sys.version)
if __name__ == "... |
6a840719843ca064ff4e9e57548388335bd25691 | hypergravity/cham_hates_python | /monte_carlo_pi.py | 1,103 | 3.53125 | 4 | # -*- coding: utf-8 -*-
"""
Spyder Editor
This is a temporary script file.
"""
import sys
#import pdb
import numpy as np
def monte_carlo_pi_single_point():
""" this function does this
Parameter
---------
?
"""
# generate random X, Y pair
x = np.random.uniform(-1.0, 1.0)
y = np.r... |
096b2ac895517c118ecfc762ca779ffe80a1ddcf | saaalik/KBC-Quiz-Tkinter | /main.py | 104,107 | 3.921875 | 4 | from tkinter import * #To use python GUI tkinter module is to be used
from PIL import ImageTk,Image #To put images on the screen
import tkinter.font as f #To style and resize font of the text in program
from datetime import date #To calculate the current date and time of when the game wa... |
f7ed51b9039ee4b5488431c519be8027e383b5e6 | markkampstra/examples | /Python/fizzbuzz.py | 1,620 | 4.25 | 4 | #!/usr/bin/python
# FizzBuzz by Mark Kampstra
#
# Write a program that prints the numbers from 1 to 100.
# But for multiples of 3 print "Fizz" instead of the number and for the multiples of five print "Buzz".
# For numbers which are multiple of both 3 and 5, print "FizzBuzz".
#
import string
class FizzBuzz:
'''The... |
98498e16d760c1f50f90b53184b90da244195871 | ManuelLobo/random_stuff | /ML/neural.py | 2,455 | 3.828125 | 4 | import numpy as np
def simple_neural():
def relu(z):
return max(0, z)
def feed_forward(x, hidden_weights, output_weights):
# Hidden Layer
Zh = x * hidden_weights
H = relu(Zh)
# Ouput Layer
Zo = H * output_weights
output = relu(Zo)
print(output)... |
a46fce543c096ace1a26c1967476bb77886f3fe8 | ManuelLobo/random_stuff | /flask/helper_db.py | 1,154 | 3.546875 | 4 | import csv
def prepare_data(input_file):
users = []
with open(input_file) as infile:
reader = csv.reader(infile)
for line in reader:
first_name = line[1]
last_name = line[2]
users.append((first_name, last_name))
return users
def insert_user(first_name,... |
c5171153f4d24f7f9a32fda70b0c3a80e640b0aa | ManuelLobo/random_stuff | /deep_learning/tensorflow_classification_exercise.py | 3,212 | 3.53125 | 4 | import pandas as pd
import tensorflow as tf
from sklearn.model_selection import train_test_split
census = pd.read_csv("census.csv")
# String labels need to be converted to 0 and 1. pandas has the funcion apply()
# which converts the strings.
# the label is "income_bracket"
print(census["income_bracket"].unique()) ... |
c9d0fa94e5fc5f0092636a94fc163d93b7e02ec0 | WBLACKB/leasson_1 | /w5.py | 1,575 | 3.75 | 4 | # Запросите у пользователя значения выручки и издержек фирмы. Определите, с каким финансовым результатом работает фирма (прибыль — выручка больше издержек, или убыток — издержки больше выручки). Выведите соответствующее сообщение. Если фирма отработала с прибылью, вычислите рентабельность выручки (соотношение прибыли к... |
44ca6afe742c3717cbaed22ec5728836b47e63e3 | jamiec-0123/pythonRelearnt | /cake.py | 547 | 3.640625 | 4 | class cake():
def __init__(self, layers, event, flavour):
self.layers=layers
self.event=event
self.flavour=flavour
inputLayers = input("How many layers would you like for your cake \n")
inputEvent = input("What event will this cake be made for \n")
inputCake = input("What flavour of cake? \... |
de5ebc9da1aadaddaa5088c43ad722eaba793890 | krnirmal2/Wood-working-images | /imagebazar/view.py | 1,522 | 3.546875 | 4 | """ below the function use for handling the request from the user can get to view http response """
from django.shortcuts import render
from django.http import HttpResponse
from myapp.models import *
def show_about_page(request):
print("about page request ")
name='learncode with NIRMAL '
link='https://www... |
ea3cd26f2804b5ac8850ea448d8dcb23f9e1cca9 | dbozic/useful-functions-exploration | /column_unique_values.py | 1,252 | 4.71875 | 5 | def column_unique_values(data, exclusions):
"""
This function goes through each column of a dataframe
and prints how many unique values are in that column.
It will also show what those unique values are. The
function is particularly useful in exploratory data
analysis for quick understandi... |
2a6c0cde8cb09990a3b053fb84b81d841fa13f24 | omilggr/WorldOfGames | /MainGame.py | 294 | 3.578125 | 4 | # start World of the game
from Live import load_game, welcome
# get user's name and print welcome message by using welcome function
print("welcome to the game")
name = str(input('Insert your name, please: '))
welcome(name)
# load and execute the game according to user selection
load_game()
|
0035555e3ba24abed816d3d3d16693a276867d2a | shiv97/python_w3 | /Date&Time/leapyr/leapyr.py | 227 | 3.90625 | 4 | def leap_year(yr):
if yr % 400 == 0:
print('leap yr')
if yr % 100 == 0:
print('not a leap yr')
if yr % 4 == 0:
print('leap yr')
else:
print('not a leap yr')
print(leap_year(1998)) |
6a8e7ee3500ec17d5328b99e520143cd313134f2 | shiv97/python_w3 | /bp1/Nprint/Nprint.py | 136 | 3.90625 | 4 |
num=int(input('enter number'))
sum=0
for i in range(1,num):
j=i;
while(j<num):
print(num)
j=j+1
print("+")
|
4b6c06be98f7c0492cbb3c7b9d353029536b9e19 | shiv97/python_w3 | /Math/DegRad/DegRad.py | 87 | 3.921875 | 4 | pi=22/7
radian = float(input("entr radians: "))
degree = radian*(180/pi)
print(degree)
|
60ec90b10021a8d417099ab707904400494aa231 | shiv97/python_w3 | /Math/RadDeg/RadDeg.py | 86 | 3.8125 | 4 | pi=22/7
degree = float(input("entr degrees: "))
radian = degree*(pi/180)
print(radian) |
7ee870ae5ed8111967c921a06eea16557f82afbd | noozip2241993/basic-2-python | /task18.py | 148 | 4.15625 | 4 | numbers = [1,424,234,123,1,23]
def enumerating(list):
for index,value in enumerate(list):
print(f'{index}:{value}')
enumerating(numbers) |
a7124b6977f27f5a805e9e53da8e868c7ab133ef | rbartosinski/Flask-Little-Things | /exponentiation.py | 1,019 | 3.515625 | 4 | from flask import Flask
from flask import request
app = Flask(__name__)
@app.route('/', methods=['GET', 'POST'])
def tabela():
if request.method == "POST":
n = int(request.form["licz"])
return """
<table>
<tr>
<th>2 do potęgi n</th>
<td>{}</td>
</tr>
<tr>
... |
20c18b03bf97bb5e6df93b2ecbeb6a12964044b0 | JustParsa/RSA_Encryption | /src/gnt_prime.py | 2,554 | 3.65625 | 4 | #Currently Compatible with Python version 3.X
import random
import sys
import math
def is_probable_prime(n, k = 7):
#use Rabin-Miller algorithm to return True (n is probably prime) or False (n is definitely composite)
if n < 6: # assuming n >= 0 in all cases... shortcut small cases here
return [False,... |
ae172af54bc2698ce83bedd94416e22847593e60 | QkqBeer/PythonSubject | /面试练习/29.py | 1,205 | 4.1875 | 4 | # __author__ = "那位先生Beer"
#
#
# def divide( dividend, divisor ):
# """
# :type dividend: int
# :type divisor: int
# :rtype: int
# """
# flag = 0
# dividendn = abs( dividend )
# divisorn = abs( divisor )
# while dividendn > 0:
# if dividendn >= divisorn:
# dividen... |
03045b5177d361694e50578863abcf111bfe7a22 | QkqBeer/PythonSubject | /算法/归并排序.py | 677 | 3.875 | 4 | __author__ = "那位先生Beer"
def mergesort( seq ):
if len( seq ) <= 1:
return seq
mid = int( len( seq ) / 2 )
left = mergesort( seq[:mid] )
right = mergesort( seq[mid:] )
return merge( left, right )
def merge( left, right ):
result = []
i, j = 0, 0
while i < len( left ) and j < le... |
50dfbb2e0c83edb13249e3a7a9d73509ad5f35a6 | QkqBeer/PythonSubject | /面试练习/704.py | 573 | 3.84375 | 4 | __author__ = "那位先生Beer"
def search( nums, target ):
"""
:type nums: List[int]
:type target: int
:rtype: int
"""
def Bsearch(nums, low, high):
if len(nums[low:high]) > 1:
mid = (low + high) // 2
if nums[mid] == target:
return mid
elif ... |
6f49be7723501a2616c5145ac2cc96c812519f4f | QkqBeer/PythonSubject | /training_camp/各类方法.py | 668 | 4.0625 | 4 | #静态方法
#属性方法
class P:
def __init__(self,name):
self.name=name
@property
def eat(self):
print("%s eat something %s"%(self.name,self.__food))
@eat.setter
def Eat(self,food):# 此名随意
print("set to food:" ,food)
self.__food=food
#call方法 __init__() 构造方法是由创建对象出发的,即:... |
5148851e587505c15aec38bbc729bc5c84438494 | QkqBeer/PythonSubject | /面试练习/443.py | 727 | 3.625 | 4 | __author__ = "那位先生Beer"
def compress(chars):
flag = 0
count = 1
if len(chars) == 1:
return 1
chars.append( 0 )
for i in range(1, len(chars)):
if chars[i - 1] == chars[i]:
count += 1
else:
if count > 1:
chars[flag] = chars[i - 1]
... |
801d4d6dad8294462a98a11536fcd52b3a33c767 | QkqBeer/PythonSubject | /算法/bank.py | 676 | 3.53125 | 4 | __author__="那位先生Beer"
def isSushu(num):
flag = True
for i in range( 2, num // 2 + 1 ):
if (num % i) == 0:
flag = False
break
return flag
def isTrue(i, num):
flag = 1
while i ** flag < num:
flag += 1
if i ** flag == num:
return True
else:
... |
4929b757e18489c96e6abc113b089cbd6ff21b66 | llyaas/Project-98 | /Project98.py | 745 | 3.921875 | 4 | # A = contents of file 1
# B = contents of file 2
# file1 = content of file A
# file2 = content of file B
# readLines
# open
# read
# write
# input
#function definition to swap data between 2 files
def swapFileData():
file1Path = input("enter file1 name/Path: ")
file2Path = input("enter file2 na... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.