blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
29eaddabb6d375e44c6e8c52410fcdbcf367e368 | BernardWong97/PythonExercise | /codeSnippet/Exercise.py | 491 | 4.25 | 4 | # print to terminal
print("this line will be printed")
# Data types (Every variable is an object)
# integer
myInt = 123
print(myInt)
# float
myFloat = 123.4
print(myFloat)
# string
myString = "Hello World!"
print(myString)
myString = 'Hello World!'
print(myString)
myString = "Don't worry about apostrophes"
print(myStr... |
7b075acdc70fdb01947523d538a9e11907cf476b | CapnFlint/TwitchBot101 | /05 - Basic Syntax/0-sample.py | 937 | 3.515625 | 4 | #!/usr/bin/env python27
'''
This is a multiline comment
'''
# These are imports
import logging
# Colon (:) signifies the start of a block!
def globalFunction(myVar):
# Some operators
message = "Hello " + myVar + "!"
# Built in function
# This works the same:
# print(message)
print message... |
8470bc0f181f1094fb60ccffd445a1177bd8d7ae | dileepkr/datastructures | /ds_queues/hotpotato.py | 410 | 3.640625 | 4 | from myqueue import Queue
def hotPotato(namelist, numrounds):
namequeue = Queue()
for name in namelist:
namequeue.enqueue(name)
while namequeue.size() > 1:
for i in range(numrounds):
namequeue.enqueue(namequeue.dequeue())
namequeue.dequeue()
return namequeu... |
a6e06759e894d7b9607175e1b84377b5f9255c35 | bmarkwalder/csc594 | /hw_01/text_pre_processing.py | 8,741 | 4 | 4 | """
Brandon Markwalder
CSC 594
Spring 2018
Homework 01 Text pre-processing
This program will tokenize a corpus such that words, leading and trailing
punctuation and expanded contractions are converted to tokens. Punctuation
found in the middle of a word is ignored. The program outputs the number of:
Sentences, paragra... |
10efa411f8afa23538978254632b70152cc7bc85 | xxEoD2242/reinforcement-learning | /multi-arm-bandits/bandit/__init__.py | 4,312 | 3.828125 | 4 | import numpy as np
class Bandit():
"""
Bandit reinforcement learning algorithm that takes actions based
upon precieved rewards. Generally, Gaussian distributions are
utilized.
Inputs:
- eps [double] Epsilon value. Strictly in [0,1].
- k [integer] Number of arms of bandit. Lo... |
a292e62cf0800473f7129b14afb58648ddfbd711 | arshiahemmat/Simple_Projects | /Professional_calculator.py | 10,958 | 4.09375 | 4 | from datetime import datetime
import math
class user:
def __init__(self, name):
self.name = name
def __str__(self):
now = datetime.now()
current_time = now.strftime("%H:%M:%S")
return 'name of user is : {} and the current time is : {}'.format(self.name, current_time... |
54ef3d0cb0b21785c1fef66f0dda6a9b75bef49d | sharma-adi0906/my-first-project | /Blocks.py | 208 | 4.09375 | 4 | Name = input("what is your name?")
age = int(input("how old are you, {0}?".format(Name)))
if age >= 18:
print("You are eligible to vote")
else:
print("come back in {} years to vote".format(18 - age)) |
2331832cf6bc5306d8e35ac9ab38aab242bdc656 | sharma-adi0906/my-first-project | /searching.py | 193 | 4.03125 | 4 | shopping_list = ["Milk", "eggs", "bread", "jam", "coffee"]
for items in shopping_list:
if items == "bread":
print ("bread needed")
break
print(items + " not needed")
|
78cd1f3f5cd709e90618c0bc2b063262029d908a | lucaslb767/InfnetATPythonRedes | /Q06_server.py | 1,257 | 3.84375 | 4 | '''
Escreva um programa cliente e servidor sobre TCP em Python em que:
O cliente envia para o servidor o nome de um diretório e recebe a lista de arquivos (apenas arquivos) existente nele.
O servidor recebe a requisição do cliente, captura o nome dos arquivos no diretório em questão e envia a resposta ao cliente de vol... |
da03b1660f7d4e824f51bffe198784d0682a8189 | AsmaAbdullah1998/Artificial-Intelligence-2020 | /MyFirstProjectOpenCV/Resize image.py | 861 | 4 | 4 | import cv2
print("Package Imported")
import numpy as np #when we want to call funtion we just write np.'the name of the funcion'
#To resize the image we need firs to know the current size of our image
#Write the path of our image
path = r'C:\Users\EngSa\OneDrive\Desktop\MyGithub\Path3\MyFirstProjectOpenCV\boy.jpg'
#... |
6d71db8ecef1c91d7ea256f2a64054ce3e342b24 | catsneedapps/lpthw | /ex3.py | 727 | 4.125 | 4 | print "I will now count my chickens:"
print "Hens", 25+30/6
print "Roosters", 100 - 25 * 3 % 4
print "Now I will count the eggs"
print 3.0000 + 2.0000 + 1.0000 - 5.0000 + 4.0000 % 2.0000 - 1.0000 / 4.0000 + 6.0000
print "Is it true that 3+2 < 5-7?"
print 3+2 < 5-7
print "What is 3+2?", 3+2
print "Wh... |
4c7003bfbed601a642dbdc22d3bd4662a9c1aed0 | leoEspin/trade-blotter | /calcStats.py | 3,408 | 3.5625 | 4 | #!/usr/bin/env python3
import argparse
def parcero():
huyparce = argparse.ArgumentParser()
huyparce.add_argument('-i', '--input', type=str,
metavar='input.csv', required=True)
huyparce.add_argument('-o', '--output', type=str,
metavar='output.csv')
r... |
ccef24597df070ea7df47b6e5b50c15e186b883d | D4TI3C/Rima-Rizky-Lestari-1144118 | /doc/tugas2.py | 1,401 | 3.609375 | 4 | graph = {
'Jln Bumi': ['Pasar Mayestik'],
'Pasar Mayestik': ['Jln Rs Pertamina'],
'Jln Rs Pertamina': ['Jln Pakubuwono'],
'Jln Pakubuwono': ['Jln Lauser'],
'Jln Lauser': ['Jln Kyai Maja'],
'Jln Kyai Maja': ['Jln Hasanudin Dalam'],
... |
b114f9533bf93ae8329c73e1a1e2ab4e31c48331 | mbcrocci/Scripts | /python/test_temp.py | 776 | 3.5 | 4 | #!/usr/bin/env python3
import unittest
import temp
class test_temp( unittest.TestCase):
cel = 100.00
fahr = 212.00
kel = 373.15
def test_celsius_fahr(self):
self.assertEqual(temp.cel_to_fahr(self.cel), self.fahr)
def test_celsius_kelvin(self):
self.assertEqual(temp.cel_to_kel(sel... |
e6c471c988e217e2ee388b342521430383b8a8ef | anirudhkannanvp/GeeksForGeeksSolutions | /count-of-strings-that-can-be-formed-using-a-b-and-c-under-given-constraints.py | 76 | 3.5 | 4 | for _ in range(int(input())):
n=int(input())
print((n*n*n+3*n+2)//2) |
04f7c83f16ac7457813f685adf75f0402b681cd6 | grafitosLeg/Kurs_Python_22122020 | /Choinka.py | 169 | 3.78125 | 4 | #Merry Christmas 2020 ==========
for i in range (1, 50, 2):
print(('*' *i).center (50))
for i in range (3):
print(('| |').center(50))
print(('===').center (50))
#Merry Christmass |
7d3240737624023ef1659520258ba92af77b35fe | hydraer/Python_stydy | /fx/fx_07_元祖.py | 533 | 4.4375 | 4 | # 元祖:可以存储多个数据,不可修改
# 定义:小括号,数据后加逗号
# 若只有一个数据时,数据后应加逗号,否则电脑会认为这不是元祖
tuple1 = (1, 'a', False, ['hello', 1, True, 1])
# index:查找某个数据,若存在则返回下标,不存在则报错
print(tuple1.index(1,0,2))
# count:查找数据出现次数
print(tuple1.count(0))
# len()统计元祖中数据个数
print(len(tuple1))
# 元祖内数列可以修改数据
print(tuple1)
tuple1[3][1] = '呵呵'
print(tuple1) |
04de08a194fc78752fca4c4cfb9209f7a92a18b6 | hydraer/Python_stydy | /fx/fx_03_while循环.py | 217 | 3.625 | 4 |
row = 1
while row < 10:
line = 1
while line <= row:
print(f'{line} * {row} = {row * line}', end= '\t')
line = line +1
else:
print()
row += 1
else:
print('九九乘法表') |
9aeb39148b718aec24f702e50952f1820479b085 | hydraer/Python_stydy | /hy/hy_11_列表.py | 716 | 4.09375 | 4 | list1 = [1, 'tom', True, 'jim', 'jim']
list2 = 'hello'
list3 = [1, 2, 3]
# print(list1.index('tom',1, 3))
# print(list1.count('tom'))
# print('h' in list2)
# print(list2.find('h'))
# print(list1)
# list1.append('222')
# print(list1)
# list1.extend(list3)
# print(list1)
# list1.insert(2,'hello')
# print(list1)
# del l... |
8676c3cb3b009a36db1727fded02781e48b5622e | hydraer/Python_stydy | /hy/hy_08_while循环.py | 1,406 | 3.765625 | 4 | # 1、重复打印5次媳妇我错了
# i = 0
# while i < 5:
# print('媳妇我错了')
# i += 1
# 2、计算1-100的和
# i = 1
# count = 0
# while i <= 100:
# if i%2 == 0:
# count = count + i
# i += 1
# print(count)
# # 3、吃苹果、第三个吃饱了
# i = 1
# while i<= 5:
# print('正在吃第%d个苹果'%i)
# if i == 3:
# print('吃饱了')
# b... |
cca9299a42e567337a2796ebba350671d745e98d | hydraer/Python_stydy | /fx/StudentManagerSystem/student.py | 298 | 4.0625 | 4 | # 学员类:包含姓名、性别、手机号
class Student():
def __init__(self, name, sex, tel):
self.name = name
self.sex = sex
self.tel = tel
def __str__(self):
print(f'学员姓名:{self.name},学员性别:{self.sex},学员电话:{self.tel}')
|
b362fbefd550d8fb03befd2c567e9d4e8eeba97b | hydraer/Python_stydy | /fx/fx_11_列表推导式.py | 685 | 4.125 | 4 | # 推导式
# 作用:用一个表达式创建一个有规律的列表或控制一个有规律的列表,列表推导式又叫列表生成式
# 列表推导式
list1 = []
for i in range(10):
list1.append(i)
print(list1)
i = 0
while i < 10:
list1.append(i)
i += 1
print(list1)
list2 = [i for i in range(0, 10, 2)]
print(list2)
list3 = [(i, j) for i in range(3) for j in range(11, 13)]
print(list3)
# 字典推导式
l... |
07b67a4e0630df25b77a20de947e0cef3a9d87bd | rguan72/basic-flask-app | /app.py | 1,643 | 3.5 | 4 | from flask import Flask
from flask import render_template
from flask import url_for
from flask import request
from flask import jsonify
import sqlite3
app = Flask(__name__)
@app.route('/')
def first():
return render_template("app.html")
@app.route('/receive_json', methods=['POST'])
def receive_json():
print(... |
4f404b3b1cfd91fe22b8f2626aca831680225cbe | juhgio/CodeAdventation | /advent_coding_1.py | 711 | 3.515625 | 4 | # -*- coding: utf-8 -*-
#!/usr/bin/env python3
#author: juho-petteri lesonen
#date: 04.12.2017
#Problem description from Advent of code 2017: https://adventofcode.com/2017/day/1
import time
import sys
def testing(value):
checksum = 0
num_i = list(map(int, value))
num_i.append(num_i[0])
length = len(num_i)-1
fo... |
21efc7087e1aa1ae62b97fe57c84663935706d6b | Jahdie/Algorithms_And_Structures_Data | /Lesson_2/Task_4.py | 712 | 4 | 4 | """
Найти сумму n элементов следующего ряда чисел: 1, -0.5, 0.25, -0.125,… Количество элементов (n) вводится с клавиатуры.
"""
def sum_series(n, first_num) -> float:
_sum = 0
if n != 0:
if first_num == 1:
_sum = 1
_sum = _sum + sum_series(n - 1, first_num / 2 * -1)
... |
aa7c93c2140dae9cfb9d40022e123a8e8a9a0d56 | Jahdie/Algorithms_And_Structures_Data | /Lesson_1/Task_6.py | 411 | 4.28125 | 4 | # Пользователь вводит номер буквы в алфавите. Определить, какая это буква.
# https://drive.google.com/file/d/1zjCdF5ZTABUqmMwkeLk06Lg9t-LYs9AC/view?usp=sharing
num = int(input("Введите номер от 1 - 26: "))
if 1 <= num <= 26:
print(f"Буква: {chr(96 + num)}")
else:
print("Число должно быть от 1 до 26.")
|
1b31ba4629c59c7a75d75ba85f06fbb04b4b1eb5 | Jahdie/Algorithms_And_Structures_Data | /Lesson_3/Task_3.py | 670 | 4.03125 | 4 | # В массиве случайных целых чисел поменять местами минимальный и максимальный элементы.
from random import randint
SIZE = 10
MIN_ITEM = 0
MAX_ITEM = 100
array = [randint(MIN_ITEM, MAX_ITEM) for _ in range(SIZE)]
min_item = max_item = array[0]
max_item_index = min_item_index = 0
print(array)
for i in range(len(array... |
9a4609ed7afe2d0803978387a68dc260fb6a9daf | jduarte2021/poo-python | /tienda_y_productos/producto.py | 616 | 3.625 | 4 | class Producto:
def __init__ (self, nombre,precio,categoria):
self.nombre = nombre
self.precio = precio
self.categoria = categoria
def print_info(self): # imprime el nombre del producto, su categoría y su precio.
print (f"El producto {self.nombre} que tiene la categoria de {self... |
986957ab03c1d971275c54f5738d90db1e480c3e | kzufelt/Python | /DragonQuest1.py | 20,233 | 4 | 4 | # This program is based on code from inventwithpython.com
import random
import sys
import math
cardinalDirections=['west','north','east','south']
difficulty=1
#Functions
def helpText():
print('\n\nDragonQuest is a text based game created by Kyle Zufelt in Python.\n\
In this first chapter of the game, the user finds ... |
966737893045a789f3e4703f7e9d989645b8362c | magisterzot/advent-of-code-2020 | /Day 11/adv_11.py | 1,894 | 3.6875 | 4 | from copy import deepcopy
def read_input(path):
with open(path,'r') as input:
lines = input.readlines()
entries = [line.strip() for line in lines]
array = [list(entry) for entry in entries]
return array
def adjacents(array,y,x):
adjacents = []
#new_array = array
for i in rang... |
746f181c8ca5a4dd363754d8d74dd2a569e9d905 | CodecoolBP20172/pbwp-3rd-tw-lightweight-erp | /crm/crm.py | 2,143 | 3.84375 | 4 | # data structure:
# id: string
# Unique and randomly generated (at least 2 special char()expect: ';'), 2 number, 2 lower and 2 upper case letter)
# name: string
# email: string
# subscribed: boolean (Is she/he subscribed to the newsletter? 1/0 = yes/not)
# importing everything you need
import os
# User interface ... |
41dad5e1f08ca61ace6d0301a910dc929a4ed754 | soniadonati/python_image_crypt | /template.py | 10,167 | 3.765625 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-—
from PIL import Image
import re
import base64
# file access
# ---------------------------------------------------
def openimage(filename):
""" Open the image (only lossless images are supported) given by the filename specified in the
filename string ... |
1651c9c3de6883ba153cd24d73d068bb242eb0f6 | shahin217/python | /Assignments/Assignment-2/Day2_Assignment.py | 1,545 | 3.640625 | 4 | def odd_one_out(l1): # Q1 odd man out
for i in range(len(l1)):
freq = 0
for j in range(len(l1)):
if l1[i] == l1[j]:
freq += 1
if freq == 1:
return l1[i]
return -1
def closest_to_mean(lst): # Q2 closest to mean
mean = sum(lst... |
a247899063aa4c12aec8d9a3b278d4795756d3d0 | cflo530/Python-Tokenizer | /PartA.py | 838 | 3.703125 | 4 | import sys
import re
# Each function runs in O(n) time
def tokenize(filepath):
result = []
regex = re.compile("[a-z0-9_]*")
with open(filepath, encoding='utf-8') as f:
for line in f:
result.extend(regex.findall(line.lower()))
return result
def computeWordF... |
6d9e619e0f1c1995c419642e08654c93ec458c32 | Vipexi/python_course | /functionist.py | 754 | 4.125 | 4 | #! /usr/bin/python3
"""def function_with_return(input_to_function1, input_to_function2):
variable_that_we_return_from_function = input_to_function1 + input_to_function2
return variable_that_we_return_from_function
answer_to_print1 = function_with_return(1,4)
print(answer_to_print1)"""
"""def returnable_func... |
2d496460437bf4ad8c1429a26b82ae74ea1b1789 | Vipexi/python_course | /fibonacci.py | 4,384 | 4.3125 | 4 | #! /usr/bin/python3
# First I made an input to ask the user how many numbers of the fibonacci the user wants to know.
# Until I asked others how they had done it.
# But the code worked also with asking a answer input for how many numbers the user wanted to know.
# Wasn't sure if the task was to use input or change th... |
8776c4d6dc0f02be3098d808f338b559da6b93c9 | Vipexi/python_course | /fibonacci_no_comma.py | 902 | 3.828125 | 4 | #! /usr/bin/python3
if __name__ == "__main__":
filename = "fibonacci_series_no_commas.txt"
try:
file_to_write = open(filename,"a")
except:
print("cannot open file")
file_to_write.write("Fibonacci series from 1 to 100:\n")
def fibonacci_numbers(numbers_in_series):
fib... |
be54bca6aebc06fdc296bf8c633cad128d74d41e | Vipexi/python_course | /try_except.py | 178 | 3.984375 | 4 | #! /usr/bin/python3
while True:
try:
number = int(input("give a number:"))
break
except:
print("give a number in digits, like a 2")
print(number) |
494ad5d7ba8502c4426b482e1be8759a3b1bb5c0 | jonyonson/Sorting | /src/iterative_sorting/iterative_sorting.py | 1,491 | 3.859375 | 4 | # TO-DO: Complete the selection_sort() function below
def selection_sort(arr):
# loop through n-1 elements
for i in range(0, len(arr) - 1):
cur_index = i
smallest_index = cur_index
# TO-DO: find next smallest element
# (hint, can do in 3 loc)
for j in range(i + 1, len(arr... |
dffe2730d153c6c4b71301f62e2925af12860e43 | artemrudenko/experiments | /euler/euler_1.py | 503 | 4.0625 | 4 | __author__ = 'artemr'
# Multiples of 3 and 5
# Problem 1
# If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9.
# The sum of these multiples is 23.
#
# Find the sum of all the multiples of 3 or 5 below 1000.
def euler_1(end, multiples=[3, 5]):
curr = multiples[0]
re... |
1bf41404805402c39dcbf8ad2e20147588935a9d | BaseCampCoding/python-fundamentals | /3-functions/pytest-exercises/functions.py | 3,827 | 3.75 | 4 | def add_em_up(a, b, c):
""" (number, number, number) -> number
Return the sum of a, b, and c.
"""
raise NotImplementedError("Delete this line and put your code here")
def sub_sub_hubbub(a, b, c):
""" (number, number, number) -> number
Return a minus b minus c.
"""
raise NotImplemente... |
471e533632ab2329d20e5091da28fbe1401e1020 | kpkk1518/algorithms | /chapter10_그래프이론_크루스칼알고리즘.py | 705 | 3.59375 | 4 | def find_parent(parent,x):
if parent[x]!=x:
parent[x]=find_parent(parent,parent[x])
return parent[x]
def uninon_parent(parent,a,b):
a,b=map(int,input().split())
a=find_parent(parent,a)
b=find_parent(parent,b)
if a>b:
parent[a]=b
else:
parent[b]=a
v,e = map(int,input... |
0bce1aade02935b0f27e94260929b64c207e5553 | wenyue7/LearnPython | /2.Tools/matplotlib/baseDemo.py | 2,184 | 3.859375 | 4 | import matplotlib.pyplot as plt
import numpy as np
# ======================================================================== 创建
# -- method 1
plt.plot([1, 2, 3, 4], [1, 4, 2, 3]) # Matplotlib plot.
# -- method 2
fig_1 = plt.figure() # an empty figure with no Axes
fig_2, ax = plt.subplots() # a figure with a sin... |
0464e57a68aeaf025ff4b1fe756e527731d29bbf | MHbN98/Innomatics_Internsip2021 | /Internsip_assinment/Minion_game.py | 634 | 3.6875 | 4 | def minion_game(string):
# your code goes here
vowels = 'AEIOU'
Stuart_score, Kevin_score = 0, 0
length = len(string)
for start_idx in range(length):
score = length - start_idx
if string[start_idx] in vowels:
Kevin_score += score
else:
Stuart... |
428e97a77d425546a922f9a14231c8c1c040fcf0 | skypilot-org/skypilot | /examples/docker/echo_app/echo.py | 657 | 3.796875 | 4 | """Echo app
Reads a file, echoes it and writes back to a specified path.
"""
import argparse
def main():
"""Main function"""
parser = argparse.ArgumentParser(description='Echo app')
parser.add_argument('input', type=str)
parser.add_argument('output', type=str)
args = parser.parse_args()
with... |
1247d268c73e248266448fe57929d993319086d0 | wesenbergg/hy-data-analysis-with-python-2020 | /part04/part04-e02_powers_of_series/src/powers_of_series.py | 332 | 4.125 | 4 | #!/usr/bin/env python3
import pandas as pd
def powers_of_series(s, k):
df = pd.DataFrame([])
for i in range(1, k+1):
df[i] = pd.Series(s**i, dtype=int)
return df
def main():
s = pd.Series([1,2,3,4], index=list("abcd"))
print(powers_of_series(s, 3))
if __name__ == "__main__":... |
8eb1f4859bc9b3bc6e459026bd2634cfb0c52058 | wesenbergg/hy-data-analysis-with-python-2020 | /part01/part01-e06_triple_square/src/triple_square.py | 340 | 3.953125 | 4 | #!/usr/bin/env python3
def triple(num):
return num*3
def square(num):
return num**2
def main():
for i in range(1, 11):
t=triple(i)
s=square(i)
if t < s:
break
print("triple({:.0f})=={:.0f} square({:.0f})=={:.0f}".format(i, t, i, s))
if __name__ == "__... |
439439ea94504368f6f073800b9f99d3274dca44 | wesenbergg/hy-data-analysis-with-python-2020 | /part03/part03-e13_read_series/src/read_series.py | 1,015 | 3.921875 | 4 | #!/usr/bin/env python3
import pandas as pd # This is the standard way of importing the Pandas library
import numpy as np
def read_series():
user_input = ""
arr = np.array([])
while True:
user_input = input("Write index and value separeted with whitespace: ")
if user_input == "": break
... |
3cf71a5364cc5ae8a3f6b27bb09e9f4ea49ef57d | wesenbergg/hy-data-analysis-with-python-2020 | /part02/part02-e08_prepend/src/prepend.py | 271 | 3.984375 | 4 | #!/usr/bin/env python3
class Prepend(object):
def __init__(self, prepend):
self.pre = prepend
def write(self, text):
print(f"{self.pre}{text}")
def main():
p = Prepend("+++ ")
p.write("Hello")
if __name__ == "__main__":
main()
|
33e8826faba5f0f9a0dca724460f49cca47b7002 | piotrszyma/aoc2019 | /day1/task1.py | 112 | 3.5 | 4 | with open('input', 'r') as file:
fuel_needed = sum(int(line) // 3 - 2 for line in file)
print(fuel_needed)
|
9bf90d6e2943320fd69093b0068267055ca54d5b | albgut/InternshipM1_CMAPF | /instance.py | 15,829 | 3.8125 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Jun 10 18:19:57 2021
@author: algutier
"""
import igraph as ig
import random as r
import math as m
from configuration import *
from astar import *
import multi_a_star
class Instance:
"""
A class to represent all the data of the problem :
... |
1dfd84e28a58d5be3dcf4ca4275b7be281e979be | tbradshaw91/DS-Unit-3-Sprint-2-SQL-and-Databases | /demo_data.py | 984 | 4.09375 | 4 | import sqlite3
# Establishing Connection
conn = sqlite3.connect('demo_data.sqlite3')
curs = conn.cursor()
# Creating a table
curs.execute(
"""
CREATE TABLE demo (
s str,
x int,
y int
);
"""
)
conn.commit()
# Inserting Values
curs.execute(
"""
INSERT INTO demo
VALUES
('g',3,9),
('v',5,7),
('f',8,7);
""")
conn.co... |
3f86c771b0577faee9a796b754a2be8a816144f5 | poshan0126/PythonPractice | /addwithinput.py | 314 | 3.96875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sat Jun 29 20:07:07 2019
@author: Poshan Pandey
"""
# Store input numbers
num1 = input('Enter first number: ')
num2 = input('Enter second number: ')
# Add two numbers
sum = float(num1) + float(num2)
# Display the sum
print('The sum of {0} and {1} is {2}'.format(num1, num2, sum))... |
375caf6a1cec165092aa7ab2110260dfcceefdaf | jcoder53/junk | /threading/1.py | 670 | 3.8125 | 4 | import time
from threading import Thread
def greet():
start = time.time()
name = input("Enter your name: ")
print(f"Hello {name}")
print(f"greet ran in {time.time()-start} seconds")
def calculate():
start = time.time()
[x**2 for x in range(20000000)]
print(f"calculate ran in {time.time()-s... |
99b002cc523b9642f363885ce5a4d861def925c4 | jasoven/extract-IPs | /extract-IPs.py | 618 | 3.734375 | 4 | #!/usr/bin/env python2
import re
import argparse
from IPy import IP
def parse_args():
parser = argparse.ArgumentParser()
parser.add_argument("-f", help="Filename to extract IPs from")
return parser.parse_args()
def main(args):
ips = []
with open(args.f, 'r') as f:
for line in f.readlines... |
58938694f449b37629c8df25c280c81ff1b379d1 | 4m1g0/bitcoin_botnet | /minar.py | 672 | 3.65625 | 4 | #!/usr/bin/python
import hashlib
hashM = "sadj129ah29uasdj1k3l92joasd-123ishdia9123-123ijq"
targetM = 4
def zeros(target):
i=0
resultado ="0"
while i < target-1:
resultado +="0"
i+=1
return resultado
def minar(hashMinar,target):
nonce=0
while True:
resultado = hashMinar+ "-" + str(nonce)
solucion= has... |
0763451b5949d63571ac14e6fa4d7e05507867c8 | john2796/Python-Algos | /Data-Structure/LinkedList.py | 3,706 | 3.90625 | 4 | # Create Linked List with these methods
# print all linked - lists
# enqueue(self, item) add to last
# dequeue(self) remove head thanos LOL
# length
# def contains(self, value):
class Node:
def __init__(self, value):
self.value = value
self.next = None
class LinkedList:
def __init__(self):
... |
3ef0b2845f95b58437b7f7e840590d86dd04a2b6 | simplextable/FreeCodeCamp_MachineLearning | /1/RPS.py | 2,068 | 3.59375 | 4 | # The example function below keeps track of the opponent's history and plays whatever the opponent played two plays ago. It is not a very good player so you will need to change the code to pass the challenge.
import random
def player(prev_play, history=[], my_history=[]):
#print("len(history): ", len(history... |
598eb90408b6e8830956da8fb8a026cfedff8010 | ja-mf/py-traffic | /Auto.py | 778 | 3.5 | 4 | # Auto mantendra el inicio, final y la ruta
# Se hara el calculo de la ruta mediante un algoritmo y se pondra en ruta[]
# ciudad es el grafo (diccionario).
class Auto:
def __init__(self, inicio, final, ciudad):
self.uid = 0
self.inicio = inicio
self.final = final
self.ruta = []
self.calcularRuta(inicio, fin... |
4653a3337032adc75ab58eb56d8ea00c25dfd452 | shubhkalani/MachineLearning | /CC37_SLR2.py | 1,246 | 3.84375 | 4 | import pandas as pd
import matplotlib.pyplot as plt
Movie = pd.read_csv("Bahubali2_vs_Dangal.csv")
#Splitting into dependent and independent columns
Days=Movie.iloc[:,0:1]
Bahubali2=Movie.iloc[:,1]
Dangal=Movie.iloc[:,2]
#Generating linera regression prediction model for Bahubli2
from sklearn.linear_model import Li... |
5de316c8b16c1691ea5a3390dd6e28856d8b9659 | shubhkalani/MachineLearning | /CC46_PCA(Crime.py | 1,090 | 3.890625 | 4 | import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
Dataset = pd.read_csv("crime_data.csv")
#Splitting into Dependent and Independent Data
x=Dataset.iloc[:,[2,3,4]].values #Removed the urban pop as it is not taken for clustering
y=Dataset.iloc[:,0:1].values
#labelEncoding of y:
from sklearn.prepr... |
7fd37a7929bb64dca5847106a10cbd5ddbcd5206 | tmcmaster/python-playground | /test-rotation.py | 1,322 | 3.875 | 4 | #!/usr/bin/python
from copy import copy, deepcopy
#
# The maze map
#
matrix = [
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ],
[ 1, 0, 0, 1, 0, 0, 0, 0, 1, 1 ],
[ 1, 1, 0, 1, 0, 1, 1, 0, 1, 1 ],
[ 1, 1, 0, 0, 0, 0, 1, 0, 1, 1 ],
[ 1, 1, 1, 1, 0, 1, 1, 0, 0, 1 ],
... |
bf790388a703bd95a99a2e6afffe901e6cef9c2b | ghimiregokul/calculator | /addition.py | 174 | 3.96875 | 4 | def addition():
number1 = int(input('Enter your first number: '))
number2= int(input('Enter your second number: '))
print(number1 + number2)
print(hello)
|
3430b123dc8c147330c944f7505edaa1d99f3074 | RealWangcc/datawhale-test | /day2.py | 2,982 | 4.15625 | 4 | #1. 合并两个有序链表
"""
将两个有序链表合并为一个新的有序链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。
输入:1->2->4, 1->3->4
输出:1->1->2->3->4->4
"""
# Definition for singly-linked list.
class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
class Solution(object):
def mergeTwoLists(self, l1, l2):
"""
... |
ca1d3a2f6a2b2c0912e09dd270fb8aedac0f28e1 | Blackshirt99/1902 | /1902/_python_/obj/1.py | 325 | 3.53125 | 4 | class People():
def __init__(self, name):
self.name = name
def work(self):
print(self.name + ' is working now')
class Student(People):
def __init__(self, sid, name):
self.sid = sid
super().__init__(name)
stu = Student(100, 'FangFang')
print(stu.name)
stu.work();... |
a65d16edb47ea5bd0261d919ee78ac5b4d07bbaa | Tmozovka/Python_algorithms | /BST iterative.py | 1,686 | 3.984375 | 4 | class Node(object):
def __init__(self, value):
self.value = value
self.left = None
self.right = None
class BST(object):
def __init__(self, root):
self.root = Node(root)
def insert(self, new_val):
cur = self.root
while True:
if new_val > cur.value... |
4387e3804065ec1330b195ae427e7d93ba340ec4 | smykalk/UPOL-PAPR4 | /zapocet/para_mergesort.py | 1,426 | 3.5625 | 4 | import threading
from random import randint
#import sys
# sys.setrecursionlimit(1500)
def random_list(length, from_value=1, to_value=1000):
random_list = [randint(from_value, to_value) for i in range(length)]
return random_list
def parallel_merge_sort(arr, thread_count):
if len(arr) > 1:
mid = ... |
42286ffa944c6a96daadebd2fbf4b25eb6eef9fe | Narotu18/Python | /lou1/listtest.py | 255 | 4.03125 | 4 | #!/usr/bin/env python3
import sys
first_list=[]
second_list=[]
for i in sys.argv[1:]:
if len(i) <=3:
first_list.append(i)
else:
second_list.append(i)
print(' '.join(first_list))
print(' '.join(second_list))
|
6b393406abb792c087eef603502847139829231c | Narotu18/Python | /lou1/classtest.py | 1,447 | 3.96875 | 4 | #!/usr/bin/env python3
class UserData:
def __init__(self,ID,Name):
self.ID=ID
self.Name=Name
class NewUser(UserData):
def __init__(self,ID,name):
super(NewUser,self).__init__(ID,name)
def __call__(self): #call函数,使实例可以被调用
... |
7cc5c86d2346a4a9ebc12608045ba0d0da822b59 | weizhiyangq/python_train | /caidan.py | 991 | 3.6875 | 4 | hao=1
caidan=['米饭','番茄炒鸡蛋','白切鸡','排骨','白菜','茄子']
while True:
num=1
liao=[]
print("What do you want to add:\n"+str(num)+".")
while True:
zeng=input()
if zeng in caidan:
liao.append(zeng)
num+=1
print("OK\n"+str(num)+".")
elif zeng=='quit':
... |
ec97f830c3f2897bcbc4df4f05a20a7e32210882 | coocos/advent-of-code-2018 | /day5.py | 1,626 | 4 | 4 | import string
import re
import os
from typing import List, Tuple
def trigger_reactions(polymer: str) -> str:
"""
Triggers the polymer reactions and returns the polymer with all the
reactions applied.
The algorithm works by iterating through the polymer and comparing the
current unit against the n... |
dcc1ac9d1ba54cb16f56e831cbb70e2480efc321 | bertacsevercan/Numeric-Matrix-Processor | /processor.py | 7,452 | 3.671875 | 4 |
def constant_x_matrix():
n,m = [int(x) for x in input("Enter size of matrix: ").split()]
matrix_a = []
print("Enter matrix:")
for i in range(n):
i_ = [int(x) if x.isdigit() else float(x) for x in input().split()]
matrix_a.append(i_)
c = input("Enter const... |
428007683a6442548993ed77b64cc50865e7de1b | hajaranazeer/python_tutorial | /intro/intro5.py | 118 | 3.75 | 4 | #typcasting- desired_datatype(value)
a=int(input('enter a value'))
b=int(input('enter b value'))
c=a+b
print('sum=',c) |
b99473c284d61d38f52e3a28c4eac19337e21a74 | hajaranazeer/python_tutorial | /loop/range/forloop.py | 150 | 3.84375 | 4 | n=8
for i in range(8):
for j in range(0,n):
print( end = " ")
n=n-1
for j in range(0,i-1):
print(j, end = " ")
print() |
58ddeacf5ac2dc2d2246bc562554e0012586a162 | hajaranazeer/python_tutorial | /programs/algebra.py | 124 | 4 | 4 | a=int(input("enter a value"))
b=int(input("enter b value"))
((a+b)**2)=(a^2)+(b^2)+(2*a*b)
algebra=(a+b)^2
print(algebra)
|
aa5dd98d0dcd43e6b37e505374b73ac7d5253ded | hajaranazeer/python_tutorial | /basics/function/fibu.py | 364 | 3.625 | 4 | a="normal variable"
_b="variable with a single under score"
__c="variable with a double underscore"
def factorial(n):
fact=1;
for i in range(1,n+1):
fact=fact*i
return fact
def fibonacci(n):
print("this is fibonacci")
fib=[]
a,b=0,1
for i in range(n):
c=a
a=b
... |
10beb5017fb3ee0089bc5bee38b68252462974c0 | hajaranazeer/python_tutorial | /intro11.py | 69 | 3.625 | 4 | a=eval(input("enter a number to find cube"))
cube=a*a*a
print(cube)
|
25d211e45c3b42a55a9301b32d43d1fc6a8ceb4d | kcwillis/hotdog | /competition.py | 4,534 | 4.125 | 4 | #
# Copyright (C) 2017 Tignis, Inc.
#
"""
Implement the Competition class.
"""
from decimal import Decimal
from operator import attrgetter
def round_value(value, precision=Decimal('1.000')):
"""
Round float value to specified precision.
:param value: Float value.
:param precision: Precision as a Deci... |
8e3f132cae23cea41711282ceea604a8477aef55 | dldk-gael/lm-heuristic | /src/lm_heuristic/tree_search/mcts/counter_node.py | 4,764 | 3.5625 | 4 | """
Define a node's wrapper that maintains several statistics needed during the MCTS search
"""
import random
from typing import *
from lm_heuristic.tree import Node
class CounterNode(Node):
"""
A counter node will be used on top of a given (which is denote as the reference node) in order to
maintain se... |
a7af3e626826821713e4c4ca8b79cb7ec7ae8bd4 | DmitriiShamrikov/punit | /assertions.py | 2,758 | 3.578125 | 4 | import math
def IsTrue( value ) :
assert value, "Expected True"
def IsFalse( value ) :
assert not value, "Expected False"
def IsNone( value ) :
assert value == None, "Expected " + str( value ) + " is None"
def IsNotNone( value ) :
assert value != None, "Expected " + str( value ) + " is not None"
... |
33a6677004089fdc39922e206e6521b3c008a854 | pdoherty31/Intro_Biocom_ND_319_Tutorial5 | /ex5.py | 1,084 | 3.765625 | 4 | ###Exercise 5-1###
import pandas as pd
wages=pd.read_table("wages.csv",",")
gen_years=wages.iloc[0:len(wages),0:2]
gen_years=gen_years.sort_values(by=['gender','yearsExperience'], ascending=[1,1])
gen_years.to_csv('ex5_1.txt', header=True, index=False, sep=" ")
###Exercise 5-2###
import pandas as pd
wages=pd.read_tabl... |
ed90b7279b8469049aad8c712e330f1c425ea55e | huangh12/single_channel_colorful_image | /draw.py | 777 | 3.515625 | 4 | '''
reference: http://stackoverflow.com/questions/3114925/pil-convert-rgb-image-to-a-specific-8-bit-palette
http://abruzzi.iteye.com/blog/314790
http://www.2cto.com/kf/201603/492898.html
'''
from PIL import Image
import numpy as np
from datasets import CONFIG
# The arr is a predicted result
... |
b7e9b3162149b5aba4e19e03615cacfaf5c25ba3 | haveric/roguelikedev | /python/pt5/entity.py | 562 | 3.609375 | 4 | class Entity:
"""
A generic object to represent players, enemies, items, etc.
"""
def __init__(self, x, y, char, color, name, blocks=False):
self.x = x
self.y = y
self.char = char
self.color = color
self.name = name
self.blocks = blocks
def move(self, dx, dy):
# Move the entity by a given amount
s... |
755a8a6df3387caf27f4e3f69a5e11249b452eb0 | zhyErick/fengkuang_python | /06/6.2.decorator_test.py | 921 | 3.875 | 4 | # def funA(fun):
# print("A")
# fun() # 执行传入的fn参数
# return 'fkit'
# # 下面的装饰效果相当于funA(funB),funB将会被替换(装饰)成该语句的返回值,由于funA函数返回fkit,因此funB就是fkit
# @funA
# def funB():
# print('B')
#
# print(funB)
def foo(fn):
# 定义一个嵌套函数
def bar(*args):
print("===1===", args)
n = args[0]
print... |
619c3ba486511c78246280cbd4f29fa0944ec6da | zhyErick/fengkuang_python | /04/4.4.for_test.py | 136 | 3.71875 | 4 | s_max = input("请输入您想计算的阶乘:")
mx = int(s_max)
result = 1
for num in range(1, mx + 1):
result *= num
print(result) |
c1c98ee523de076a840db858bce35b9da4696fa3 | zhyErick/fengkuang_python | /practise/03/prac1.py | 168 | 3.640625 | 4 | a, b, c = input('请输入第一个字符串:'), input('请输入第二个字符串:'), input('请输入第三个字符串:')
tuple1 = (a, b, c)
print(tuple1 * 3) |
2aa082b4e1d11f84196f7d0270f1aa5583871316 | zhyErick/fengkuang_python | /02/2.3.hex_test.py | 376 | 3.5 | 4 | # 十六进制
hex_value1 = 0x13
hex_value2 = 0XaF
print("hexValue1的值为:", hex_value1)
print("hexValue2的值为:", hex_value2)
# 二进制
bin_val = 0b111
print('bin_val的值为:', bin_val)
bin_val = 0B101
print('bin_val的值为:', bin_val)
# 八进制
oct_val = 0o54
print('oct_val的值为:', oct_val)
oct_val = 0o17
print('oct_val的值为:', oct_val) |
f94078cc3d9ad5a55f711b2a274bbc7ff38968de | ILIKEFUUD/Python | /DNAAnalysis.py | 2,204 | 3.6875 | 4 | """
Rahul Shah
DNAAnalysis.py
Compares arrays of DNA sequences
"""
testStrand = ["A","T","T","A","G","A","C","A","T","G","G","A","G","T","T","A","C","C","A","T"]
targetStrand = ["A","T","A","A","G","A","C","A","A","C","G","A","G","A","T","A","C","C","A","T"]
#print out strands
temp = "Test Strand: "
fo... |
6e4f72684bd1e539bc1045c5f5bc54c1289bca45 | ILIKEFUUD/Python | /RectanglePerimeter.py | 333 | 4.1875 | 4 | """
Rahul Shah
RectanglePerimeter
11/11/15
Calculates and displays the perimiter of a Rectangle
of width 4 and a length of 13
"""
#variables
#Width is the width of the rectangle
width = 4
#length is the length of the rectangle
length = 13
#output
#print the perimeter
print ( "Perimiter: ",(2*width... |
7d12ade16c0fae6a43a130bc131525326aea0da6 | ILIKEFUUD/Python | /ArrayLab.py | 504 | 4.03125 | 4 | """
Rahul Shah
Pd 6
ArrayLab.py
- Constructed an array of 50 integers
- Initialized the array of 50 integers with the numbers 1 to 50.
- Printed out the numbers 1 to 50 separated by commas on the same line.
"""
#python actually uses lists, which are basically arrays
nums = []
#populate array
... |
37e9c1b1df3b6e37b1729226394f4660adf6b6a8 | jmquintana79/utilsDS | /scripts/plot/scatter.py | 6,401 | 3.59375 | 4 | # @Author: juan
# @Date: 2020-01-21T08:49:20+01:00
# @Last modified by: juan
# @Last modified time: 2020-01-21T08:49:20+01:00
"""
Scatter plot where is possible label by other variables (numerical and categorical) and include
linear regression estimation.
"""
import seaborn as sns
import matplotlib.pyplot as plt
... |
9a7e907b7012b8a2e0df914a2a24edc2ff74db65 | YiField/python-demo | /recursive-func.py | 841 | 4.03125 | 4 | # 递归函数的优点是 定义简单,逻辑清晰。
def fact(n):
if n == 1:
return n
return n*fact(n-1)
print(fact(10))
# 在计算机中,函数调用是通过栈(stack)这种数据结构实现的,
# 每当进入一个函数调用,栈就会加一层栈帧,每当函数返回,栈就会减一层栈帧。
# 尾递归:函数返回的时候,调用自身本身,并且return语句不包含表达式。 【把循环看成是一种特殊的尾递归函数】
def fact2(n):
return fact_iter(n, 1)
def fact_iter(num, product):
... |
24be2c7e237786185bffcdb8763e372b59f58876 | GodsloveIsuor123/holbertonschool-higher_level_programming-3 | /0x0B-python-input_output/7-save_to_json_file.py | 300 | 3.859375 | 4 | #!/usr/bin/python3
'''
file: 7-save_to_json_file.py
functions:
-> save_to_json_file
'''
import json
def save_to_json_file(my_obj, filename):
''' writes Object to a text file, using JSON representation '''
with open(filename, 'w', encoding="utf-8") as file:
json.dump(my_obj, file)
|
c7a97bf3041ae87692ecb01cb28134be1021091f | GodsloveIsuor123/holbertonschool-higher_level_programming-3 | /0x01-python-if_else_loops_functions/8-uppercase.py | 215 | 4.09375 | 4 | #!/usr/bin/python3
def uppercase(str):
for i in range(len(str)):
word = ord(str[i])
if (word >= 97 and word <= 122):
word -= 32
print("{:c}".format(word), end="")
print()
|
6e0a0729db7d8c2475a02369acc257b9284291b1 | Pick1a1username/making_games_with_python_and_pygame | /chapter8/squirrel_eat_squirrel.py | 17,982 | 3.796875 | 4 | # Squirrel Eat Squirrel (a 2D Katamari Damacy clone)
# By Al Sweigart al@inventwithpython.com
# http://inventwithpython.com/pygame
# Creative Commons BY-NC-SA 3.0 US
import random, sys, time, math, pygame
from pygame.locals import *
FPS = 30
WINWIDTH = 640
WINHEIGHT = 480
HALF_WINWIDTH = int(WINWIDTH / 2)
HALF_WINHEI... |
565a745e13d47c00ea90773e82484095274d35d0 | mjoze/kurs_python | /kurs/02_instrukcje_sterujace/other/while4.py | 546 | 3.71875 | 4 | """Napisz skrypt obliczający wartość silnii. Rozwiąż zadanie za pomocą pętli for oraz pętli while.
Wejście: „Podaj dowolną liczbę całkowitą do 15:” 4
Wyjście: 4! = 24"""
silnia = 1
num = int(input('Podaj liczbę całkowitą do 15'))
if num > 15:
print("podałeś za dużą liczbę")
num = int(input('Podaj liczbę całkow... |
a434de8010698d34650134ccf229579427b6a36d | mjoze/kurs_python | /kurs/04_funkcje/zadania/zadanie3.py | 534 | 3.9375 | 4 | """ Nie korzystając z funkcji wbudowanej max(), napisz funkcję znajdującą maksymalną wartość z 3 liczb.
maximum_of(a, b, c)."""
def my_max(a, b, c):
list_number = [a, b, c]
max_n = list_number[0]
for i in list_number:
if i > max_n:
max_n = i
return max_n
a = my_max(26, 190, 78)
p... |
16a129f29ff3073069525a5fd385ac728b920db2 | mjoze/kurs_python | /kurs/04_funkcje/zadania/zadanie4.py | 572 | 3.78125 | 4 | """Napisz funkcję, która sprawdzi, czy liczba występuje w podanym przez użytkownika zakresie.
Powinna zwrócić komunikat: “tak, liczba x znajduje się w zadanym zakresie”, “nie, liczba x jest z poza zakresu”."""
c = int(input("podaj liczbę"))
def is_number_in(c):
a = 2
b = 121
num_in_range = []
for i ... |
d837a84ea09ef7b0a97d8dc939e3ba234cacfeb6 | mjoze/kurs_python | /kurs/09_algorytmy/zadanie3.py | 398 | 4.125 | 4 | """Przypomnij sobie szkolny wzór na silnię. Zapisz funkcję silnia iteracyjnie np. pętlą for,
a następnie analogiczną funkcję tylko, że rekurencyjnie."""
def silnie(n):
silnia = 1
for n in range(1, 1 + n):
silnia *= n
return silnia
def sil(n):
if n in (0, 1):
return 1
elif n > 1:
... |
7b505ea6e082145127ee19dfc4112ca29ff08d0b | mjoze/kurs_python | /kurs/03_kolekcje/zadania/ex7.py | 280 | 3.78125 | 4 | """Usuń duplikat z podanej list i utwórz na jej bazie krotkę. Znajdź minimalną i maksymalną liczbę w krotce.
"""
example_list = [34, 17, 25, 41, 12, 194, 41, 3, 12, 99, 94]
a = tuple(list(set(example_list)))
print(a)
a_max = max(a)
print(a_max)
a_min = min(a)
print(a_min) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.