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 |
|---|---|---|---|---|---|---|
bdca9b57fc462e41dd679824d8f5af18c7cb3112 | Thoaitran260901/python | /Buoi 3/cau10.py | 291 | 3.9375 | 4 | print("De quy dem so luong chu so le")
i=0
def count_odd(n,i):
if i==len(n) or n[i].isnumeric==False:
return 0
if int(n[i])%2!=0:
return 1+count_odd(n,i+1)
else:
return 0+count_odd(n,i+1)
n=input("Nhap so can kiem tra: ")
print(count_odd(n,i)) |
95baae6d40b26b5e237db5ec7720e07228cb5a0a | Nahid-Hassan/software-development | /courses/algorithmic-toolbox/main.py | 317 | 3.578125 | 4 | # read n
n = int(input('Enter the n: '))
# read the sequence of numbers
nums = list(map(int, input("Enter n integers: ").split()))
# processing - iterative method
# initialize mx = 0
mx = 0
for i in range(n):
for j in range(i+1, n):
if nums[i] * nums[j] > mx:
mx = nums[i] * nums[j]
print(mx)
|
5f4363e84f13c2e08caa29979355158642767afe | Nahid-Hassan/software-development | /py-codelab/stress_test(HSE).py | 1,264 | 3.734375 | 4 | from random import randint
def maximum_pairwise_product(nums):
# Iterative solution
result = 0
# calculate maximum pairwise of multiplication
for i in range(len(nums)):
for j in range(i + 1, len(nums)):
# if new pair multiplication is greater than previous result
# then ... |
b92391ebf1367e4082c50c2fc70daa77ac76f0e9 | bartdavids/ML | /Regression/Regression.py | 4,323 | 4.03125 | 4 | # -*- coding: utf-8 -*-
"""
Created by: bartdavids: https://github.com/bartdavids/ML/
Python executable to initate the Linear and Logistic Regression packages and
compare linear and logistic regression for the purpose of classification.
In addition some Adam vs. Gradient Descent is tested.
"""
import os
o... |
81e4980db2076f66ff68a0050cb9fcaacdce7046 | naveenprakash74/InnovateIND | /SmartCarFinal.py | 3,200 | 3.546875 | 4 | import RPi.GPIO as GPIO
import time
GPIO_TRIGGER=3
GPIO_ECHO=5
#set GPIO Pins
def init():
GPIO.setmode(GPIO.BOARD)
GPIO.setwarnings(False)
GPIO.setup(GPIO_TRIGGER, GPIO.OUT)
GPIO.setup(GPIO_ECHO, GPIO.IN)
GPIO.setup(35,GPIO.OUT)
GPIO.setup(36,GPIO.OUT)
GPIO.setup(37,GPIO.OUT)... |
036def49066d8f34f97c96a06350bc5c79560063 | Anurag-12/learning-python | /json_module/main.py | 2,656 | 4.0625 | 4 | '''
SON stands for JavaScript Object Notation. JSON is a data-interchange format, derived from JavaScript. It is mostly used for storing or
transferring data. So, if we want our program to interact with the internet, we must be familiar with this module, even only to send or
receive data through the internet.
A... |
f204312c8a2bd68d75b89db21b8334c3d7d9191d | Anurag-12/learning-python | /Coroutines_Example/main.py | 2,464 | 4.3125 | 4 | '''
Both generator and coroutine operate over the data; the main differences are:
Generators produce data
Coroutines consume data
Coroutines are mostly used in cases of time-consuming programs, such as tasks related to machine learning or deep learning algorithms or in cases
where the program has to re... |
b218d86d37133fcc696e1852c415e61dfc993e14 | Anurag-12/learning-python | /request_module/main.py | 2,110 | 3.703125 | 4 | '''
What is HTTP?
HTTP stands for the 'Hypertext Transfer Protocol,'. It is a set of protocols that are designed to enable communication between clients and
servers. Between clients and servers, it works as a request-response protocol. To request a response from the server, we can request data
from the server, ... |
d181bf517a3d745068e1e2de3af4d91abaf18b6b | Anurag-12/learning-python | /seek-tell-file/main.py | 861 | 4.4375 | 4 | #This code will change the current file position to 5, and print the rest of the line.
# Note: not all file objects are seekable.
f = open("myfile.txt", "r")
f.seek(5)
print( f.readline() )
f.close()
f = open("myfile.txt")
f.seek(11)
print(f.tell())
print(f.readline())
# print(f.tell())
print(f.readlin... |
8852db9a90e6e376ce7626675d47863d80b8c0af | Mustafa188/class2-functions-week04 | /4-greatest_common_divisor.py | 517 | 4.03125 | 4 | def greatest_common_divisor():
a = int(input("Please Enter any number : "))
b = int(input("Please Enter any number : "))
set_a=set()#kume elemanlari tekrarlamaz
set_b=set()
for i in range (1,a+1):
if a % i == 0 :
set_a.add(i)
#print(set_a)
for j in range (1,b+1):
... |
b2d3227019b95ca396b8d0c02937a08aeb3d62ff | vahansukiasyan/python | /homework 1.py | 419 | 3.578125 | 4 | # exercise 1
#s = "Hello!I am Ruben. how are you?"
#s = s.replace(".", " ")
#s = s.replace("?", " ")
#s = s.replace("!", " ")
#print(s)
# exercise 2
#n = [int(x) for x in input()]
#print(round(sum(n)/len(n),1))
# exercise 3
#text = input().split()
#count = 0
#for word in text:
#if word[0] == word[0].upper... |
4f040c95b3aec3234582e90a09a4196ce618dc70 | hisheng/PythonAlgorithms | /selection_sort.py | 566 | 3.578125 | 4 | # 选择排序 O(n*n)
#1.遍历这个列表,找出最大的值,并将这个值添加到一个新列表中。
#2.再次这样做,找出次数第二多的乐队
nums = [123,45,53,23,12,11,34,67,32,78,1]
def selection_sort(nums):
new = []
while len(nums) > 0:
index = get_max(nums)
new.append(nums[index])
del nums[index]
return new
def get_max(nums):
max = 0
i = 0
... |
0df933d27823138c6cd831441817711a7b5caa8c | hisheng/PythonAlgorithms | /quick_sort.py | 661 | 3.890625 | 4 | # 快速排序
#1.基线条件,当为空,以及 1个元素的时候,都不需要排序
#2 (1) 选择基准值。
#2 (2) 将剩余数组分成两个子数组:小于基准值的元素和大于基准值的元素。
#2 (3) 对这两个子数组进行快速排序
array = [123,45,53,23,12,11,34,67,32,78,1]
def quick_sort(arr):
if(len(arr) < 2):
return arr
else:
base = arr[0]
small = []
big = []
for i in arr[1:]:
... |
5111dee03f6cdcc8dc76ffe3409b809fefaf4ffd | vijaypalmanit/daily_coding_problem | /daily_coding_problem_2.py | 649 | 4.125 | 4 | # This problem was asked by Uber.
# Given an array of integers, return a new array such that each element at index i of the new array is the product of all the numbers in the original array except the one at i.
# For example, if our input was [1, 2, 3, 4, 5], the expected output would be [120, 60, 40, 30, 24]. If our... |
0290d5eca488fd4279ca9f28d6d2a729cfe7adb5 | woslade/Bioinformatics | /hammingDistance.py | 502 | 3.828125 | 4 | def pointMutations(s,t):
'''
Assume len(s) == len(t)
Assume len(s) <= 1kbp
Given two strings s and t of equal length, the Hamming distance between s and t, denoted dH(s,t), is the number of
corresponding symbols that differ in s and t.
Input
---
s: string
t: string
Oup... |
9a5c8593951a960ab1ccd21f50cf7f1b41aa4467 | CriusCrius/PythonDataStructure | /01-array.py | 762 | 4.09375 | 4 | # 数据结构中的线性结构——数组和列表,线性结构特点:内存连续、可通过下标访问
# 实现一个数组
class Array(object):
def __init__(self, size=32):
self._size = size
self._items = [None] * size
def __getitem__(self, index):
return self._items[index]
def __setitem__(self, index, value):
self._items[index] = value
de... |
2e241c6ad9da2148036956c2444f4ddb1d9cb7d9 | CriusCrius/PythonDataStructure | /11-1_recursion.py | 527 | 3.890625 | 4 | # 递归
"""
本节用栈模拟递归
"""
from collections import deque
class Stack(object):
def __init__(self):
self._deque = deque()
def push(self, value):
return self._deque.append(value)
def pop(self):
return self._deque.pop()
def is_empty(self):
return len(self._deque) == 0
d... |
36829d8f6439f71ab6bca0fcf2b99617a611101a | Smile-Bonchichi/Library_Lab_PIPITEH | /4 семестр/Питон/Задание практика 5.py | 1,238 | 4.1875 | 4 | ===1===
class Mercedes(object):
def __init__(self, colors, type, model):
self.colors = colors
self.type = type
self.mode = model
def drive(self):
"""
Drive
"""
return "Я за рулем машины"
def brake(self):
"""
Brake
... |
14002e04f2edc0954f218ff4907d6f77191d5b15 | RoobenK/E-commerce-Sales-Predictor | /RegressionModel.py | 1,958 | 3.828125 | 4 | import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import math
import pickle
## Data extraction from txt file
dataframe = pd.read_csv('CustomersData.txt')
dataframe.drop(['Address','Avatar', 'Email', 'Time on Website'], 1 , inplace = True)
# We drop the Time on Website as it has outliers and th... |
9dd9cbf82e8bcecb2eee94c27c92852e89cd6303 | xiaoxuesheng-ok/learnpy | /02hardway/ex21.py | 659 | 3.984375 | 4 | def add(a,b):
print(f"adding {a} + {b}")
return a + b
def subtract(a,b):
print(f"subtract {a} - {b}")
return a - b
def multiply(a,b):
print(f"multiply {a} * {b}")
return a * b
def devide(a,b):
print(f"devide {a} / {b}")
return a / b
print("Let's do some math with just functions!")
a... |
bfa3ec34680975e514abed96ccabe1a3a0091924 | tristanbriseno/super_hero_team_dueler | /team.py | 1,657 | 3.65625 | 4 | import random
class Team:
def __init__(self, name):
self.name = name
self.heroes = list()
def remove_hero(self, name):
foundHero = False
for hero in self.heroes:
if hero.name == name:
self.heroes.remove(hero)
foundHero = True
... |
88827745c52b0830e401eaa495dd9dae44d80a75 | VitaliyKrytsun/Student | /Student3Week/31.py | 355 | 3.5 | 4 |
def chisla(n):
a = []
for i in range(n + 1):
a.append(i)
i = 2
while i <= n:
if a[i] != 0:
j = i + i
while j <= n:
a[j] = 0
j = j + i
i += 1
a = set(a)
a.remove(0)
print(a)
n = int(input('Введ... |
a42e98f2e6c117f671ea0e30e220701a45432392 | VitaliyKrytsun/Student | /1.py | 193 | 4 | 4 | def add_three():
"""Вернуть 3 + число, введенное пользователем."""
number = int(input('Enter a number: '))
return number + 3
z = add_three
print(z) |
58f7f2323b1a1a384faf63318b00dd5baef44965 | VitaliyKrytsun/Student | /Student4Week/Decorator.py | 661 | 3.953125 | 4 | def construct_dict(S):
char_dict = {} # char_dict - словник символів
for c in S:
if c not in char_dict:
char_dict[c] = S.count(c)
return char_dict
def find_most_popular_char(D):
max_char = '' # найпопулярніший символ
max_num = 0 # кількість його входжень
for c, num in D.item... |
c36b90329a86ec512d5e8a702bfe6bb883c011a3 | eandrew45/Cracking_the_coding_interview_python | /Chapter_3-Queues-and_stacks/3.5.py | 1,693 | 4 | 4 | '''
QUESTION:
Sort Stack:
Write a program to sort a stack such that
the smallest items are on the top. You can use an additional temporary stack,
but you may not copy the elements into any other data structure
(such as an array). The stack supports the following operations: push, pop, peek, and isEmpty.
SOLUTION:... |
70740eab4349129f07a229cd7f28b9a01471c2b6 | eandrew45/Cracking_the_coding_interview_python | /Chapter_1-strings-arrays-and-strings/1.3.py | 771 | 3.78125 | 4 | '''
QUESTION:
URLify: Write a method to replace all spaces in a string with '%20'.
You may assume that the string has sufficient space at the end to hold
the additional characters, and that you are given the "true" length of the string.
SOLUTION 1:
If allowed to use inbuilt split function in python
'''
####### ... |
4a25a4069fa3d15466dc0aa43dd48322cc53097a | eandrew45/Cracking_the_coding_interview_python | /Chapter_4-trees-and-graphs/bidirectional_search.py | 1,394 | 4 | 4 | # given two nodes in a graph with the intention of finding if there exists a path between the two
# we will perform two BFS instead of one keeping track of visited nodes and then returning
# true if we find any common child or the other node from the other
def biderectional_search(node1, node2):
visited_nodes1 = s... |
12f62b73cd58bde4a8d3c974c41273b1721234d2 | eandrew45/Cracking_the_coding_interview_python | /Chapter_2-LinkedLists/2.2.py | 951 | 3.90625 | 4 | '''
QUESTION:
Return Kth to Last:
Implement an algorithm to find the kth to last element of a singly linked list.
SOLUTION:
Have 2 pointers that will first extend the length of K between them then iterate
as usual till the end and return the Kth element
we make use of the linked list implementation found in this ve... |
a88aff5efcb9004e5cebd918a9dc8dab8c4fbe74 | toBeOfUse/MitchBot | /db/queries.py | 10,238 | 3.59375 | 4 | """
Provides functions to access the word frequency and wiktionary words databases (which
are in SQLite and bespoke trie database forms, respectively) as well as the nicknames
in db/nicknames.json and poetry from text/poetry.txt. The RandomNoRepeats class
defined here is also useful in general. Note: the paths within t... |
b7c949c633a41a603ef8f249ab66d7842d0ce4cf | Drogarot/the-base-puthon | /dz5.py | 599 | 4.03125 | 4 | revenue = int(input('Введите сумму выручки: '))
costs = int(input('Введите сумму издержек: '))
if revenue > costs:
profitability = revenue - costs
rent = profitability / revenue
print(f'Ваша фирма работает в прибыль на {profitability} ')
worker = int(input('Сколько сотрудников в фирме: '))
pr... |
7a3465855bc46764912722ccf1dc94daa4773ea7 | vinsmokemau/ArtificialIntelligence | /perceptron.py | 1,095 | 3.59375 | 4 | """Perceptron with Hebb rules."""
import numpy as np
import neurolab as nl
import matplotlib.pyplot as plt
hardlim = nl.trans.HardLim()
# No conditional
p0 = 0
w0 = 1
# Conditional
p = 1
w = 0
b = -0.5
alpha = 0.1 # Learning Factor
gamma = 0.2 # Forgetting Factor
for epoch in range(150):
n = (w0 * p0) + (w *... |
b51bf638b4f3e676c4588b4641a3ba6ccfdaf1f7 | perlh/Algorithm | /回溯法/n皇后问题.py | 1,217 | 3.75 | 4 | #! /usr/bin/env python3
num=0
def eight_queen(arr,finish_line=0):
if finish_line == len(arr): #如果放置皇后成功的行数与数组中的元素个数一致(即棋盘的行数)则认为完成了一种摆法
global num #将上边定义的num定义为全局变量 这样才能在后边对其进行自加操作
num+=1
print("第%s种摆法:" % num)
for i in range(n):
... |
1ed697f09ffeb18065905166f740326b3648a26d | perlh/Algorithm | /循环赛日常表.py | 596 | 3.578125 | 4 | def port(A,n):
if n==1:#矩阵的长度为1, 这时候给最左上角的单元格赋值为1
A[0][0]=1
return
port(A,n//2)
m = n//2
for i in range(m):
for j in range(m):
A[i][j + m] = A[i][j] + m #右上角的值 = 左上角的值 + 矩阵长度的一半
A[i + m][j] = A[i][j + m] #右下角的值 = 左上角的值
A[i + m][j + m]... |
6b81431a6ba94651dfba75ea254458a9cd846a0c | ferbjava/firstPythonApp | /ticTacToe/ticTacToe_test.py | 976 | 3.53125 | 4 | import unittest
from ticTacToeGame import TicTacToeGame
class TicTacToeGameTest(unittest.TestCase):
def setUp(self):
self.gra = TicTacToeGame()
class TestGame(TicTacToeGameTest):
def test_czy_w_planszy_01(self):
ruch = "A1"
self.assertTrue(self.gra.sprawdzCzyWPlanszy(ruch))
def ... |
1f10a84c5deda29ee3a533bc0c643bb99a267892 | ShanjinurIslam/Machine-Learning-with-Python | /Basic Python/formatted_strings.py | 374 | 3.953125 | 4 | # Formatted Strings
userName = 'shanjinur'
lastLogin = 'Yesterday'
# Method 1
print(f'Welcome back {userName}, your last Login was on {lastLogin}') # f tells python it is a formatted string
# Method 2
print('Log out, {} ?'.format(userName))
# Method 3
print('good bye, {user}'.format(user=userName))
print('Copyr... |
c1f3fb921f1524ebec5eda16af7d47f0bb60213b | ShanjinurIslam/Machine-Learning-with-Python | /Basic Python/strings.py | 217 | 3.75 | 4 | text = 'Hello User!'
print(text)
print(type(text))
long_string = '''
Well I am broke!
O O
---
'''
print(long_string)
first_name = 'John'
last_name = 'Doe'
full_name = first_name + ' ' + last_name;
print(full_name) |
b39280b921fb1d8fd9f69425fdd506b3ef480852 | fadhil-amree/Tugas-Pendahuluan-Pengkom | /H03.21100924.01.py | 392 | 3.515625 | 4 | # NIM / Nama : Muhammad Fadhil Amri
# Tanggal : Minggu, 18 April 2021
# Deskripsi : Program menerima N buah bilangan dan menuliskan kembali bilangan tersebut lalu dibalik
N = int(input('Masukkan nilai N = '))
Z = []
i = 0
while i < N :
A = int(input())
Z.append(A)
i += 1
print('Ha... |
1ddb94edc520ff8d015442d83a32f9621dd82c53 | terrenjpeterson/python-pong | /pong.py | 4,830 | 4.03125 | 4 | # Implementation of classic arcade game Pong
import simplegui
import random
# initialize globals - pos and vel encode vertical info for paddles
WIDTH = 600
HEIGHT = 400
BALL_RADIUS = 20
PAD_WIDTH = 8
PAD_HEIGHT = 80
PAD_SPEED = 4
HALF_PAD_WIDTH = PAD_WIDTH / 2
HALF_PAD_HEIGHT = PAD_HEIGHT / 2
# this sets wher... |
06e2cabf49068064f1688af4cf6a9082005fc1ca | ss9036726/Python | /decoDemo.py | 815 | 3.578125 | 4 | class Harley():
# Creating Constructor
def __init__(self,**kwargs):
self.features = kwargs
# Creating Setter Method
def setFeatures(self , k , v):
self.features[k] = v
# Createing Getter Method
def getFeatures(self , k):
return self.features.get(k , None)
@... |
22d444b8a90810af321f9cdd76bcb15f5df1f79f | alanrafaelpereyra/desafios | /arraydiff.py | 840 | 3.921875 | 4 | # Your goal in this kata is to implement a difference function,
# which subtracts one list from another and returns the result.
# It should remove all values from list a, which are present in list b.
# Test.describe("Basic Tests")
# Test.assert_equals(array_diff([1,2], [1]), [2], "a was [1,2], b was [1], expected [2]... |
5b56d05467facac57b20c4421d41fefb06f2ee95 | tristan-paul/lambdata | /lambdata_trista/df_utils.py | 1,350 | 3.65625 | 4 | """
utility functions for working with dataframes.
"""
import pandas as pd
import numpy as np
import os
"""import, load dataset from UCI with datetime, string and int columns"""
os.system("wget http://archive.ics.uci.edu/ml/machine-learning-databases/00482/dataset.zip")
os.system("unzip dataset.zip")
TEST_DF = pd.r... |
d49fc48d150c8a92a64af9e1b96dbcb21e1a61bb | npoet/wikipedia-game | /utils/links.py | 2,983 | 3.875 | 4 | #!/usr/bin/python3
# links.py
# written by Nicholas Poet on 2.26.2020
import requests
URL = "https://en.wikipedia.org/w/api.php"
def get_page_name(req_page):
""" Gets official page name from redirect (if applicable) for
search purposes
Args:
req_page (str): The (incomplete) title of the requested Wikipedia p... |
1357db17882299259bd088df9f5f7fa1c0254c6a | 21-Century-RavenRen/TETRIS-War-of-the-Fandoms | /programingworksheet | 1,483 | 3.765625 | 4 | '''
Author:Spectraljuice
'''
#1
def g(a,b):
c = a+b
return c
print(g(4,5))
print(g(5.2,9.8))
print(g("testing","script"))
print(g(4,"hello"))
#type out the output of the above script:
9
15.0
"testingscript"
ERROR
#2.
def b(c):
for x in range(c):
print(c)
print(b(4))
print(b("h"))
#type out the ... |
01f7fb905902888eced691a48ecab495a5c19791 | Pittawat2542/python-text-to-morse | /main.py | 1,121 | 3.984375 | 4 | from art import logo
from converter import Converter
def display_title():
print(logo)
print('Welcome to text-to-morse converter program.')
print('Our program currently only support English alphanumeric without symbols and special characters.')
print('NOTE: Any unavailable characters will convert to <O... |
08b101bb77ab9d3507caee0097d02cd4d8885fab | SuperTapood/Maze-Generator | /main.py | 1,713 | 3.828125 | 4 | """
1. Choose the initial cell, mark it as visited and push it to the stack
2. While the stack is not empty
1. Pop a cell from the stack and make it a current cell
2. If the current cell has any neighbours which have not been visited
1. Push the current cell to the stack
2. Choose one of the unvisited neighbours
... |
36cb1676388642c2204adc402fc522217de572cf | vfcrawler/20191015 | /06_03.py | 227 | 3.890625 | 4 | def duplicateList(alist):
ret = []
for li in alist:
if li not in ret:
ret.append(li)
return ret
if __name__ == '__main__':
alist = [1, 2, 2, 3, 4, 4, 6, 7, 7]
print(duplicateList(alist)) |
acbb36c90361508be15d0df36c2cdafe8fc906f2 | vfcrawler/20191015 | /06-01.py | 210 | 3.625 | 4 | def duplicateList(alist):
keys = {}
keys = keys.fromkeys(alist)
ret = list(keys)
return ret
if __name__ == '__main__':
alist = [1, 2, 2, 3, 4, 4, 6, 7, 7]
print(duplicateList(alist))
|
cce892e78f25d8c59bc2c4850d9bb9b82deabf00 | sm-injamam/Basic-py-code | /pycode/Inheritance.py | 1,279 | 3.984375 | 4 | class phone:
def call(self):
print("you can't call")
def Message(self):
print("Pls text me")
class Aphone(phone): # inherit phone class
# message,call
def call(self):
super().call()
print("you can now call")
def video_call(self):
print("p... |
3bea59d9a4ae6641e01dfe5c198cd44676bae5f8 | JHa568/OpenCV-learning-workspace | /OpenCV/image_processing_methods/Edge_Detection.py | 450 | 3.921875 | 4 | import cv2 as cv
# Edge detection is outlining the edges in the image
# such that the edges is the steep change in colour gradient
class Edge_Detection():
# OpenCV
def canny_detect(self, img):
# @param - image, high bound, low bound
# Doc for Canny Algorithm is:
# https://docs.opencv... |
d14ee49ee410a7ce7c495810d26668c3e0b453c4 | Congo-Kid/python-challenge | /PyPoll/main.py | 3,139 | 3.828125 | 4 | #import modules
import csv
import os
file=os.path.join('election_data.csv')
#open csv file with the election data
with open(file,'r') as csvfile:
#read file
csvread=csv.reader(open('election_data.csv'))
#create dictionary to hold voterIDs correlated with the candidate they voted for
voteInfo = {}
... |
8abba3ee8dee485fb0154d060c74d516dd4ca296 | ewarlock/ITEC-2905-80-Project-01 | /RefactorQuiz.py | 4,927 | 4.40625 | 4 | """ This program offers the user a quiz. The quiz can be selected based on several different categories. At the end of the quiz, the user is scored based on how many questions they got right. They receive a special message if they got all of the questions right."""
#quiz questions and answers sorted by category
catego... |
b69fd238fe58207e2fc2f8883c032cf2ca69908f | vidit-aggarwal/student-management-system | /student_database.py | 7,760 | 3.828125 | 4 | import tkinter as tk
import sqlite3
from tkinter import ttk, messagebox
con = sqlite3.connect("university.db")
con.execute("CREATE TABLE IF NOT EXISTS student(name TEXT, branch TEXT, section TEXT, roll INTEGER, cgpa FLOAT);")
def insert_data(name, branch, section, roll, cgpa):
conn = sqlite3.connect("university.... |
54ad1438359c861d10e728bea6baadc29fb4f997 | RafaelLua13/URI | /1002.py | 435 | 4.1875 | 4 |
## Código ##
r = float(input())
a = (r * r) * 3.14159
print("A=%0.4f" %a)
## Código comentado ##
# r = float(input()) # Definição da variável 'r' como um valor float (Não necessáriamente inteiro).
# a = (r * r) * 3.14159 # Cálculo da área do circulo multiplicando r^2 (r**2) pelo valor de Pi (3... |
e20fb408dabc5bbb4384205992a7092ad3885c03 | neuml/codequestion | /src/python/codequestion/tokenizer.py | 1,504 | 3.8125 | 4 | """
Tokenizer module
"""
import re
import string
class Tokenizer:
"""
Text tokenization methods
"""
# Use standard python punctuation chars but allow tokens to end in # (to allow c#, f#) and + to allow (c++ g++)
PUNCTUATION = string.punctuation.replace("#", "").replace("+", "")
# fmt: off
... |
b9214ec1262f92170de8faa2930bad0a00c5b135 | kertureinsalu/Koolitus | /Tund 2/Tsükkel5.py | 675 | 3.6875 | 4 | import random
nimi = input("Sisesta oma nimi")
nimekiri = []
punktid = 0
kontroll = True
while kontroll == True:
punktid = 0
for x in range (1):
x = random.randint(1, 10)
y = random.randint(1, 10)
tehe = x*y
print (x, "*", y)
sisestus = int(input("Vastus"))
... |
4df2e50f5ae17467fc0da50b87039ed4ab512d6a | kertureinsalu/Koolitus | /ELSEIF.py | 422 | 3.859375 | 4 | sisestus = input("Kas ruut või kolmnurk?")
if sisestus == "ruut":
number = float(input("sisesta ruudu külg"))
pindala = number**2
print (pindala)
elif sisestus == "kolmnurk":
number1 = float(input("sisesta kolmnurga esimene külg"))
number2 = float(input("sisesta kolmnurga teine külg"))
p... |
1926dd0c796b44fe1c079b4cb94d6bc7b6bc9b80 | huot3000/tictactoe-programs | /TicTacToe.py | 3,505 | 3.9375 | 4 | # Two-Player Tic Tac Toe Game
# Setup
import time
import random
board = [' ',' ',' ',' ',' ',' ',' ',' ',' ',' ']
# Drawing the board
def drawBoard():
print('-----------')
print(' ' + board[1] + ' | ' + board[2] + ' | ' + board[3] + ' ')
print('-----------')
print(' ' + board[4] + ' | ' + board[5]... |
6955ff9afaf174952c29a5eebc4013d50850e8dd | ashleycampion/IrisDataSetProject | /filesNotUsed/createDataFrame1.py | 3,455 | 4 | 4 | import pandas as pd
# read in the csv file and assign it to a variable
# (it is now a pandas dataframe object)
df = pd.read_csv("irisDataSet.csv")
# these variables will store the indices of the first
# versicolor and virginicas
versicolor = 0
virginica = 0
# this function finds the indexes of the first versicolor
#... |
c389f4d3f4dedc6e60cbf6804973a09851811fab | IsmailCS55/Ismailsland | /aim_lab.py | 1,708 | 3.65625 | 4 |
# Imports
import pygame
import math # for checking for collisions with the mouse and the circle
import random
# Define the screen the screen and initialize pygame
pygame.init()
width = 1200
height = 500
display = pygame.display.set_mode((width, height))
# Colors
black = (0, 0, 0)
white = (255, 255, 255)
purple = ... |
6b62004059198522e6c882682d5c1634de5fda1a | PengZhigang/leetcode | /python_version/two_sum/main.py | 489 | 3.515625 | 4 | class Solution:
def twoSum(self, nums: [int], target: int) -> [int]:
res = []
for i in range(len(nums)):
for j in range(i+1, len(nums)):
if (nums[i] + nums[j] == target):
res.append(i)
res.append(j)
break
r... |
b3ad0e17600add2caba0246412e7d07af321b062 | jcvirulant/my_repository | /league_builder.py | 3,506 | 3.875 | 4 | if __name__ == "__main__":
# Soccer League Builder
# create three teams - Dragons, Sharks, and Raptors
def league_builder():
import csv
assigned = list()
dragons = list()
raptors = list()
sharks = list()
teams = [{'Team' : 'Dragons'}, {'Team' : 'R... |
23df929eceeb93d0890346f844b44c0bf05835c8 | pkostereva/ES_Python | /LSN_6/DZ_6.6.py | 169 | 3.53125 | 4 | a = str(input('Введите число: '))
b = list(a)
s = 0
for i in range(len(b)):
if int(b[i]) % 2 != 0:
s = s + pow(int(b[i]), 2)
else:
print(s)
|
890a8f6853bea0506209ff02d78c73af441e49ec | pkostereva/ES_Python | /LSN_10/DZ_10.1.py | 1,301 | 3.96875 | 4 | class Human:
def __init__(self, new_name):
self._name = new_name
print(f'Родился человек с именем {self._name}')
def growing(self, years):
print(f' {self._name} отмечает день рождения! Ему {years}! ')
def eating(self):
print(f' {self._name} ест')
def sleeping(self):
... |
eff7226805b52f7c670fe124d44e8a368a27de17 | pkostereva/ES_Python | /LSN_9/DZ_9.2.py | 1,037 | 3.65625 | 4 | from pprint import pprint
import json
print('''
1. Добавить задачу.
2. Вывести список задач.
3. Выход.
''')
n=0
while True:
n=input('Выберете пункт: ')
if n.isnumeric():
if int(n) == 1:
print('\n')
a=input('Задача: ')
b=input('Категория: ')
c=input('Время:... |
e1307286aa7b3ee337d9a4640bea4c19e6ee50d1 | pkostereva/ES_Python | /LSN_3/DZ_3.2.py | 271 | 3.625 | 4 | import random
b = random.randint(1, 4)
a = int(input('Введите число: '))
if a == b:
print('Победа!')
else:
if b>a:
print('Введенное число меньше')
else:
print('Введенное число больше')
|
c189368d1871caa3510c42b1d4e23a79d0e61617 | henrihakkarainen/projects | /Python_I/round2_task7.py | 1,680 | 4.03125 | 4 | # 1
'''
from sys import argv
alphabet = "abcdefghijklmnopqrstuvwxyz"
def encrypt(text, cipher):
res = []
for c in text:
pos = alphabet.find(c)
if pos >= 0:
res.append(cipher[pos])
else:
res.append(c)
return "".join(res)
def decrypt(text, cipher):
res = []
for c in text:
pos = cipher.find(c)
i... |
41ee138a23ad4a5710ccda0f7654ad98b3825539 | henrihakkarainen/projects | /Python_I/cmd_parameters.py | 453 | 3.71875 | 4 | from sys import argv
'''
# Osa yksi
for i in range(len(argv)-1):
print(str(argv.index(argv[i+1])) + ": " + argv[i+1] + " (length: " + str(len(argv[i+1])) + ")")
# Osa kaksi
arg_list = argv
argv.sort()
for i in range(len(argv)-1):
print(str(argv[i+1]))
print()
argv.reverse()
for i in range(len(argv)-1):
... |
03079653ad9450ca7e424e3bf8341c220ac91290 | henrihakkarainen/projects | /Python_I/round2_task3.py | 1,042 | 3.765625 | 4 | from sys import argv
def s_row(index):
s_row = ["#", "", "|", "" , "|", "" , "#" , "" , "|" , ""
, "|", "" , "#" , "" , "|" , "" , "|" , "" , "#"]
for i in range(1, len(s_row), 2):
s_row[i] = sudoku_list[(index)]
index += 1
print(" ".join(s_row))
return index
s = "".join(argv[1:])
sudoku_list = []
in... |
ab0beacd151db90f8cb0317de5fe9049c0d2a71c | henrihakkarainen/projects | /Python_I/lecture3.py | 1,625 | 4 | 4 | # Exercise one
'''
def printDecision(person):
print(f"You are a {person}")
age = int(input("Enter a age: "))
printDecision("Adult" if age >= 18 else ("Minor" if age >= 12 else "Child"))
# if age >= 18:
# person = "Adult"
# else:
# person = "Minor"
'''
# Exercise two
'''
p1 = (-1.5, 3)
x, y = p1
print(x, y)
... |
f98bd923a2f9ff3483a34c06a324997d0b847d6c | colepjohn/Face-Detection | /face_detection.py | 1,014 | 3.609375 | 4 | import cv2
# Load some pre-trained data on face tutorials from opencv (haar cascade algorithm)
trained_face_data = cv2.CascadeClassifier( 'haarcascade_frontalface_default.xml' )
# Choose an image to detect faces in
# img = cv2.imread( 'headshot.png' )
# To capture video from webcam
webcam = cv2.VideoCapture... |
1d9404e895b7335725f471486e932088983754e3 | mahim007/complete-python | /OOP/Classmethods.py | 387 | 3.703125 | 4 | class MyClass:
name = 'mahim'
def __init__(self, result):
super().__init__()
self.result = result
@classmethod
def adding(cls, num1, num2):
print(cls.name)
return cls(num1 + num2)
@staticmethod
def find_square(num):
return num**2
example = MyClass... |
82b0d190385a0c0d193f13aa0354b735d2d1bfdb | mahim007/complete-python | /Python Basics 2/Enumerate.py | 149 | 3.921875 | 4 | for key, value in enumerate([1,2,3]):
print(key, value)
for item in enumerate(list(range(10))):
print(item)
print(f'{item[0]}{item[1]}') |
bedfef104105a0d4abfd5f7e74be05e7ac4b5779 | romapavelko01/Notebook | /task6.py | 1,503 | 4.0625 | 4 | from note import Notebook
from menu import Menu
print("\n" + 100*"-")
print("The dir() function for Notebook - shows all of the attributes and methods of an object")
print("dir() function for Notebook \n", dir(Notebook))
print("\n" + 100*"-")
print("isinstance() function - returns True if the object belongs to a specif... |
0c8b74e723e8afab15eb97b6085b472abc96211b | sumit-subedi/Advent-of-code-2020 | /day3.py | 214 | 3.5 | 4 | file = open('day3.txt', 'r')
string = file.read().split('\n')
total = 0
start = 0
right = 1
for i in string[::2]:
pos = int((start + right) % 31)
start = pos
if i[pos] == "#":
total += 1
print(total)
|
52e5bfc74f4a087b5f263e7c96729c6b32e96e3f | kalyaniandhare/selfCode | /pyclass.py | 629 | 3.859375 | 4 | class Employee:
count = 0
def __init__(self, name, salary):
self.name = name
self.salary = salary
Employee.count += 1
def getEmpCount(self):
print Employee.count
def getEmpInfo(self):
print "Info", self.name, self.salary
emp1 = Employee("kalyani", "75000"... |
0c1907cd6f5a16ff5394e76ed694f8b76054934b | kalyaniandhare/selfCode | /matrix.py | 1,944 | 3.515625 | 4 | import sys
import os
import copy
'''Complete the function below.'''
def check_horizontal(input1, output, count):
for input_string in input1:
string = ''.join(input_string)
if string == output:
count += 1
return count
def check_digonal(inp1, output, ip1_rows, count):
input_list... |
fdfcb0cbd4acea1b752849ff7179a4735820b2d7 | sbrj/Martino | /loja_v1.0.py | 2,619 | 4.03125 | 4 | #coding=Utf-8
# Dicionário com produtos a serem cadastrados e seus respectivos valores
produtos = {}
# Lista para definir indice nos produtos
index_list = []
def cadastrar():
'''
Função responsável por cadastrar produtos.
Pede que seja digitado nome e valor e então guarda em 'produtos'
'''
produto = ... |
6fb5f411a3d8fd121403c9830f95154b2712fd14 | andreichelariu92/Scraper | /src/python/autovit.py | 1,833 | 3.53125 | 4 | from bs4 import BeautifulSoup
import urllib
import re
import sys
from CarClass import Car
def get_cars(url,car_list,id):
"""function that parses the url using BeautifulSoup4
With the information from the site we construct a list of car objects"""
website=urllib.urlopen(url)
soup=BeautifulSoup(website.read()... |
02411b748a6d1a5e4efbadb7de5497e4df6496cc | damasofc/Analisis_algoritmos_Trabajos | /tarea1/aa1er.py | 499 | 3.578125 | 4 | import sys
import timeit
x = int(sys.argv[1])
def minMonedas(a):
falta = a
cantMonedas = 0
while falta != 0:
if falta - 10 >= 0:
cantMonedas += 1
falta -= 10
elif falta - 5 >= 0:
cantMonedas += 1
falta -= 5
else:
cantMoned... |
0d20c723e85b963227cfa907e35e7f4b3048a3f5 | cipollone/atarieyes | /atarieyes/features/genetic.py | 26,511 | 3.5625 | 4 | """Implementation of genetic algorithms.
Genetic algorithms are really different from other gradient-based methods.
I'll implement the custom training here, then cast this as a generic Model.
"""
from abc import abstractmethod
import math
import tensorflow as tf
from atarieyes.layers import make_layer
from atarieyes... |
c47d3da78b11081e3215228779f1f41124058ce8 | 8314home/pycodes | /Python_codes/ArtistsV3OOP.py | 4,215 | 4.3125 | 4 | class Song:
"""Class to represent a song
Attributes:
title (str): The title of the song
artist (Artist): An artist object representing the songs creator.
duration (int): The duration of the song in seconds. May be zero
"""
def __init__(self, title, artist, duration=0):
... |
61c6301f3ee6bff124e562de5d26f1a400ab570a | 8314home/pycodes | /DS_Algo/BST.py | 4,623 | 4.125 | 4 | class Node(object):
def __init__(self, data):
self.data = data
self.left_child = None
self.right_child = None
class BinarySearchTree(object):
def __init__(self):
self.root = None
# All operation will take O(log n) complexity if Tree is BALANCED - if unbalanced will take O(n) ... |
ecfb308b2c76c4684589f5987ff7039c4e7d96c4 | kozborn/python-the-hard-way | /Exercise16/ex16.py | 588 | 4.0625 | 4 | from sys import argv
script, filename = argv
print "We're going to erase %r" % filename
print "If you don't want that press CTRL+C (^C)."
print "If you want that press ENTER"
raw_input("?")
print "Opening the file ..."
target = open(filename, "w")
print "Truncating file, Goodbye data"
target.truncate()
print "Now I'm... |
20d8fac3666ebc4c18fc2c3074632bda39c69e65 | VimalKumarS/opecv-lab | /ck1.py | 1,292 | 3.546875 | 4 | import cv2
import matplotlib.pyplot as plt
import numpy as np
image = cv2.imread('maxresdefault.jpg')
print('This image is:', type(image),
' with dimensions:', image.shape)
image_copy = np.copy(image)
# Change color to RGB (from BGR)
image_copy = cv2.cvtColor(image_copy, cv2.COLOR_BGR2RGB)
# Display the image c... |
fe8c41771429b2f1a1f078cd414fc2a5751fa68c | kyung01/NeuralNetworkPractice00 | /dummy.py | 2,270 | 3.640625 | 4 |
def main():
gameBegin()
def printBoard(b):
data = [
[str(b[0]),str(b[1]),str(b[2])],
[str(b[3]),str(b[4]),str(b[5])],
[str(b[6]),str(b[7]),str(b[8])]
]
for row in data:
print("{:>20} {: >20} {:>20}".format(*row))
def switchPlayer():
global currentPlayer
if currentPlayer == X:
currentPlayer = O
elif... |
04252ca358958dc072a09b7f7ddd861e509d3629 | nphamilton/rl_library | /algorithms/abstract_algorithm.py | 2,120 | 3.6875 | 4 | """
File: abstract_algorithm.py
Author: Nathaniel Hamilton
Description:
Usage: This class should be inherited by each implemented algorithm class in order to enforce consistency.
"""
from abc import ABC, abstractmethod
class Algorithm(ABC):
"""
An algorithm is how an agent learns to perform a g... |
eb7a9c4b5477a795c60d5ad9e755e71ee233c87a | Carlobebeboy/MachineProb5_Python | /MP5.py | 624 | 3.71875 | 4 | import numpy as np
import matplotlib.pylab as plot
n = np.linspace(0,199,200)
s = input("Input your function, x(n):")
def x(n):
evaluate = eval(s)
return evaluate
for i in range(0,200):
if i==0:
y = (-1.5*x(n))+(2*x(n+1))-(0.5*x(n+2))
... |
04e5d73b444b80cc4b5a6cc1dd2665fbf6573297 | Garador/smallAdventureGamePython | /main.py | 4,762 | 3.828125 | 4 | import random
import re
from classes.room import Room
class Game:
finished = False
path = []
currentRoom = None
characterStatus = {
"leftRoom": False
}
def start(self):
print """
%s
You wake up in a strange place...
You don't have a memory of this place..... |
0fc8e658181ce92026372fd30cfd168798d00511 | fgksgf/TensorFlow-Toys | /02_TransferLearning/cache.py | 7,036 | 3.734375 | 4 | ########################################################################
#
# Cache-wrapper for a function or class.
#
# Save the result of calling a function or creating an object-instance
# to harddisk. This is used to persist the data so it can be reloaded
# very quickly and easily.
#
################################... |
1f848e8400a6ecfc1342116e24906206c8745fd2 | GDMane/Santubhau | /collectionsArrays/listOperations.py | 921 | 4.15625 | 4 |
print("Shree Swami Samarth")
print("Collections (array)")
gmList = ['ganesh', 'ganesh', 'gmList']#duplicate allowed
print(gmList[0])#single object print using index
print("--------------")
'''
gmList.reverse()
print(gmList)#reverce elements in original refrance
print("--------------")
'''
gmList[0]="myChange"
prin... |
1892d0e432d4163042ef6be24e8d0adbf134b788 | Basemera/trailapp | /app/modals.py | 4,733 | 3.71875 | 4 | from flask import session, request
from werkzeug.security import generate_password_hash
class User(object):
"""Create and store a user oblect"""
user_id = 0
users = {}
def __init__(self, Username, Email, Password, Password2):
"""initialize the object User"""
User.user_id += 1
sel... |
9d894e0a9fb15d74da36b257292edba422aff02c | nologon/P4E | /Course_Work/Assignments/assign2.3/calc_pay.py | 152 | 3.53125 | 4 | #!/usr/bin/python
inp = raw_input("Enter Hours: ")
hours = int(hrs)
inp = raw_input("Enter Rate: ")
frate = float(rate)
pay = hours * frate
print pay
|
907d4ff001d7eb020fcf802c1498bbb1af79a8ad | nologon/P4E | /P4I/Chapter3/3.3score.py | 309 | 3.953125 | 4 | #!/usr/bin/python
while True:
try:
score =float(raw_input('Enter a Score: '))
break
except:
print "Bad Score."
if score >= 1:
print 'wrong score'
elif score >= 0.9 and score < 1:
print 'A'
elif score >= 0.8:
print 'B'
elif score >= 0.7:
print 'C'
elif score >= 0.6:
print 'D'
else:
print 'F'
|
a2eb84adef8415c00e35dfaaece54ccf39e86a6a | pyhero/player | /amazing_pen.py | 754 | 4.0625 | 4 | import turtle
turtle.bgcolor('black')
def rainbow():
pen = turtle.Pen()
pen.pensize('1')
sides = 7
colors = ['red', 'pink', 'yellow', 'green', 'cyan', 'blue', 'purple']
x = 0
while True:
pen.pencolor(colors[x % sides])
pen.forward(x * 3 / sides + x)
pen.left(360 / side... |
d8d0e70cfb11d1044ea2192cc3d7fa69c1f090cd | BMEJSchmitz/Pizza | /app.py | 5,848 | 3.53125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Tue Oct 5 14:36:02 2021
@author: Aditi Mishra
"""
from flask import Flask, make_response, request, render_template
app = Flask(__name__)
from model import Pizza, Toppings, drinks, desserts, Customer, Order
@app.route("/Pizza/<pizza_id>")
def get_Pizza(pizza_id: int... |
fa58f3870b7861a813ca09b5f99952e4d52b23c0 | rknyx/algorithms_and_data_structures | /traversal.py | 1,462 | 3.515625 | 4 | #python3
import sys
from collections import deque as deq
class TreeNode():
def __init__(self, inf):
[self._value, self._left, self._right] = inf
self._left = None if self._left == -1 else self._left
self._right = None if self._right == -1 else self._right
def set_data(self, data):
self._data = data
def ... |
b324be91c4ad3381cbc67bcbb0dd7c4b550b394d | JVSeidel/getbib | /lib/utils.py | 2,927 | 3.90625 | 4 | def input_error():
import sys
print(' Call this function with author surname, and optionally a start year and end year respectively.')
print(' If using getbib, optionally you may also specify a bibfile to which the reference is output.')
print(' The following are examples of valid input:'... |
226314c785f412b879fc23e757a46d63648bc831 | shantanu092/Sample-Codes-in-Python | /Python/py2.py | 2,248 | 3.609375 | 4 |
>
>>> a+b
121
>>> print(a,b)
54 67
>>> x = int(input())
34343
>>> x
34343
>>> y
Traceback (most recent call last):
File "<pyshell#17>", line 1, in <module>
y
NameError: name 'y' is not defined
>>> x = int(input())
34234.234
Traceback (most recent call last):
File "<pyshell#18>", line 1, in <m... |
29bb5663b7d8fb57dc06480f2ec0043f8800de41 | Questionm/Zhuo_Chen_test | /QA-line-overlap.py | 519 | 3.671875 | 4 | #Question A
#code
class Solution(object):
# @param {list} line1
# @param {list} line2
# @return {bool}
def isLineOverlap(self, line1, line2):
A, B = line1[0], line1[1]
E, F = line2[0], line2[1]
if A > F or B < E:
return False
return True
... |
ed6c788c404377b04e8e08707a3e789dfe456845 | LZD962/cp_1404_practical | /prac_04/quick_picks.py | 396 | 3.8125 | 4 | import random
MAX = 45
MIN = 1
NUMS = 6
num = int(input("How many quick picks? "))
for i in range(num):
nums = []
for j in range(NUMS):
while len(nums) < 6:
x = random.randint(MIN, MAX)
if x not in nums:
nums.append(x)
print("{:2} {:2} {:2} {:2... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.