blob_id stringlengths 40 40 | repo_name stringlengths 5 119 | path stringlengths 2 424 | length_bytes int64 36 888k | score float64 3.5 5.22 | int_score int64 4 5 | text stringlengths 27 888k |
|---|---|---|---|---|---|---|
66c5c7f9880f28f067a6c2b227e3e906409a0e3c | fabianfroding/dat455-python1-chalmers | /exam-prep/futuresalary.py | 461 | 3.765625 | 4 |
def main():
print("Welcome to the Future Salary Predictor.")
current = eval(input("Enter your current salary: "))
increment = eval(input("Enter the yearly precentage increase: "))
years = eval(input("Enter the number of years: "))
future = current
for i in range (1, years + 1):
futu... |
cb6456bea978e1c3473146838aea2c394c52c90e | uran001/Small_Projects | /Hot_Potato_Game/hot_potato_spicy.py | 1,193 | 3.875 | 4 |
from queue import ArrayQueue
import random
def hot_potato_spicy(name_list, num):
"""
Simulates the Hot potato game "spiced up" with lives and randomness
:param name_list: a list containing the name of the participants and their number of lives
:param num: the counting constant (e.g., the length of e... |
f568d87083e0759625365c2bb2e0c16416ec0d09 | lingxiaodshz/Python | /Py01/day06/NumpyTest02.py | 2,799 | 3.59375 | 4 | import numpy as np
array = np.array([[[1, 2, 3],
[2, 5, 8]]], dtype=int)
# 基本属性
print("======================================")
print(array.ndim) # 维数
print(array.shape) # 行列
print(array.size) # 元素个数
# 创建矩阵
print("======================================")
zeroArray = np.zeros((3, 4)) # 生成3行4列的零... |
52450a0f67a851b92ba64c53aeff719fec4aa946 | singham3/python-programs | /lalit.py | 151 | 3.765625 | 4 | a,b=map(int,input("Enter Two number:").split())
print("Value of a=",a,"b=",b,"Before swapping")
a,b=b,a
print("Value of a=",a,"b=",b,"After swapping")
|
96025a84fa050ecd7202e6ac9a27576ee56a8ad0 | joelwitherspoon/PythonCrashCourse | /Python10-10CommonWords.py | 459 | 3.578125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Wed Feb 19 15:53:48 2020
@author: jwitherspoon
"""
def Common_Words(filename,word):
try:
with open(filename) as f_obj:
contents = f_obj.read()
except FileNotFoundError:
msg = "Sorry the "+filename+" does not exist."
print(msg)
... |
170c6f8c0785db3cafd6000f731984c9f37be9fb | croach/natureofcode.py | /introduction/monte_carlo_distribution.py | 1,551 | 3.953125 | 4 | from p5 import *
size(200, 200)
vals = [0] * width # Array to count how often a random number is picked
norms = [0] * width # Normalized version of above
def draw():
background(100)
# Pick a random number between 0 and 1 based on custom probability function
n = montecarlo()
# What spot in the... |
1d79dcf4f1926948e7879282d6860f5dcabf791d | acetaxxxx/LeetCode | /138. Copy List with Random Pointer/LC138.py | 1,372 | 3.78125 | 4 | """
# Definition for a Node.
class Node:
def __init__(self, x: int, next: 'Node' = None, random: 'Node' = None):
self.val = int(x)
self.next = next
self.random = random
"""
class Node:
def __init__(self, x: int, next: 'Node' = None, random: 'Node' = None):
self.val = int(x)
... |
bbd2c5d3fe9b86d927d5674099d5f7e97b57d742 | johnsila/Python-Strings | /stringOperators.py | 285 | 4.03125 | 4 | #string operators
print("string operators")
a="hello"
b="world"
#concatination
print("1.",a+b)
#print a 5times
print("2.",a*5)
#bool. is there h in a
print("3.",'h'in a)
#bool. is there m in a
print("4.",'m'in a)
#bool. is x not in a
print("5.",'x'not in a)
|
87cb712a4b5a3c4e6369fb97bde98b2f56705206 | JiahuiQiu/Python-Learning | /ZJU-Python/CH3/CH3-16.py | 608 | 3.90625 | 4 | # -*- coding: utf-8 -*-
"""
删除字符
输入一个字符串 str,再输入要删除字符 c,大小写不区分,
将字符串 str 中出现的所有字符 c 删除。
输入格式:
在第一行中输入一行字符 在第二行输入待删除的字符
输出格式:
在一行中输出删除后的字符串
输入样例:
在这里给出一组输入。例如:
Bee
E
输出样例:
在这里给出相应的输出。例如:
result: B
"""
str = input().strip()
c = input().strip()
print("result:", str.replace(c.up... |
53b5d18bcd181c915cbddfacc01b70e6f6ce6386 | skhortiuk/Jimmy | /jimmy/sensors/base.py | 402 | 3.578125 | 4 | from abc import abstractmethod, ABC
class SensorData:
"""Wrapper for sensor results
"""
pass
class BaseSensor(ABC):
@abstractmethod
def connect(self, timeout: int):
pass
@abstractmethod
def disconnect(self):
pass
@abstractmethod
def data_ready(self) -> bool:
... |
420b30818492b595f4230639cfcc9d891d9e1241 | ankitmazumder/executeoncommand | /17_generators.py | 958 | 3.765625 | 4 | # Normal method
import memory_profiler
def generate_even_squares(numbers):
even_list = []
for num in numbers:
if num % 2 == 0:
even_list.append(num*num)
return even_list
m1 = memory_profiler.memory_usage()
es = generate_even_squares(range(30000000))
counter=0
for x in es:
if coun... |
25a4fcf1426de82724259bf1c3cb6146a40d343d | Rakshy/coding | /treesandgraphs/binarytree.py | 4,213 | 4.1875 | 4 | '''implement a binary tree'''
class node():
def __init__(self,d):
self.data=d
self.left=None
self.right=None
def get_data(self):
return self.data
def set_data(self,d):
self.data=d
def get_left(self):
return self.left
def get_right(self):
return... |
c4ba7a6cfeb472d5f37492c35878f650f5218f64 | makerlindsay/mathcalculator | /calculator2.py | 735 | 3.984375 | 4 | def add(num1, num2):
return num1 + num2
# print add(4,5)
def subtract(num1, num2):
return num1 - num2
# print subtract(1,2)
def multiply(num1, num2):
return num1 * num2
# print multiply(1,2)
def divide(num1, num2):
return num1 / num2
# print divide(1,2)
def modulo(num1, num2):
return num1% num2
# print modulo(... |
2070c6ab17ccad821fef11e57985d74b63480f66 | MogeWorkForce/data-science-from-scratch | /stats/chapter_5/stats_formula.py | 1,864 | 3.8125 | 4 | # -*- coding: utf-8 -*-
from __future__ import absolute_import, unicode_literals, division
import math
from collections import Counter
from ..chapter_4.vectors import sum_of_squares, dot
def mean(items):
return sum(items) / len(items)
def median(items):
items_sorted = sorted(items)
n = len(items)
... |
cb5202d03a93dc04de1d4c864c8413707e3094a5 | amymhaddad/python_workout | /ch_2/indexes_and_slices/more_indexes_and_slices.py | 1,285 | 4.375 | 4 | # Swap the first element of a list with the last, the second with the second-to-last, and so forth —
# so that the list [10, 20, 30, 40, 50] becomes [50, 40, 30, 20, 10].
list1 = [10, 20, 30, 40, 50]
# Option 1
list1.reverse()
print(list1)
# Option 2
list1[:] = list1[::-1]
print(list1)
# Given a list of integers m... |
7e2ff5bbb6406ef04057133a318b0f6bfc7c2841 | RashiniKaweesha/Repo-Excluded-From-HacktoberFest-2021 | /codes/pythonXmysql.py | 1,426 | 3.796875 | 4 | #################################
## Connect python with mysql
## Requirements:
## Install MySql workbench: https://dev.mysql.com/downloads/workbench/
## create a database/schema called "test"
## Run this script to connect to that mysql server
#################################
from getpass import getpass
from mysql.co... |
cf5f7ecbe8d4523da95fec4bed44a85bc8de181b | nonameP765/back-joon | /2019-03/03-01/6603.py | 613 | 3.515625 | 4 | # 깊이 위주 서치
def dfs(lis, index):
# 남은 배열의 길이가 6번을 채울정도로 길지 않으면
if 6 - len(lis) > len(a) - index:
return
# 만약 길이가 6이면
if len(lis) == 6:
print(' '.join(lis))
return
# 배열 복사
tmp = lis[:]
tmp.append(a[index])
# 현재값 추가해서 넘기고
dfs(tmp, index + 1)
# 현재값 안추가해서 넘기고
... |
82b129a5289c75f6a1232529858a75a6bc269a53 | piyushghate/Note-app-using-Python | /app.py | 360 | 3.765625 | 4 | from notes import *
print('Starting Note App');
userInput = input('What will you like to do? ');
print('Performing '+userInput+' operation!');
if (userInput == 'add'):
addNote();
elif (userInput == 'list'):
listNote();
elif (userInput == 'remove'):
removeNote();
elif (userInput == 'read'):
readNote()... |
d2903729e0f3273a5830fd5df7daf43587b6342e | number09/atcoder | /abc043-b.py | 168 | 3.625 | 4 | s = input()
result = list()
for w in s:
if w == "B":
if len(result):
result.pop()
else:
result.append(w)
print("".join(result))
|
487be66979a27a8c26a01a39c43c257089ba5648 | gabsabreu/cursoemvideo-python | /aula07d10.py | 268 | 3.9375 | 4 | #Crie um programa que leia quanto dinheiro uma pessoa tem na carteira e mostre quantos dólares ela pode comprar.
r = int(input('Quantos reais você tem na carteira? R$'))
#considerando US$ 1,00 = R$3,27
d = r / 3.27
print('Você pode comprar US${:.2f}'.format(d)) |
bb17f165574b0c1da988916ef2dc4b910668a84a | dcmikki/content-python-for-sys-admins | /bin/exercise-elif-improved | 424 | 3.703125 | 4 | #!/usr/bin/env python3.6
user = { 'admin': True, 'active': True, 'name': 'FERNANDO' }
prefix = f"{user['name']}:\t "
if user['admin'] and user['active']:
prefix += "(ACTIVE) - (ADMIN)"
elif user['admin']:
prefix += "(ADMIN)"
elif user['active']:
prefix += "(ACTIVE)"
elif user['name']:
prefix += "No... |
1777c4d8f62987f8235b80c225a36bdb771a8264 | Mrzhoug/Python | /String.py | 1,444 | 3.890625 | 4 | # -*- coding: utf-8 -*-
#学习String
print 1,r'C:\Python\name' #\n会被认定为转义字符 加上r会按照原始字符串输出
print 2,'''\
Usage: thingy [OPTIONS]
-h Display this usage message
-H hostname Hostname to connect to
''' #加上\号将不会输出第一行 (示例中第一个会输出换行)
print 3,3 * 'un' + 'ium' #输出3次‘un’然后和‘ium’连... |
4c906280a2a31049a0ef7da2c33adc023aaad451 | ssangitha/guvicode | /reverse_case.py | 119 | 3.78125 | 4 | s=input()
a=""
for i in s:
if i.islower():
a=a+i.upper()
elif i.isupper():
a=a+i.lower()
else:
a=a+i
print(a)
|
c3179f3120c5a624d3f12a1e470bc0ada3028ac1 | Rivarrl/leetcode_python | /leetcode/1501-1800/1642.py | 1,195 | 3.8125 | 4 | # -*- coding: utf-8 -*-
# ======================================
# @File : 1642.py
# @Time : 2020/11/25 0:49
# @Author : Rivarrl
# ======================================
from algorithm_utils import *
class Solution:
"""
[1642. 可以到达的最远建筑](https://leetcode-cn.com/problems/furthest-building-you-can-reach/)... |
5455c44a62d26453acd8f42fbc77e2960006df22 | HyeminNoh/TIL-2019 | /알고리즘문제풀이/remove_couple.py | 273 | 3.609375 | 4 | def solution(s):
answer_list=[]
for letter in s:
if answer_list and answer_list[-1]==letter:
answer_list.pop()
else:
answer_list.append(letter)
if not answer_list:
return 1
if answer_list:
return 0 |
3451c988e84691b8951499d224e3b95749e12568 | mindovermiles262/codecademy-python | /11 Classes/01_class_basics.py | 280 | 3.640625 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Jan 9 17:20:32 2017
@author: mindovermiles262
Codecademy Python
Define a new class named "Car". For now, since we have to put something
inside the class, use the pass keyword.
"""
class Car(object):
pass |
9c4f510d06a8015bd7ae3c11d5e35f7aecc41cd0 | ltachevna/exz3 | /main.py | 2,417 | 3.90625 | 4 | # def bank(karta):
# print(str(karta).replace(str(karta)[:12], '*' * 12))
# def palindrome(a):
# if a == a[::-1]:
# return True
# else:
# return False
from os import name
class Tomato:
index = None
states = {0: "Рост", 1: "Цветение", 2: "Формирование", 3: "Созревание"}
def in... |
3024868997f9b894529ce9f1fae2287f95b31c23 | ashikaJo/Python_Training | /Python_Assignments/Task4.py | 6,364 | 4.4375 | 4 | # 1. Write a program to reverse a string. Sample input: “1234abcd” Expected output: “dcba4321”
def reverse_str(input_str):
return print(input_str[::-1])
if __name__ == "__main__":
reverse_str("1234abcd")
# 2. Write a function that accepts a string and prints the number of uppercase letters and lowercase letter... |
1f1f3b64fe5443bf0263be8577c4c4d08eb74479 | leonardocarbone/python_examples | /examples/filter.py | 858 | 4.5 | 4 | # Example 1 - Filter even/odd numbers on the list using lambda expression
list = range(6)
print "Even numbers", filter(lambda n: n%2==0, list)
print "Odd numbers", filter(lambda n: n%2!=0, list)
# Example 2 - Filter even/odd numbers on the list using classic method
def check_even(number):
if number%2 == 0:
re... |
3c21d1a228740837bf971fd63a4efaf795593ca3 | Dmitry-White/HackerRank | /Python/Itertools/iterators.py | 533 | 3.5625 | 4 | """
Created on Tue Sep 26 01:03:23 2017
@author: Dmitry White
"""
# TODO: You are given a list of N lowercase English letters.
# For a given integer K, you can select any K indices
# (assume 1-based indexing) with a uniform probability from the list.
# Find the probability that at least one of the K
# indices select... |
196e436423368266280988fe0ea3d8b7891d2922 | utcsox/Leetcode-Solutions | /Python/number-of-islands.py | 2,462 | 3.5625 | 4 | class Solution1:
def numIslands(self, grid: List[List[str]]) -> int:
if not grid:
return 0
def helper(grid, row, column):
# for each grid u travel turn it to 0
grid[row][column] = '0'
# u can continue traverse left, ... |
1b35d79ff969e1463c6ecfcda96bdd5639d7d4b1 | JasonLin43212/jasonL | /22_closure/closure.py | 974 | 3.9375 | 4 | # Jason Lin
# SoftDev2 pd7
# K22 -- Closure
# 2019-04-30
def repeat(word):
def output(num):
return word*num
return output
r1 = repeat('hello')
r2 = repeat('goodbye')
# print(r1(2))
# print(r2(2))
# print(repeat('cool')(3))
def make_counter():
x = 0
# y = 2 #Declaring it here is not closure
... |
08d0ad683f37dd9ae23b46cf5f99fe963d399d5d | franciole/python | /curso-em-video/desafios/desafio019.py | 639 | 3.953125 | 4 | print('Exercício Python 019: Um professor quer sortear um dos seus quatro alunos para apagar o quadro. \n'
'Faça um programa que ajude ele, lendo o nome dos alunos e escrevendo na tela o nome do escolhido.')
import random
a1 = input('Nome do 1º aluno: ')
a2 = input('Nome do 2º aluno: ')
a3 = input('Nome do 3º alu... |
b15e4064e504b25b7857d3dc8e1544f5909512d9 | sobamchan/Easy21 | /env.py | 2,053 | 3.5625 | 4 | from random import choice
from copy import deepcopy
class Card(object):
def __init__(self, init=False):
self.number = choice([1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
if init:
self.is_black = True
else:
self.is_black = choice([True, True, False])
def value(self):
... |
46e4aacbc92bc7ec1272d40d0f66101c5d00e860 | vyomio/CraigslistScan | /looptest3_0.py | 578 | 3.546875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Wed Nov 4 18:25:34 2020
@author: Vyom
just some basic loop testing that will be used in VERSION 4.0
"""
cites = []
yn = 1
while yn == 1:
add_state = input('Enter states: ')
if add_state != 'done':
def state():
with open(ad... |
7697a7ad0aa16cbf2ead3e5732c8748d51d60644 | sabakethar/Python-Learning | /mypy1.py | 148 | 3.890625 | 4 | #! /usr/bin/python
#print(input("enter:"))
x=input("enter a number:")
if x.__class__.__name__!="int":
print("You have not entered a number")
|
c63ba95d602601535d28b9a879a3dffecc29de6c | JonasCoussement/AdventOfCode2016 | /Day21/Day21.py | 2,904 | 3.71875 | 4 | def get_instruct():
instr = open("Day21.txt").readlines()
return instr
def swap(instr):
global password
if instr[1] == "position":
i = int(instr[2])
j = int(instr[5])
elif instr[1] == "letter":
i = password.index(instr[2])
j = password.index(instr[5])
password[i]... |
e3db19c7ae6ac3b873a38d88f341937ba98b1c2d | John2941/Code-Eval | /easy/sum of digits/main.py | 783 | 3.9375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sun Jul 12 17:25:31 2015
Given a positive integer, find the sum of its constituent digits.
INPUT SAMPLE:
The first argument will be a path to a filename containing positive integers, one per line. E.g.
23
496
OUTPUT SAMPLE:
Print to stdout, the sum of the numbers that make ... |
757e8b7f213f0138b307b0b6190b4c2f45b7d6ad | Hanuvendra/Codechef-PRACTICE | /Easy codechef/chef-jumping.py | 91 | 3.953125 | 4 | n=int(input())
if(n%6==0 or n%6==1 or n%6==3):
print ("yes")
else:
print ("no") |
af60e1c54d55e36190b8f06a0dae9691fc1a2c26 | KevinChenWu/principios2-19 | /Tarea1-Errores.py | 4,691 | 3.71875 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#Nombre:
#INSTRUCCIONES:
#NO AGREGUE NI ELIMINE líneas de código. Sólo debe corregir los errores sintácticos o lógicos
#presentes en el código a continuación.
#Para cada uno de los errores vea el mensaje. Identifique y corrija el error.
#Al final de cada Caso, ... |
fbda3acfc5e21dc7d6b2f3a89da88d654e9d6e74 | zackaryjwright-jcu/Tutorials | /prac_01/shop_calculator.py | 1,133 | 4.40625 | 4 | """
A shop requires a small program that would allow them to quickly work out the total price for a number of items, each
with different prices.
The program allows the user to enter the number of items and the price of each different item.
Then the program computes and displays the total price of those items.
If the t... |
40ab6398429ec2cb50c765961377145c59838d2e | liseyko/CtCI | /leetcode/p0024 - Swap Nodes in Pairs.py | 951 | 3.90625 | 4 | # Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def swapPairs(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
# 1->2->3->4 => 2->1->4->3
# h->1->2<-t
... |
917f9ee2d9b728614c972bb6195ff4326e1aa63f | zabacad/networking-scootaloo | /World.py | 695 | 3.765625 | 4 | class World:
"""World."""
def __init__(self, width, height):
self.width = width
self.height = height
self.world = [[" " for x in xrange(self.width)] for y in xrange(self.height)]
def __del__(self):
pass
def __str__(self):
printable = ""
for y in xrange(self.height):
for x in xrange(self.width):
... |
80b947e2c81d66cbbfb13aed817af108d3eb9243 | uvsq21929616/Sololearn-Course-Projects | /Sololearn - Python Data Structures/Letter Frequency/Code.py | 198 | 3.78125 | 4 | text=input()
letter=input()
totalLen=len(text)
num=text.count(letter)
print(int(num/totalLen*100))
text=input()
letter=input()
totalLen=len(text)
num=text.count(letter)
print(int(num/totalLen*100))
|
6bce2f302fd35088e851a2fe67591cfa4d876da5 | ceaumo02/Python_algorithms | /Estadistica_computacional/probabilidades.py | 1,493 | 3.953125 | 4 | import random
def tirar_dados(numero_de_tiros, numero_de_dados):
secuencia_de_tiros = []
if numero_de_dados <= 0:
numero_de_dados = 1
for _ in range(numero_de_tiros):
tiro = 0
for _ in range(numero_de_dados):
tiro += random.choice([1,2,3,4,5,6])
secuencia_de_tir... |
e1cdaf7bc1909801309bdfa04249542bf53ce834 | JiaXinDong-coderer/AI | /A1/puzzleSolver.py | 16,006 | 3.953125 | 4 | from sys import argv # use to examine input line
from sys import maxsize
from math import sqrt
import time
class Heuristics:
"""This function will compare each element in currentboard
to correct answer. It returns the summation of mismatch
distance. e.g. mismatch distance of 3 and 8... |
498084f55f58c8b6647a500827098e5001fe6868 | josephsurin/cp-practice | /leetcode/1329.py | 1,128 | 3.96875 | 4 | # sort the matrix diagonally
# given a m*n matrix of integers, sort it diagonally in ascending order from the top-left to the bottom-right then return the sorted matrix
from typing import *
def get_diag(y, x, m, n):
o = []
while y < m and x < n:
o.append((y, x))
y += 1
x += 1
retur... |
6b085a4efc2f58c557c6683cfa0e5c8980c0b94e | gauth555/DataScience | /Misc - Other Programs/FibonacciSeries.py | 411 | 4.21875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Wed Feb 4 09:22:44 2015
@author: manghnani
"""
# Function to compute the nth Fibonacci numbers
def fibonacci(number):
if number==0:
return 0
elif number==1:
return 1
else:
return fibonacci(number-1)+ fibonacci(number-2)
# Cal... |
8a463adc2d12701e7079fbebd67f68e40d9ac730 | TCmatj/learnpython | /10-1_python_study.py | 405 | 3.5625 | 4 | # TC 2020/10/9/22:20
filename = 'C:\\Users\\Administrator\\Desktop\\learnpython\\python_study.txt'
with open(filename) as file_object:
contents = file_object.read()
print(contents)
with open(filename) as file_object:
for line in file_object:
print(line.rstrip())
with open(filename) as file_object:
... |
b9cd6c9f0a044c4c5112785c5373b3c720ff6882 | Shekhar9011/InfyTQ-PF | /day8_assgnmnt52_odd_even_list_sum.py | 597 | 3.625 | 4 | #PF-Assgn-52
#This verification is based on string match.
def sum_of_numbers(list_of_num,filter_func=None):
if filter_func==None:
return sum(list_of_num)
elif filter_func==even:
return sum(filter_func(list_of_num))
elif filter_func==odd:
return sum(filter_func(list_of_num))
def ev... |
9b62ccdf0e974a854737cfd57621ba5d115e9ae1 | BCasaleiro/schelling-model-segregation | /main.py | 17,260 | 3.734375 | 4 | from Tkinter import *
import time
import plotly
import plotly.plotly as py
import plotly.graph_objs as go
from random import random, randint
from math import pow, sqrt
from time import sleep
mean_s = 0.0
def print_matrix(m): #TODO: remove this method
for... |
b1d305e6565b20bf082c64ed319ec0fcbeefc2d9 | zmunk/Project-Euler | /Euler59.py | 1,027 | 3.59375 | 4 | val = 0
def dectobin(n): # takes int returns str
if n < 2:
return str(n)
if n % 2 == 0: # if n is even
return dectobin(n / 2) + "0"
return dectobin(n / 2) + "1"
def bintodec(n): #takse str returns int
if len(n) == 1:
return int(n)
return bintodec(n[:-1])*2 + int... |
d1086f39a719274168aef783a6db9d7d970b1ffb | piyushgit1/arratech | /delete.py | 314 | 3.703125 | 4 | import sqlite3
class delete:
def delt(self):
connection = sqlite3.connect('test.db')
deletequery = "SELECT * FROM cart WHERE Id=?"
Id = input("input the id to delete")
connection.execute(deletequery, [Id])
connection.commit()
print("Data Deleted Succesfully")
|
9ef9569f89574c21dfdecbdc252f207b4b20dd0f | GNLRaviTeja/Python | /test.py | 360 | 3.9375 | 4 | #x = 1
#def my_function():
# x = 2
# print(x)
#print(x)
#my_function()
#print(x) */
#for integer in (-1,3,5):
# if integer < 0:
# print("negative")
# else:
# print("non-negative")
x = 'String'
y = 10
z = 5.0
print(x + x) # print command 1
print(y + y) # print command 2
print(y + x) # print com... |
59b72994f771b2b462671b1bcb2caad8937ed4ed | RyanSamman/KAU-CPIT110 | /Lab3/P1.py | 464 | 4.375 | 4 |
# Imports an accurate value of pi
from math import pi
# Prompts user to assign a value to the radius and length
radius, length = eval(input("Enter the radius and length of a cylinder: ")) # not reliable
# Processes input length and radius into area and volume
area = radius * radius * pi # value of pi not g... |
50935f7ff6503d4622af017bb5da92ecabf5845f | buckmaxwell/cassidoo | /2020-08-03_char_num_sort/char_num_sort.py | 269 | 3.828125 | 4 | def char_num_sort(words):
return sorted(words, key=lambda x: (len(set(x.lower())), -len(x)))
if __name__ == '__main__':
assert(
char_num_sort("Bananas do not grow in Mississippi".split())
== "do in not Mississippi Bananas grow".split()
)
|
98fbc7ee4b04d4025cce627c4a6c56ad4dd2c66d | WalkerTxsRngr7/python | /mastermind.py | 3,258 | 3.609375 | 4 | import pygame
import random
pygame.init()
win=pygame.display.set_mode((700,710))
pygame.display.set_caption("Mastermind")
win.fill((50,50,50))
pygame.display.update()
x = 150
y = 40
radius = 20
width = 0
rowDrawn = False
row = 1
red = (255,0,0)
white = (255,255,255)
w, h = 6, 11
Rows = [[0 for x in range(w)] for ... |
ebe937ee81c282dd39a74f11b5e9904f7b2f0df4 | szymekj/python-sandbox | /guess-the-number.py | 399 | 3.640625 | 4 | import random
b = 0
liczba = random.randint(1, 100)
while (True):
a = int(input('guess the number from 1 to 100 that I\'m thinking of: '))
b = b + 1
if a == liczba:
print ("\n\n\t\t\tgood!!!! you guessed it after " + str(b) + " tries \n\n")
break
elif a > liczba:
print("\nno, t... |
6d4de8b1bbd3d94b5e1e86f317a3d7c49e4cd770 | TomSheridanCox/advent-of-code-2020 | /day3/2/main.py | 862 | 3.59375 | 4 | from collections import Counter
with open("input.txt") as f:
content = f.readlines()
# you may also want to remove whitespace characters like `\n` at the end of each line
content = [x.strip() for x in content]
print(len(content))
print(content)
# actual code starts here
valid_counter = 0
for line in content:
s... |
f6a1b6521f256bde7df1468a5c03185bbebcc844 | Bazarovinc/GeekBrains.Algoritms_on_Python | /Lesson_2/2.7.py | 598 | 3.90625 | 4 | """7. Написать программу, доказывающую или проверяющую, что для множества натуральных чисел выполняется
равенство: 1+2+...+n = n(n+1)/2, где n — любое натуральное число."""
n = int(input("Введите натуральное число: "))
sum = 0
for i in range(1, n + 1):
sum += i
if sum == (n * (n + 1) / 2):
print(f"Равенств... |
a659ca7086e56f53c03e9ea2d33192c17a90d0ac | SajinKowserSK/algorithms-practice | /543-diameter-of-binary-tree/543-diameter-of-binary-tree.py | 1,507 | 3.890625 | 4 | # Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def diameterOfBinaryTree(self, root: Optional[TreeNode]) -> int:
# diameter is defined by length of ... |
5bfbbd44bda901f207ac17b3176cf1bbf9f9b22b | piercegov/CS-156 | /set2_coins.py | 1,034 | 3.875 | 4 | import numpy as np
# Flip 1000 coins 10 times each, repeat this 1000 times
# Store the coin with the minimum number of heads, a random coin, and the first coin for each run
def run_iteration(num_coins, num_flips): # Performs one 'run' of the experiment
arr = np.array(np.zeros(num_coins))
for i in range(num_coi... |
f03e732db534284dc7fce3d9de57b47295cdf31c | silviajlee/MC102 | /lab12.py | 1,403 | 3.9375 | 4 | #"Roteiro do Lab. 12: https://www.ic.unicamp.br/~mc102/mc102-1s2020/labs/roteiro-lab12.html"
#entrada
lista = []
entrada = input()
x = "".join(entrada.split())
lista.extend(x)
numeros = [int(x) for x in lista]
#print
def desenho(lista):
z = len(numeros)
y = (z + 2)
print(y * ".")
maior =... |
cbe49ffdf9819fe1d41c7845c66b7454218b9a9b | mossblaser/spinn_route | /spinn_route/model.py | 10,091 | 3.765625 | 4 | #!/usr/bin/env python
"""
Components of a model of a SpiNNaker network consisting of interconnected cores
and routers with multicast routes mapped out within it.
"""
import topology
from collections import namedtuple
Chip = namedtuple("Chip", ["router","cores"])
class Route(object):
"""
A specific multicast rou... |
8cd39086c42c025ce7ac9890018a760506865604 | daizutabi/machine-learning | /docs/tensorflow/b1_チュートリアル/p2_詳細/c01_カスタマイズ/s04_カスタム訓練:基本.py | 2,522 | 3.625 | 4 | # # カスタム訓練:基本
# # (https://www.tensorflow.org/tutorials/customization/custom_training)
import matplotlib.pyplot as plt
import tensorflow as tf
# ## 変数
# !Python の状態を使う
x = tf.zeros([3, 3])
x += 2 # これは x = x + 2 と等価で, x の元の値を変えているわけではない
print(x)
# -
v = tf.Variable(1.0)
# !Python の `assert` を条件をテストするデバッグ文として使用
asser... |
7ccbe2294cfeb120ada59e0725a35bcf497df99f | ricklixo/cursoemvideo | /ex045.py | 1,253 | 3.875 | 4 | # DESAFIO 045 - Crie um programa que faça o computador jogar JOKENPÔ com você.
from random import choice
jankenpo = ['PEDRA', 'PAPEL', 'TESOURA']
cpu = choice(jankenpo)
selecao = ' '
print('[1] - PEDRA')
print('[2] - PAPEL')
print('[3] - TESOURA')
escolha_jogador = int(input('Escolha sua opção: '))
if escolha_jogad... |
894da6297a8e969ac3972711225b52e403c54252 | zhxjenny/SoftTest | /preview-exercise/ex33.py | 195 | 3.90625 | 4 | i=0
number=[]
while i<6:
print "At the top i is %d" %i
number.append(i)
i=i+1
print "Numbers now:",number
print "At the bottom i is %d" %i
print "The number:"
for num in number:
print num
|
ccf7cd51d9e716fe73fb7434e2378bdc5ecfef5c | albert-pakichev/ip-pakichev-albert | /lesson5/main.py | 3,452 | 3.984375 | 4 | # n1=2
# n2=n1
# n1=4
# print(f'n1={n1} n2={n2}')
# # неизменяемые объекты int float complex str tuple- immutable objects
# # изменяемые объекты set list dict - mutable objects
# sp1=[1,2,3]
# sp2=sp1
# # sp2.append(4)
# # print("sp1=",sp1,"sp2=",sp2)
# #передача аргументов по ссылке/значению
# def modify(lst):
# l... |
f8b4cc079fc0906ad3de161649d7cff3aa8e8e1a | gary-gggggg/gary | /1-mouth01/day02/速度计算器.py | 278 | 3.90625 | 4 | """计算加速度
位移=初速度×时间+加速度×时间的平方/2
"""
distance=float(input("请输入位移:"))
start_speed=float(input("请输入初速度:"))
time=float(input("请输入时间:"))
eccelarate=(distance-start_speed*time)*2/time**2
print(eccelarate)
|
0feb565bea79bc4279a38538c6cafda236c727b2 | sajdik/School-Projects-BIT | /IPP/Task2/Frame.py | 1,086 | 3.59375 | 4 | from ErrorHandler import ErrorHandler
class Frame:
"""Storing variables, info about them and their values"""
def __init__(self):
self.store = dict()
self.initialized = set()
def define(self, name):
"""Define variable in frame"""
assert name is not str
if name in se... |
9c0fe999de04aa2118e8d7f06526854b28040a71 | rvua/Functions_Basic_II | /functions_basic_II.py | 2,313 | 4.25 | 4 | # Q.1 Countdown:
# Create a function that accepts a number as an input. Return a new list that counts down by one, from the number (as the 0th element) down to 0 (as the last element).
# Example: countdown(5) should return [5,4,3,2,1,0]
def countdown(number):
num = []
for i in range(number, -1, -1):
num... |
1e783301244d5050336174c56693d54d35ce161e | jiher/Euler | /XP_Quest.py | 560 | 3.515625 | 4 | #!/usr/bin/env python
def erato(n):
"""
Suggestions from Ka-Ping Yee, John Posner and Tim Peters"""
sieve = [0, 0, 1] + [1, 0] * (n//2) # [0 0 1 1 0 1 0...]
prime = 3 # initial odd prime
while prime**2 <= n:
for i in range(prime**2, n+1, prime*2):
sieve[i]... |
e55f607933ee96961284894da06a92d66ecc5b0c | SensationG/PythonStudy | /textbook/sample_code_s3/s3_dict_3_list2dict.py | 964 | 4.09375 | 4 | """
Converting list into dictionary with index as key
"""
#把list表转到dict中
list = [2, 55, 27, 15, 39]
dict1={}
for k, v in enumerate(list):
print("k, v:", k, v)
dict1[k] = v
print('dict1: ',dict1)
#dict1 = {i:v for i,v in enumerate(list)} #方法2
#print(dict1)
#del (dict) #出现dict not callable时使用
dict2 = di... |
4117fbe5b1c8bce4dcba6d4e014fdb1e8f22b770 | Vahid-GitHub/HackerRank-Cracking-the-Coding-Interview | /12 - Merge Sort Counting Inversions - Top to Buttom.py | 1,133 | 3.625 | 4 | #!/bin/python3
import sys
def countInversions(arr):
iCount = 0
arr, iCount = mergeSort(arr, 0)
return(iCount)
def mergeSort(a, iCount):
La = len(a)
if (La < 2):
return((a, iCount))
La2 = La // 2
a1, iCount = mergeSort(a[:La2], iCount)
b1, iCount = mergeSort(a[La2:], iCount)
... |
33037befc84eef862f864cdc8cfefd292584ef41 | Jitha-menon/jithapythonfiles | /PycharmProject/fundamental_programming/Swapping/type 1.py | 203 | 3.96875 | 4 | a=int(input('enter the 1num'))
b=int(input('enter the 2 num'))
temp=a
a=b
b=temp
print('value of num1 is',a)
print('value of num2 is',b)
# 2nd approach
#(a,b)=(b,a)
#3rd approch
# a=a+b
# b=a-b
# a=a-b |
fe07de6dbd04432b2ee74e0a5e3d7e8e436e9696 | JSzkup/GameSelector | /games/noughtsAndCrosses.py | 6,644 | 4.09375 | 4 | import random
class TicTacToe():
def __init__(self):
# Sets the game state and initializing letter variable
self.gameIsPlaying = True
self.letter = ''
def drawBoard(self, board):
# The board is a list of 10 strings ignoring 0 to make it
# easier on the user when choo... |
19c9ee6ae18b867d82293eaa976ee21bfa5f607b | higor-gomes93/curso_programacao_python_udemy | /Sessão 4 - Exercícios/ex9.py | 359 | 3.90625 | 4 | '''
Leia uma temperatura em graus Celsius e apresente-a convertida em graus Kelvin. A fórmula de conversão é:
K = C + 273.15, sendo C a temperatura em Celsius e K a temperatura em Kelvin.
'''
temp_celsius = float(input("Insira a temperatura em graus Celsius: "))
temp_kelvin = temp_celsius + 273.15
print(f"A temperatur... |
a3dd8836e9b1131b5a1f09c63bbb50431618c5ef | menard-noe/LeetCode | /Sort Integers by The Number of 1 Bits.py | 1,123 | 3.578125 | 4 | from typing import List
class Solution:
def sortByBits(self, arr: List[int]) -> List[int]:
dict_number_bits = dict()
arr = sorted(arr)
dict_memo_count_bits = {0: 0, 1: 1}
def count_bits(val: int):
if val in dict_memo_count_bits:
return dict_memo_count_... |
d9ffbaa1c4e2f6ce8a428030ce54c3971181f5b2 | BAFurtado/Python4ABMIpea2019 | /my_agent0.py | 292 | 4.03125 | 4 | import turtle
def polygon(n, t):
# n é o número de lados do poligono
# t é o tamanho em passos do objeto
b = turtle.Turtle()
b.speed(1)
for i in range(n):
b.forward(t)
b.lt(360/n)
if __name__ == '__main__':
polygon(8, 75)
turtle.mainloop()
|
b33f8776fd7bc392c9b8d2a545a3c7317b2e965c | marmiod1/pythonowe_przygody | /02_Proste dzialania matematyczne/Wypisz liczby podzielne przez 3 i 5.py | 610 | 4.0625 | 4 | '''Wypisz liczby podzielne przez 3 albo 5 ( w zakresie 1..100) (nie wypisuj tych podzielnych jednocześnie przez 3 i 5)'''
def solution():
numbers = []
for x in range (1,101):
if x % 3 == 0 or x % 5 == 0:
if x % 3 != 0 or x % 5 !=0:
numbers.append(x)
print(numbers)
solu... |
20a8757532ca61369f8f1cd95257649b6d186715 | zeeshantariqrafique/algo_ds | /python/OneLiners/factorial.py | 106 | 3.5625 | 4 | from functools import reduce
num = 5
factorial = reduce(lambda x,y: x*y,range(1,num+1))
print(factorial)
|
25a41edbd69aa1bcf970d64292d1764a60c0589e | lohchness/probability-calculator | /prob-calculator.py | 2,240 | 3.5625 | 4 | import copy
import random
# Consider using the modules imported above.
class Hat:
def __init__(self, **kwargs):
self.contents = []
for color, count in kwargs.items(): # Unpacks key and value from kwargs dictionary
for i in range(count):
self.contents.append(color)
... |
0f389136812da6dbea707df62c8bf66c338b173c | pmoeini1/Web-Scraper | /Web Scraping/scraper.py | 1,804 | 3.5625 | 4 | from urllib.request import urlopen
import csv
# access webpage
url = "https://en.wikipedia.org/wiki/List_of_countries_by_electricity_consumption"
page = urlopen(url)
# read html
html_bytes = page.read()
html = html_bytes.decode("utf-8")
# isolate table body
table = html[html.find("<tbody>") + len("<tbody"):html.find("... |
071d84555691ea27d67b13a8c67884dd5152fa4c | Burner999/Python | /favlangs.py | 1,387 | 3.546875 | 4 | favourite_languages = {
'jen': 'Python',
'sarah': 'C',
'Edward': 'Ruby',
'Phil': 'Python'
}
friends = { 'jen' , 'Phil'}
print("Keys listing")
print("============\n")
for Name in (favourite_languages.keys()):
print(Name.title())
print("\n")
print("Values listing")
print("==============\n")
for language in favour... |
1e8b98f31b8ec34546e5dcecaf3b9a51f6d530e6 | Python-Programming-Boot-Camp/JonathanKarr | /Date Time/how_long_until_next_year_timer_updates.py | 378 | 3.734375 | 4 | from datetime import datetime
from time import sleep
today = datetime.now()
year = today.year
next_year = year + 1
new_year = "1-1-" + str(next_year) + "-0:00:00"
while (today.year < next_year):
new_year_date = datetime.strptime(new_year,"%m-%d-%Y-%H:%M:%S")
time_remaining = new_year_date-today
print(time_r... |
5af19cd0a1e480afd1996e362757c602e531f439 | smirnoffmg/codeforces | /2A.py | 711 | 3.5 | 4 | # -*- coding: utf-8 -*-
n = int(raw_input())
winner = None
steps = []
score = {}
max_individual_score = {}
final_score = {}
for i in xrange(n):
name, points = raw_input().split(' ')
steps.append((name, int(points)))
if name not in score.keys():
score[name] = int(points)
max_individual_s... |
d556c38fe0de8c94cf98aa0445c2862a227ef366 | alihaidermalik04/Learning | /python/decorators.py | 1,158 | 4.875 | 5 | '''
Basically it passed function as an argument in beautiful way.
to run this code:
$ python3 decorators.py
'''
'''
Consider this dec function that takes a function as an argument.
'''
# def dec(func):
# print('I will call a function')
# return func
# def f(name):
# print(f'hello {name}')
# test = dec(... |
6dfd79d8cd967f501d87176086a6f1d2dec7d4bd | Hegemony/Python-Practice | /LeetCode practice/Top 100/17.Letter combination of phone number.py | 572 | 3.59375 | 4 | def letterCombinations(digits):
if not digits:
return []
digit2chars = {
'2': 'abc',
'3': 'def',
'4': 'ghi',
'5': 'jkl',
'6': 'mno',
'7': 'pqrs',
'8': 'tuv',
'9': 'wxyz'
}
res = [i for i in digit2chars[digits[0]]]
... |
33ca19b163ef89ab893d653be7aa83db36895e5e | samikojo-tuni/2021_Python-ohjelmointi_3004 | /Examples/name.py | 587 | 4.28125 | 4 | # Harjoitus
# Kirjoita ohjelma, joka kysyy käyttäjän nimeä. Ohjelma tulostaa esim. tekstin
# "Mikä sinun nimesi on?"" nimeä kysyttäessä.
# Jos nimi on kirjoitettu pienellä alkukirjaimella, ohjelma muuttaa nimen alkukirjaimen
# isolla kirjoitetuksi. Lopuksi ohjelma tulostaa "Sinun nimesi on <Nimi>"
name = input("What i... |
8baeae8fc0763c740a0072c0c1811c10f65e6c3a | dstark85/mitPython | /midterm/dot_product_map.py | 494 | 3.859375 | 4 | # with map instead
def dotProduct(listA, listB):
'''
listA: a list of ints
listB: a list of ints
lists have same number of elements
return the dot product of the lists
'''
def multiply(a, b):
return a * b
res = 0
for product in map(multiply, listA, listB):
res += pr... |
8b225e29c1bd3cc79c8f1845e21f38aeccc60631 | f4z3r/project_euler | /python/solutions/p001_multiples.py | 461 | 4.375 | 4 | #!/usr/bin/env python3 -OO
"""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.
"""
from functools import reduce
def run(num):
def sum_multiples(... |
228bc71afe3c920097de251b232cf36104ebbd77 | mus-g/CodeWars | /Kata/8KYU/Are You Playing Banjo/test.py | 594 | 3.5625 | 4 | import unittest
areYouPlayingBanjo= __import__("Are You Playing Banjo")
class DNAToRNATestCase(unittest.TestCase):
def test_equals(self):
self.assertEqual(areYouPlayingBanjo("Adam"), "Adam does not play banjo")
def test_equals_2(self):
self.assertEqual(areYouPlayingBanjo("Paul"), "Pau... |
cc909c0d4da70fbf2011ad4c3736c8ac6d56ab39 | ErrorCode51/ProjectEuler | /Euler_01.py | 237 | 3.65625 | 4 | print("Hello World")
from includeFiles.Functions import *
number = 0
total = 0
while(number < 1000):
if check3(number) or check5(number):
print(number)
total += number
number += 1
print("Total:" + str(total))
|
136d7b03bb8bc3c94b74fe292c5f8023106b84f6 | SuperSultan/Kattis | /knapsack.py | 2,270 | 3.953125 | 4 | from sys import stdin
def main():
while True:
try:
arr = [int(x) for x in stdin.readline().split()]
capacity = arr[0]
n = arr[1]
values = []
weights = []
for i in range(n):
value_weight = [int(x) for x in std... |
199a8d9d89cd58009c70e6ac6a886bfd55203d93 | jwkblades/utils | /d6Chance.py | 772 | 3.890625 | 4 | #!/bin/python
from math import factorial
def choose(a, b):
return factorial(a) / (factorial(b) * factorial(a - b))
def chance(dice, passes):
num = sum([choose(dice, x) for x in range(0, dice - passes + 1)])
return num / (2 ** dice)
def chance2(dice, passes, prob = 1/2):
pct = 0;
for x in range(0... |
e1ef7d07a30138c404a3776ba8ecf20abe30bfa5 | varunkumar032/lockdown-leetcode | /random/solutions/q16_CapacityToShipPackagesWithinDDays.py | 1,727 | 4.0625 | 4 | # A conveyor belt has packages that must be shipped from one port to another within days days.
# The ith package on the conveyor belt has a weight of weights[i]. Each day, we load the ship with packages on the conveyor belt (in the order given by weights). We may not load more weight than the maximum weight capacity o... |
403f1ba47b4a67b4faad71ba5133b0f7a8c87e09 | TalatWaheed/100-days-code | /code/python/Day-100/1D.py | 305 | 3.953125 | 4 | print("Enter 'x' for exit.")
nval = input("How many element you want to store in the array ? ")
if nval == 'x':
exit()
else:
n = int(nval)
arr = []
for i in range(1, n+1):
arr.append(i)
print("\nElements in Array are:")
for i in range(0, n):
print(arr[i], end=" ")
|
ebb979b22896c1999a077821c3b634c1551987fb | alekhaya99/DSA_Python | /Exercise/Loop Exercise/problem5.py | 145 | 4.21875 | 4 | '''
Question 5: Calculate an factorial
'''
n=int(input("Please enter a number: "))
fact=1
for i in range (1,n+1):
fact=i*fact
print(fact)
|
e61bfeca1bb4caf667320dc52c2fd70fab18ead8 | young-nlp/LeetCode | /004.Longest palindromic substring/solution.py | 1,041 | 4 | 4 | # coding:utf-8
'''
Given a string s, find the longest palindromic substring in s. You may assume that the maximum length of s is 1000.
Example:
Input: "babad"
Output: "bab"
Note: "aba" is also a valid answer.
Example:
Input: "cbbd"
Output: "bb"
Hint:
遍历每个字符,以该字符为中心向左右两边扩伸,直到该子串不是回文,返回的则是以该字符为中心最长回文子串。
以两个字符为中心同理。
... |
d2d245d73027f3b56a298822c380afc02cf19edd | loclincy10/AdvancedPython | /webscraping - movies.py | 2,370 | 3.71875 | 4 |
from urllib.request import urlopen
from bs4 import BeautifulSoup
import openpyxl as xl
from openpyxl.styles import Font
webpage = 'https://www.boxofficemojo.com/weekend/chart/'
page = urlopen(webpage)
soup = BeautifulSoup(page, 'html.parser')
title = soup.title
print(title.text)
##
##
##
##
print(soup)
#f... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.