blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
f136d041f32b05814a195e2b7d2e4924ee4cd1ff | dloeffen/datamining-practicals | /solutions/linear_models/code/utils.py | 514 | 3.921875 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Sep 21 14:09:10 2020
@author: dirk
"""
import numpy as np
def sum_squared_errors(y1, y2):
# Implement sum of squared errors
diff = y1 - y2
square = np.multiply(diff, diff)
return np.sum(square)
def mean_squared_error(y1, y2):
... |
683354238d01811f3191a4ab9ee251c7c0131cf8 | iamshubhamsalunkhe/Python | /funct_with_mult_argue/funct_with_mult_arguement.py | 303 | 3.953125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Wed Mar 6 14:48:40 2019
@author: Shubham
"""
#program to create a func with multiple arguement
def newfunction(a,b,c,d):
result = a*b-c+d
print("The answer is ",result)
newfunction(1,2,3,4)
newfunction(a=1,b=2,c=3,d=5)
newfunction(c=1,d,3,a=2,b=6) |
acb5f38b59568f0e556fba6f043c24061a8099f8 | YiDomiChen/leetcodesolution | /python/BFS/graph_valid_tree.py | 1,056 | 3.75 | 4 | from collections import deque
class Solution(object):
def validTree(self, n, edges):
"""
:type n: int
:type edges: List[List[int]]
:rtype: bool
"""
if n == 0:
return True
if len(edges) != n - 1:
return False
graph = se... |
e4e980401e4628d11c76baf2eddfdcf0b0a0629a | prathamesh201999/python1 | /Selection_sort.py | 271 | 3.84375 | 4 |
def sort(list):
for i in range(5):
min = i
for j in range(i,6):
if list[j] < list[min]:
min = j
temp = list[i]
list[i] = list[min]
list[min] = temp
list = [6,7,4,90,34,56]
sort(list)
print(list)
|
b23aeb9bf2fcee9be669403a3495ab14524fc704 | danityang/PythonBase | /Tuple.py | 1,279 | 3.578125 | 4 | # coding=utf-8
# TODO Python元组
# 元组与列表类似,不同之处在于元组的元素不能修改。元组使用小括号,列表使用方括号。元组创建很简单,只需要在括号中添加元素,并使用逗号隔开即可
tup1 = ('Google', 'Runoob', 1997, 2000)
tup2 = (1, 2, 3, 4, 5)
tup3 = "a", "b", "c", "d"
# 创建空元组
tup = ()
# 当元组中只包含一个元素时,需要在元素后面添加逗号,否则括号会被当作运算符使用:
tup4 = (50)
print type(tup4)
tup5 = (50,)
print type(tup5)
# TODO 访问元... |
03a45c53c2ed1f35e8a62623ac512e26c7dfe53b | matheuszei/Python_DesafiosCursoemvideo | /0082_desafio.py | 667 | 3.890625 | 4 | #Crie um programa que vai ler vários números e colocar em uma lista.
#Depois disso, crie duas listas extras que vão conter apenas os valores pares e impares digitados.
#Ao final, mostre o conteúdo das três listas geradas
num = []
par = []
impar = []
while True:
num.append(int(input('Digite um valor: ')))
... |
665c843e5ea4b46187f73093633901757f731477 | zgljl2012/web-search-engine-ui | /index.py | 4,350 | 3.5 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
UI - a simple web search engine.
The goal is to index an infinite list of URLs (web pages),
and then be able to quickly search relevant URLs against a query.
See https://github.com/AnthonySigogne/web-search-engine for more information.
"""
__author__ = "Anthony Sigog... |
dfcc2907faa42792a8b89ccd35598e42b3a3f8fd | Hermotimos/Learning | /lambda.py | 2,189 | 4.75 | 5 | """"
This file is for learning and exercise purposes.
Topics:
- simple lambda syntax
- examples: map(), filter(), reduce()
Sources:
https://www.python.org/dev/peps/pep-0008/
https://dbader.org/blog/python-lambda-functions
https://treyhunner.com/2018/09/stop-writing-... |
ffc304c25ab19b842027640e8bfbf3bad90ca907 | Miguel-Tirado/Python | /python_work/Chapter_4/pizza.py | 301 | 3.78125 | 4 | pizzas = ['Hawaian','Perporni','Stuffed crust']
for pizza in pizzas:
print(f"I love {pizza} pizza.")
print(f"\nI love {pizzas[0]} for the pineapples.")
print(f"I love {pizzas[1]} for the classic taste.")
print(f"I love {pizzas[2]} for the chessy crust.")
print("I just really like pizza, dont I.") |
0209ef49786f6f802555933f3a13c6fb281149a8 | aalhsn/python | /loops_task.py | 977 | 3.890625 | 4 |
import time
import datetime
cashier_list = []
name =''
quantity = 0
price = 0.0
print("""
XYZ Point of Sales (POS)
DATE | TIME {}
by Abdullah Alhasan!
""".format(datetime.datetime.now()))
while True:
name= input("Type Item's Name or 'done' If You Finished..>")
... |
7c5abeb358b5790cff1bdfbf801c5093fa286443 | SavinKumar/Python_lib | /Original files/Library.py | 34,819 | 3.734375 | 4 | from tkinter import *
import sqlite3
import getpass
from functools import partial
from datetime import date
conn = sqlite3.connect('orgdb.sqlite')
cur = conn.cursor()
def passw():
pa=getpass.getpass()
passwo='seKde7sSG'
print('Entered password is of ',len(pa),' characters, To continue press Ente... |
93857396636c163579b3e6834b6d3300b64b38db | NTHU-CS50-2020/week7 | /leo/house/import.py | 712 | 3.75 | 4 | from sys import argv, exit
from cs50 import SQL
import csv
import collections
db = SQL("sqlite:///students.db")
if (len(argv) != 2):
exit("Usage: python import.py data.csv sequence.txt")
with open(argv[1] , "r")as file:
reader = csv.DictReader(file)
for row in reader:
name = row["name"].split()
... |
bc8db987a7cef010ba404cbe2088453d512881be | MRitter95/AFC-code | /Data_Analysis/Data_Processing/preAnalysis/resetDateModified.py | 4,215 | 3.828125 | 4 | import os
import sys
import time
# We take advantage of the "Date modified" labels on our data files and folders
# to organize things; specifically, we use them to sort the scope traces into
# the appropriate folders.
# Sometimes mistakes are made, and the dates modified change in such a way that
# the folders are n... |
5657210a4708bd372c858efba698a3bd82bdadb7 | faizan1402/OPENCV | /blurimage.py | 840 | 3.96875 | 4 | # Bluring the imgage
import cv2
import numpy as np
img =cv2.imread("lena.png")
cv2.imshow("Original Image",img)
cv2.waitKey(0)
#How to blur the imgblur
# useing the Kernel function through img is blur Kernel matrix value is increase then img is more times
#Syntax-
#Kernel_dimension=np.ones((size of matrix to ... |
840b4dddca04d25d204d8fd2bc469b5b5b148563 | DrakeVorndran/Tweet-Generator | /Code/zoo.py | 1,018 | 4.03125 | 4 | from pprint import pprint
def get_words(filename):
"""open the file and return a list of all words in it"""
all_words_list = []
with open(filename) as file:
for line in file:
words_list = line.split()
for word in words_list:
all_words_list.append(word)
return all_words_list
def count_a... |
1253b9d43e4b4249e502ac2dbc121e15119ec4bb | GregoryMNeal/Digital-Crafts-Class-Exercises | /Python/Function_Exercises/sin.py | 298 | 3.5625 | 4 | # Imports
import math
import matplotlib.pyplot as plot
# Functions
def f(x):
s = math.sin(x)
return s
def plotit():
xs = list(range(-5, 6))
ys = []
for x in xs:
ys.append(f(x))
plot.plot(xs, ys)
plot.show()
# Main
if __name__ == "__main__":
plotit()
|
36cfe108935709d137de45260e4eb980e6aa05b8 | vishnu11121998/VISHNU-PRASATH | /july4/qu.py | 1,020 | 4.09375 | 4 | q = {"How many days do we have in a week?":["a.7","b.8","c.6","a"],"How many days are there in a year":["a.366","b.365","c.364","b"],
"How many colors are there in a rainbow?":["a.9","b.7","c.6","b"],
"Which animal is known as the ‘Ship of the Desert?":["a.camel","b.Thorny Devil","c.Chile","a"],"How many letters ar... |
643f96cd09a81880f20456183dab9ee032b1d2ac | kaliRegenold/advent2020 | /2.py | 1,318 | 3.796875 | 4 | # Author: Kali Regenold
def fun1(pass_list):
valid_cnt = 0
for rule_pass in pass_list:
# Separate the rule and password
rule, password = rule_pass.split(':')
# Count occurences of rule letter in password
char_cnt = password.count(rule[-1])
# Increase valid count if numb... |
14c35d7a8112d067bee8d8550211b1761b512301 | adithya-r3/recycle-box | /init_db.py | 328 | 3.53125 | 4 | import sqlite3
connection = sqlite3.connect('database.db')
with open('user.sql') as f:
connection.executescript(f.read())
cur = connection.cursor()
cur.execute("INSERT INTO user(name, email, username, password) VALUES (?, ?, ?, ?)",
('Keshav', 'random@gmail.com', 'keshra12', 'krave'))
connection.... |
1634af2095da9383665dee7a2fa0000ff7c07285 | madhur2k9/Expense-Manager | /Models/User.py | 994 | 3.765625 | 4 | class User:
#Constructor for user class
def __init__(self, id, email, password, name, date_created, last_login_date, current_balance):
self._id = id
self._email = email
self._password = password
self._name = name
self._date_created = date_created
self._last_login_... |
2bc5f4069a10f7591262503265bd96d27d432d40 | flaviocardoso/uri204719 | /feitos/menoreposicao.py | 244 | 3.75 | 4 | #!/usr/bin/python3
#menoreposicao.py 1180
N = int(input())
lista = list(map(int, input().split()))
P, M = 0, lista[0]
for i in range(1, N):
if(lista[i] < M):
P, M = i, lista[i]
print("Menor valor: {0}\nPosicao: {1}".format(M, P)) |
5882e162efc5c3e0cbb704c61da496d8abe6eac4 | jtlai0921/Python- | /ex07/test07_7.py | 103 | 3.625 | 4 | def F(a) :
if (a < 0) :
return 1
else :
return F(a-2) + F(a-3)
print(F(7)) |
ae4bc9f803e0842c860ccd684a9b2a19b08ad596 | amoddhopavkar2/LeetCode-October-Challenge | /29_10.py | 635 | 3.65625 | 4 | # Maximize Distance to Closest Person
class Solution:
def maxDistToClosest(self, seats: List[int]) -> int:
distances = [float("inf")] * len(seats)
max_distance = 0
index = -1
for i in range(len(seats)):
if seats[i] == 0:
if index == -1:
continue
distances[i] = i - index
else:
index = i... |
7bff4cd8a3b1abdbf182637dcee2cb9ad597481c | soyun20/Python | /파일 라인수세기.py | 84 | 3.5 | 4 | a=open('hello.txt')
count=0
for line in a:
count+=1
print('Line Count: ',count)
|
5604b47bbee5724654a78c4c1f0c224f6b831c08 | yosef8234/test | /sorting-algorithms/1-selection_sort.py | 649 | 3.765625 | 4 | # Best Case Time: O(n^2)
# Worst Case Time: O(n^2)
# Average Case Time: O(n^2)
import numpy as np
def argmin(array):
# Get the index of the smallest
# element in the array
arg = 0
for i in range(1, len(array)):
if array[i] < array[arg]:
arg = i
return arg
def selection_sort(ar... |
13f40b75f8f668d104280d38c612e2a08b272c09 | LeHamzaSh/GettingInput | /app.py | 172 | 3.78125 | 4 | name = input('What is your name? ')
print('Hi ' + name)
color = input('What is your favourite color? ')
print(color + ' is my favourite color too')
print('Mosh likes blue') |
378d91699890004b517cff05b4a4cef3b60aa4c3 | jamesfneyer/Number-Guessing-Game | /GuesstheNumber.py | 3,440 | 3.796875 | 4 | import random
def valid_four_choice(choice1, choice2, choice3, choice4, prompt):
isValid = False
while not isValid:
replay = input(prompt)
if replay.lower() == choice1 or replay.lower() == choice2 or replay.lower() == choice3 or replay.lower() == choice4:
isValid = True
... |
db74ed686e5e972da905214a004fc84b7ae4138c | coolmich/py-leetcode | /solu/110|Balanced Binary Tree.py | 598 | 3.875 | 4 | # Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def isBalanced(self, root):
"""
:type root: TreeNode
:rtype: bool
"""
def height(... |
d405b447b86c4de8467cb79175deca905e4ada83 | fiso0/MxPython | /taobaoPriceBug/taobaoPriceBug.py | 654 | 3.53125 | 4 | #!/usr/bin/python3
# -*- coding: utf-8 -*-
# 本代码尝试使用BS4静态读取页面内容,但由于价格部分使用了动态显示,无法获取
from bs4 import BeautifulSoup
import requests
import urllib
import os
import sys
import time
def get_soup_of(url):
"""获取某个url的soup
:param url: 待获取的网页地址
"""
html = requests.get(url).text
soup = BeautifulSoup(html, 'lxml')
retur... |
2435a99b2bfd535980da09b46dee4d39589cfe87 | Thieberius/python | /objektorientiert/laufen.py | 680 | 3.640625 | 4 | class Jogger(list):
"""sportliche klasse für das verwalten von gelaufenen zeiten"""
def __init__(self, altersklasse, zeit=[]):
self.altersklasse = altersklasse
self.gelaufene_zeiten = zeit
def zeiterfassung(self, zeiten):
self.gelaufene_zeiten += zeiten
laufer_Hans = Jogger("M40")... |
e9bc3fc44ce652fe0d1ffb71635b4e6b08ef2d0f | gsaukov/python-machine | /core/days100/12.py | 1,210 | 3.75 | 4 | s = input('give me a string')
l, d = 0,0
for c in s:
if c.isalpha():
l=l+1
elif c.isdigit():
d=d+1
else:
pass
print('Letters', l)
print('Digits', d)
import re
p = input('enter password: ')
x = True
while x:
if(len(p) < 6 or len(p) > 16):
break
elif not re.search(... |
fa8402577e91cc0061b5a47177bb7a8d19d0a601 | d4rkr00t/leet-code | /python/leet/761-special-binary-string.py | 836 | 3.609375 | 4 | # Special Binary String
# https://leetcode.com/problems/special-binary-string/
# hard
#
# The number of 0's is equal to the number of 1's.
# Every prefix of the binary string has at least as many 1's as 0's.
# Choose two consecutive, non-empty, special substrings of S, and swap them.
#
# Time: TBD
# Space: TBD
#
# Sol... |
7ad92efd300cebb2edf4e83640fb9e1ce61b5797 | k8thedinosaur/labs | /needswork_atm.py | 3,320 | 4.3125 | 4 | # # Lab: ATM Interface
#
# Save your solution in a directory in `practice/` named `atm-interface`.
#
# An account will be a class named `Account` in a module named `account`: it will have private attributes for the balance and interest rate.
# Remember to underscore `_` prefix any private attributes.
# A newly-instanti... |
9d6c71959d37f8341d7ef29266ded6a186943f3f | JoshBatchelor777/Rock-Paper-Scissors_Game-Python2.7- | /rspPython_CodeBackup.py | 2,140 | 4.125 | 4 | ###
# Rock, Paper, Scissors!
###
# Version: Python 2.7.13
#
# Author: Josh Batchelor, 12/5/2017
#
# Purpose: Make a simple RPS game.
#
import time
import random
import math
moves = ['rock','paper','scissors']
cp = "Computer "
pl = "Human "
pPts = 0
cPts = 0
print("Rock, Paper Scissors game. You vs. {}".form... |
f744677868fdcf0178c4676cfafd33ecdf83e89a | artbohr/codewars-algorithms-in-python | /7-kyu/father-and-son.py | 610 | 3.890625 | 4 | def sc(s):
return ''.join([x for x in s if s.count(x.lower())>0 and s.count(x.upper())>0])
'''
#Task:
Every uppercase letter is a Father, The corresponding lowercase letters is the Son.
Given the string ```s```, If the father and son both exist, keep them. If it is
a separate existence, delete them. Return the r... |
098f73aa57663128df4ddc7be94e5527ef3cc224 | lilyfofa/python-exercises | /exercicio6.py | 295 | 4.09375 | 4 | import math
n = int(input('Digite um número: '))
#print('O dobro do número {} é igual a {}. Seu triplo equivale a {}. Sua raiz quadrada vale {}.'.format(n,(n*2),(n*3),math.sqrt(n)))
print(f'O dobro do número {n} é {n*2}, o triplo vale {n*3} e sua raiz quadrada equivale a {pow(n,1/2)}')
|
57507fada8e7f34764de2e85919b97c3baecd630 | Jstanislaus/Matrices | /PythonApplication29/PythonApplication29.py | 32,579 | 3.828125 | 4 | import random
from debugprint import Debug
import time
loop = True
global dim3
def func1():
i = 0
array = []
attempt2 = 0
j = 0
attempt = 0
temp = 0
x0 = []
x1 =[]
x2 = []
x3 = []
x4 = []
x5 = []
x6 = []
y1 = []
y2 = []
y3=[]
dim3 = 0
drake = 0
... |
9bae794cfe8ef48a39300cfd2f51ea6d9deec401 | PriyankaKhire/ProgrammingPracticePython | /Word Search Speed Coding.py | 1,776 | 3.828125 | 4 | #Word Search
#https://leetcode.com/problems/word-search/
class Solution(object):
def __init__(self):
self.neighbors = [[-1, 0], [1, 0], [0, -1], [0, 1]]
def isValid(self, row, col, board):
if(row >= 0 and row < len(board)):
if(col >= 0 and col < len(board[0])):
... |
5a3f4b296aa4be34844f480734d69a6aebdbac62 | hevalenc/Curso_Udemy_Python | /classes3.py | 1,021 | 4.46875 | 4 | #aula sore Herança Simples - este arquivo está associado a aula_86
#a herança ocorre de cima para baixo, ou seja, a super classe (classe mão não herda funções de outras classes) e a
#sub-classe (classe filha) herda funções da super classe
class Pessoa: #esta classe é chamada de super classe
def __init__(self, nome... |
52336ba193ad7d081e2292c1dfd5baef42766b6f | Vampirskiy/helloworld | /venv/Scripts/Урок1/in_type.py | 138 | 3.609375 | 4 | age=input('сколько вам лет?')
period=20
age_period=int(age)+period
print('через', period,'вам будет',age_period) |
f38755586f5f15b1e59b52c3eaa381300d185dc3 | ryoichi551124/PythonBasic | /q5.py | 263 | 3.75 | 4 | list1 = [10, 20, 30, 40, 10]
list2 = [10, 20, 30, 40, 50]
def check_list(list):
if list[0] == list[-1]:
flug = True
else:
flug = False
print(f'Given list is {list}')
print(f'result is {flug}')
check_list(list1)
check_list(list2) |
f05859d048c6acadb3359e843fc37662bc01d58a | saedmansour/University-Code | /Artificial Intelligence/AI Multi Robot/Multi_robot/src/search/utils.py | 4,413 | 3.5625 | 4 | '''
Provide some widely useful utilities. Safe for "from utils import *".
'''
import operator, math, random, copy, sys, os.path, bisect, re
import heapq
# Inifinity should be a really large number...
infinity = 1.0e400
#########################
## Data Structures ##
#########################
# Some implementati... |
5c64e81a3c59c5c88f8f38b4a66ba2d98a2a40cd | Chandra-mouli-kante/Python-100-Days-Coding | /Sumof fibnocci.py | 377 | 3.53125 | 4 | '''
fib series: 0 1 1 2 3 5 8 13 21 34 55 89
Ex: 30
21+8+1
Ex: 10
8+2
algo approach:
Ex:30
21
30-21=9
8
9-8=1
1
'''
'''
def nearfib(n): #30,9
a,b=0,1
while n>=b:
if n==b:
return b
a,b=b,a+b
print(a) #21,8,1
return nearfib(n-a) #9,1
... |
ca7bda5a5111b574d86c5cefcd37c371a7d778ef | m-squared96/ODE-Solvers | /lv_exercise_8-2.py | 1,494 | 3.78125 | 4 | #!/usr/bin/python3
'''
This script is a solution to Exercise 8.2 of Newman and solves the
Lotka-Volterra equations:
dx/dt = (alpha)x - (beta)xy, dy/dt = (gamma)xy - (delta)y
where x and y represent the populations of prey and predators in 1,000's
respectively (so they're approximately continuous to three decimal ... |
82045f2b99f6d0317790a17ed2eca4c43f03fc38 | Muktai-Suryawanshi/String-in-python | /LUR.py | 140 | 3.546875 | 4 | i = "SOFTWARE AND HARDWARE"
print(i.lower())
print()
j = "hello world"
print(j.upper())
print()
k = "Save,Trees"
print(k.replace("v","r")) |
8cb1c673931dc0a158c24f42bcce3ceead888324 | craighawki/python_bootcamp | /averageheight.py | 473 | 4.125 | 4 | #!/usr/bin/env python
# 🚨 Don't change the code below 👇
student_heights = input("Input a list of student heights ").split()
for n in range(0, len(student_heights)):
student_heights[n] = int(student_heights[n])
# 🚨 Don't change the code above 👆
#Write your code below this row 👇
tot = 0
count = 0
for num in s... |
ae3b3c9f1a62ad181c2b3cc7bfcbb4349ba680e3 | Masetto97/Symbolic-Melody-Identification | /extra/utils/lang_utils.py | 3,897 | 3.796875 | 4 | #!/usr/bin/env python
"""
Common language-related functionality, typically involving introspection.
"""
from functools import wraps
def enum(*sequential, **named):
"""
Return an enum with the specified names
Parameters
----------
Returns
-------
Example
-------
>>> M... |
efea7a0e91571502ae180e81f11f34687c803dd4 | bobbygata/cti110 | /M2HW1_Crawford.py | 463 | 3.828125 | 4 | # CTI-110
# M2HW1 - Distance Traveled
# Robert Crawford
# 9/6/2017
# speed, distanceAfter6, distanceAfter10, distanceAfter15
speed = 70
time = 6
time2 = 10
time3 = 15
distanceAfter6 = speed * time
distanceAfter10 = speed * time2
distanceAfter15 = speed * time3
print ("The total miles at ... |
9c817c94d0040b5e23223848d95b21f3f0b4ab63 | qeedquan/challenges | /codeforces/1213A-chips-moving.py | 1,734 | 4.15625 | 4 | #!/usr/bin/env python
"""
You are given n chips on a number line. The i-th chip is placed at the integer coordinate xi. Some chips can have equal coordinates.
You can perform each of the two following types of moves any (possibly, zero) number of times on any chip:
Move the chip i by 2 to the left or 2 to the right... |
83d64ee15ae56ecbd6fe764ddd3c2dd651b22729 | lsDantas/Hacker-s-Guide-to-Neural-Networks-in-Python | /backprop_practice.py | 1,012 | 4.09375 | 4 | import math
# Multiply Gate
x = a * b
# and given gradient on x(dx), we saw that in backprop we would compute:
da = b * dx
db = a * dx
# Add Gate
x = a + b
da = 1.0 * dx
db = 1.0 * dx
# Let's compute x = a + b + c in two steps:
q = a + b # Gate 1
x = q + c # Gate 2
# Backward Pass:
dc = 1.0 * dx # Backprop Gate 2
d... |
d8d642d084f1fac10004c216fab9ad1b3599fcd6 | rhiroyuki/46SimplePythonExercises | /exercise04.py | 378 | 3.953125 | 4 |
"""
Write a function that takes a character (i.e. a string of length 1)
and returns True if it is a vowel, False otherwise.
"""
def isVowel(character):
return character in 'aeiou'
def isVowel2(character):
if character in 'aeiou':
return True
else:
return False
# tests
if __name__ == "_... |
f9caadf0ff0f2e1f1a8957b9337336a285cf5060 | CodecoolWAW20171/web-askmate-project-sejsmogrzmoty | /ui.py | 2,891 | 3.71875 | 4 |
# Note: no safeguard against wide columns - terminals wrap long lines.
# If use suspect wide column be sure to stretch terminal beforehand or
# run fullscreen
def print_table(table, headers={}, head_form=['<'], cell_form=['<']):
"""
Prints table with data.
Args:
table (list): list of dictionaries... |
4b7c8b5939824bb66a5cf6e5704ac858e6158b35 | 123wtywty/ccc-2004-j | /2014/j2.py | 209 | 3.765625 | 4 | input()
str1 = input()
v_a = 0
v_b = 0
for i in str1:
if i == 'A':
v_a += 1
elif i == 'B':
v_b += 1
if v_a > v_b:
print('A')
elif v_a < v_b:
print('B')
else:
print('Tie')
|
e3a2a93ae901a793c00bfcb123388dfb011f910a | shen-huang/selfteaching-python-camp | /19100401/shense01/d3_exercise_calculator.py | 677 | 4.125 | 4 | def add(x,y):
return x + y
def subtract(x,y):
return x - y
def multiply(x,y):
return x * y
def divide(x,y):
return x / y
print("选择运算方式:")
print("1、+")
print("2、-")
print("3、*")
print("4、/")
num1 = int(input("输入第一个数字:"))
choice = input("输入运算器选择(1/2/3/4):")
num2 = int(input("输入第二个数字:"))
if choice == ... |
851c0d5f833fbb9985c91e8dd24a528cafe9ee78 | wk968/Tarot | /tarot.py | 948 | 3.65625 | 4 | import random
import json
class Card:
def __init__(self,suit,val):
self.suit = suit
self.value = val
def show(self):
return ("{} of {}".format(self.value,self.suit))
class Deck:
def __init__(self):
self.cards = []
self.build()
def build(self):
... |
3fe9c22ab3812a9a350bca53cc59e793cf838919 | MrHamdulay/csc3-capstone | /examples/data/Assignment_2/hnkluk001/question1.py | 691 | 4.09375 | 4 | # Luke Henkeman
# HNKLUK001
# Assignment 2, Question 1, CSC1015F
# 7 March 2014
def leapyear():
input_year = eval(input("Enter a year:\n"))
leap400int = input_year // 400
leap400nml = input_year / 400
leap4int = input_year // 4
leap4nml = input_year / 4
leap100int = input_year // 100... |
835eef481c878855a0658c6f182866d945326cc5 | cham0919/Algorithm-Python | /프로그래머스/탐욕법/큰_수_만들기.py | 731 | 3.59375 | 4 | """https://programmers.co.kr/learn/courses/30/lessons/42883?language=python3"""
numberList = [
"1924",
"1231234",
"4177252841",
"1000"
]
kList = [
2,
3,
4,
1
]
returnList = [
"94",
"3234",
"775841",
"100"
]
def solution(number, k):
answer = []
cnt = k
for... |
8fc056b5b10d5e0ff2e3506dfc61900c648b9e84 | shae128/CodeLearning | /Python/PythonCertification/Exersices/PCA_5_5_10.py | 347 | 3.9375 | 4 | class ThisIsClass:
def __init__(self, val):
self.val = val
ob1 = ThisIsClass(0)
ob2 = ThisIsClass(2)
ob3 = ob1
ob3.val += 1
print(ob1 is ob2)
print(ob2 is ob3)
print(ob3 is ob1)
print(ob1.val, ob2.val, ob3.val)
str1 = "Mary had a little "
str2 = "Mary had a little lamb"
str1 += "lamb"
print(s... |
0f54ad7dfac2458f054f6dad3673285acf634ae0 | atulya-kairati/100_days_of_code | /day_63/sql_databases/flask_sql_alchemy_basics.py | 2,119 | 3.5 | 4 | from flask import Flask
from flask_sqlalchemy import SQLAlchemy
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///new_book_database.db'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
db = SQLAlchemy(app)
class Book(db.Model):
id = db.Column(db.Integer, primary_key=True)
title = ... |
a69135fecce7531a572e9586bbb217c582ea16f0 | Mekhdievm/homework | /1/ex4.py | 397 | 3.515625 | 4 | def ex4(width, length, height):
if (width < 15) and (length < 15) and (height < 15):
return "Коробка №1"
elif length > 200:
return "Упаковка для лыж"
elif (width > 15 and width < 50) or (length > 15 and length < 50) or (height > 15 and height < 50) :
return "Коробка №2"
else:
return "Стандартная коробка №... |
1e4ea92627ee155981eccd241e36b4585ab26610 | anobhama/Intern-Pie-Infocomm-Pvt-Lmt | /Python Basics/q23_vowelConstanont.py | 312 | 4.0625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sun Aug 9 00:27:35 2020
@author: Anobhama
"""
#(Q23)WAP to input a character and check whether it is a vowel or consonant.
ch=input("Enter a character : ")
if ch in ['a','e','i','o','u','A','E','I','O','U']:
print("It is a vowel")
else:
print("It is a consonant") |
7aa11cf30f3a4bf5b75776c66d9025f5584e67e5 | kmdubs/ProjEuler | /14.py | 464 | 3.703125 | 4 | def seq(num):
count = 1
while num != 1:
if num % 2 == 0:
num = num/2
else:
num = 3*num+1
count += 1
return count
num = []
i = 0
while i < 1000000:
num.append(i+1)
i += 1
maxChain = 0
chainNum = 0
chain = 0
for x in num:
if x % 1000 == 0:
print x
chain = seq(x)
if chain > maxChain:
maxChain ... |
bd0526850e38ddd1df9d821abc6278a708797a10 | centos-zhb/PythonPractice | /Python基本数据类型/Dictionary.py | 1,031 | 3.8125 | 4 | # -*- coding:utf-8 -*-
'''
字典(Dictionary)是python中的另一个非常有用的内置数据类型。
列表是有序的对象结合,字典是无序的对象集合。两者之间的区别在于:字典当中的元素是通过键来存取的,而不是通过偏移存取。
字典是一种映射类型,字典用"{ }"标识,它是一个无序的键(key) : 值(value)对集合。
键(key)必须使用不可变类型。
在同一个字典中,键(key)必须是唯一的。
1、字典是一种映射类型,它的元素是键值对。
2、字典的关键字必须为不可变类型,且不能重复。
3、创建空字典使用 { }。
'''
dict = {}
dict['one'] = "1 - 菜鸟教程"
dict[... |
8e1c545d1c5642e30571f4375369433df08bfc15 | Hajer29/BikeShareData | /BikeShareData.py | 6,554 | 3.96875 | 4 | import time
import pandas as pd
import numpy as np
CITY_DATA = { 'washington': 'washington.csv',
'chicago': 'chicago.csv',
'new york': 'new_york_city.csv'
}
def get_filters():
print('Hello! Let\'s explore some US bikeshare data!')
# TO DO: get user input for c... |
378ac430b3aee16d342f6409adcb12dc73780e2a | dhumindesai/Problem-Solving | /educative/modified_binary_search/search_range.py | 1,339 | 3.59375 | 4 | def search_range(nums, target):
result = [-1, -1]
left = 0
right = len(nums) - 1
mid = -1
while left <= right:
mid = (left + right) // 2
if nums[mid] == target:
result = [mid, mid]
break
elif target > nums[mid]:
left = mid + 1
els... |
4648c6272ba7630b4f8a02d493353cf47fd8806f | dong-pro/fullStackPython | /p1_basic/day01_07base/day02/03_while循环.py | 1,434 | 3.578125 | 4 | # 数数 1-100
# count = 1
# while count < 101:
# print(count)
# count = count + 1
# 让用户一直去输入内容, 并打印. 直到用户输入q的时候退出程序
# while True:
# content = input('请输入一句话,(输入q退出程序):')
# if content == 'q':
# break # 打断. 终止当前本层循环
# print(content)
# flag = True
# while flag:
# content = input('请输入一句话,(输... |
a8ad7437bc1bf66cbd87eb639142e9e1e713a88d | DennisSnijder/HU-PROG-1 | /Lesson6/pe6_2.py | 286 | 3.6875 | 4 | list_of_strings: list = eval(input("Give in a list seperated by comma's : "))
if len(list_of_strings) < 10:
print('The list should be at least 10 words long.')
exit(1)
newList: list = []
for i in list_of_strings:
if len(i) == 4:
newList.append(i)
print(newList)
|
120b4f9e700ec23b47b655ef5689e5517f98e128 | Nelsonkioko/password-locker | /credentials_test.py | 1,068 | 3.859375 | 4 | import unittest
from credentials import Credential
class TestCredentials(unittest.TestCase):
"""
Class to perform credentials test
"""
def setUp(self):
"""
This function will create a new instance of Password before each test
"""
self.new_password = Credential("twitter"... |
0344773c3c87fa316cf07630a6d997087917e332 | bharatgupta99/beginner-python-projects | /99 beer bottles.py | 616 | 3.703125 | 4 | numbers = [x for x in range(99, -1, -1)]
for i in numbers:
if i == 1 :
l1 = str(i) + ' bottle of beer on the wall, ' + str(i) + ' bottle of beer.'
l2 = 'Take one down and pass it around, ' + 'no more' + ' bottles of beer on the wall.'
elif i == 0:
l1 = 'No more bottles of beer on the wall, no more bottles o... |
99230579033b5fa134816e1303b342cd51d3fefc | parmarjitendra/Python | /package01/Practical28.py | 150 | 4.1875 | 4 | str1 = input("Enter any String : ")
if ( str1[::-1] == str1 ) :
print( str1 , " is a palindrome" )
else:
print( str1 , " is not palindrome")
|
1f9ee06b5e532ef1eb4491d42ad5ce9a4d1b5973 | Agata999/exercises | /zipping and enumerating lists.py | 284 | 3.6875 | 4 | projects = ['Brexit', 'Nord Stream', 'US Mexico Border']
leaders = ['Theresa May', 'Wladimir Putin', 'Donald Trump and Bill Clinton']
dates = ['2016-06-23', '2016-08-29', '1994-01-01']
for n, (p, d, l) in enumerate(zip(projects, dates, leaders)):
print(f'{n+1}. The leader of {p} started {d} is {l}')
|
11ba83bdd3a15fe378b1f3fe88d3157431492af0 | dashuai888/Python_Study | /Python_Study/dashuai/chapter02/1-AdvancedFeatures/demo3.py | 1,945 | 4.25 | 4 | #!/usr/bin/env python3
# --*-- coding: utf-8 --*--
"""
迭代
如果给定一个list或tuple,我们可以通过for循环来遍历这个list或tuple,这种遍历我们称为迭代(Iteration)。
"""
# list这种数据类型虽然有下标,但很多其他数据类型是没有下标的,但是,只要是可迭代对象,无论有无下标,都可以迭代,比如dict就可以迭代:
d = {'a': 1, 'b': 2, 'c': 3}
for key in d:
print(key)
# a
# c
# b
# 因为dict的存储不是按照list的方式顺序排列,所以,迭代出的结果顺序很可能不一样。... |
5298cd42f14ce4459272b7c3e0bdabddc8fb0339 | AshurMotlagh/CECS-100 | /Lab 21-2.py | 327 | 4.0625 | 4 | pi=3.14
def main():
rad=float(input("Enter the radius of the circle: "))
area=find_area(rad)
print("Value of PI inside main is: ", pi)
print("Area of the circle = ", area)
print("Area of the circle upto 2 decimal points = ", format(area, '.2f'))
def find_area(a):
area=pi*(a**2)
return area
... |
0053d5b50d250f17e8b1aea7fd69aea71bf826e4 | BJV-git/Data_structures_and_Algorithms | /Data_structures_and_Algorithms/arrays/set_matrix_zeroes.py | 692 | 3.671875 | 4 | # for constant space solution: do a dfs at every zero we encounter
# logic is encode decode : nwo here we are encoding in terms pf its row and column to mark if thats z zero ro w or column
def zeromatrix(matrix):
row,col,first = len(matrix), len(matrix[0]), not all(matrix[0])
for i in range(1,row):
f... |
947f8075cff6da338df8a679f891a3cefc1e3e52 | LeRoiFou/mooc_sequences | /ex012_matrix.py | 1,338 | 4.28125 | 4 | """
Écrire une fonction print_mat(M) qui reçoit une matrice M en paramètre et affiche son contenu.
Les éléments d’une même ligne de la matrice seront affichés sur une même ligne, et séparés par une espace,
les éléments de la ligne suivante étant affichés sur une nouvelle ligne.
Exemple
L’appel suivant ... |
c35c3e74eade3ca2ae6ace20cbf32fdf6bdfec06 | gabriellaec/desoft-analise-exercicios | /backup/user_230/ch35_2020_04_06_20_14_19_245411.py | 153 | 3.90625 | 4 | lista=[]
while num!=0:
num=int(input("Escolha um número:")
lista.append(num)
if num==0:
soma=sum(lista)
print (soma)
|
56bdc8240f83da6470785d5eb26537aea27c4214 | comeeasy/study | /python/sw-academy-python2/list_tuple/prac17.py | 317 | 3.765625 | 4 | '''
두 개의 리스트 [1,3,6,78,35,55]와 [12,24,35,24,88,120,155]를 이용해
양쪽 리스트에 모두 있는 항목을 리스트로 반환하는 프로그램을 작성하십시오.
'''
list1, list2 = [1,3,6,78,35,55], [12,24,35,24,88,120,155]
print([num1 for num1 in list1 for num2 in list2 if num1 == num2]) |
7ce013fc79994d116d8e487fe2f0b7af7876bd68 | Suwadith/Python-Tutorial | /Introduction-To-Python/37_files_and_directories.py | 613 | 4.09375 | 4 | from pathlib import Path
path = Path("ecommerce") #if the Path is left empty Path(), it uses the current directory
print(path.exists()) #Check if a folder exists
#path.mkdir() - used for creating directories
#path.rmdir() - used for deleting directories
#path.glob('*.*') - returns all the files within the current di... |
9fe0321247d755958941a235e7e437c3700980ae | Feymus/AutoCaras | /Model/Sujeto.py | 1,722 | 3.703125 | 4 | '''
Clase utiizada para representar cada sujeto junto a su lista de fotografias
Created on Aug 16, 2017
@author: Michael Choque
@author: Nelson Gomez
@author: William Espinoza
'''
class Sujeto(object):
"""
Clase Sujeto
Esta clase es la representacion abstracta de un sujeto
"""
def __init__(self, n... |
c891f6f37594b4a511c6744337956dea5478520e | daviddayan/david-dayan_EP2 | /jogo da forca.py | 8,587 | 3.625 | 4 | # -*- coding: utf-8 -*-
from random import choice
import time
f = open("entrada.txt", encoding="utf-8")
linhas = f. readlines()
n=[]
for c in linhas:
c2=c.strip()
if c2!="":
n.append(c2)
#def desenha(tartaruga, n):
# abre janela do turtle,desenha a forca
while len(n)>0:
chutes=0
acertos=... |
543d628bf554223ab1552a8bd1d9a674936102a8 | mgunawan92/Team_Stats_Tool | /application.py | 7,418 | 3.578125 | 4 | # Import from constants.py the players' data to be used within your program.
import constants
from copy import deepcopy
# deepcopy function obtained from https://stackoverflow.com/questions/14204326/how-to-copy-a-dictionary-of-lists
# read the existing player data from the PLAYERS constants provided in constants.py
# ... |
8a2142604cd0d0b71b09f367573f18772cb7b493 | jose145/trabajo-05 | /impresion 11.py | 795 | 3.78125 | 4 | #input
cliente=input("Nombre y Apellidos:")
nro_dni=int(input("Ingrese numero de DNI:"))
nro_ruc=int(input("Ingese numero de ruc:"))
nombre_libro1=input("Ingrese nombre del 1er libro:")
nombre_libro2=input("Ingrese nombre del 2do libro:")
precio_libro1=float(input("Ingrese Importe del 1ero libro:"))
precio_libro... |
caa751b7b83175d619d1563abbe88d2fbe99c527 | bhavnavarshney/Algorithms-and-Data-Structures | /Python/Binary-Insertion-Sort.py | 228 | 4.25 | 4 | print('****** Binary Insertion Sort **********')
# Used to reduced the number of comparison in Insertion Sort O(log n) but shifting the elements after insertion takes O(n)
# Complexity : O(nlogn)-> Comparisons and O(n*n) swaps
|
6a7cfe53fbfe1091f265bce6f3e02d197124f69d | KaloyankerR/Math-Concepts-For-Developers | /Final project/skip_list.py | 3,266 | 3.671875 | 4 | import random
class Node(object):
def __init__(self, key, level):
self.key = key
self.forward = [None]*(level+1) # list to hold references to node of different level
class SkipList(object):
def __init__(self, max_lvl, P):
self.MAXLVL = max_lvl # Maximum level for this skip list
self.P = P # P is the fra... |
cef361309ff4bd750efedf6bf3bfeedee13ad80f | Official21A/GitCommiter | /Tools/Directory.py | 729 | 3.515625 | 4 | # In this file we only have the methods for checking the existence of the directories.
import os
# This function corrects the path to documents
def correct_path():
os.chdir("./Tools")
# This functions resets the path from documents
def reset_path():
current_pace = os.getcwd()
path_dir = os.path.dirname(... |
e64d0bad1926b009686767e08f185969b0f7e190 | lcantillo00/python-exercises | /12-ClasesObject/ex2.py | 1,935 | 4.1875 | 4 | class Point:
def __init__(self, init_x, init_y):
""" Create a new point at the given coordinates. """
self.x = init_x
self.y = init_y
def get_x(self):
return self.x
def get_y(self):
return self.y
def distance_from_origin(self):
return ((self.x ** 2) + ... |
e54baf7fd3905cf6150bac4c5015a00ff3706a12 | Harshada180201/21-DAYS-PROGRAMMING-CHALLENGE-ACES | /DAY_19/Bubble_Sort.py | 615 | 4.3125 | 4 | def bubbleSort(arr):
n = len(arr)
# Traverse through all array elements
for i in range(n):
# Last i elements are already in correct position
for j in range(0, n-i-1):
# Swap if the element found is greater than the next element
if arr[j] > arr[j+1] :
arr[j],... |
9294f7cc4687f2184764f1d09d467f5f1eac0182 | Dmurav/Data_structures | /linked_list.py | 4,108 | 4.40625 | 4 |
class Node:
#Класс "узел" со строковой репрезентацией значения
def __init__(self, value=None, next=None):
"""Конструктор - инициализирует экзхемпляр класса"""
self.value = value
self.next = next
def __str__(self):
"""Строковое представление экземпляра"""
return str... |
947b079e6283581c59452a1bb92fb7a95cb744ac | shreya12-hash/Speech-To-Text-and-Text-to-Speech-Conversion | /Speech To Text.py | 609 | 3.828125 | 4 | ### An open source contribution by Shreya ###
#import the module speech_recognition
import speech_recognition as sr
r = sr.Recognizer()
sound_file = 'C:/Users/Biswas/Downloads/female.wav'
file_audio = sr.AudioFile(sound_file)
# Now we set the newly read audio file as the source to recognise as speech object
with file... |
a1f60fe5370d4fc133a5c8fbbdff608ba0a56a76 | Darius-Brown/Python-Zed | /strings.py | 373 | 3.6875 | 4 | x = "There are %d types of people" % 10
binary = "binary"
do_not = "don't"
y = "thos who know %s, and those who %s" % (binary, do_not)
print(x)
print(y)
print("I said: %r " % (x))
print(" I also said: '%s'" % (y))
hilarious = "true"
joke_evaluation = "Isn't that joke funny? %r"
print(joke_evaluation % hilarious)
... |
980069f37036377d6ed2529091e5a6503d83d6dd | ESteinman/rps_python | /rps.py | 461 | 4.03125 | 4 | import random
moves = ['rock', 'paper', 'scissors']
player_wins = ['rockscissors', 'scissorspaper', 'paperrock']
player_move = input ("Please choose either rock/paper/scissor: ")
computer_move = random.choice(moves)
print ("Your move was: ", player_move)
print ("Computer choosed", computer_move)
if player_move == ... |
a61b5f4217a90df820cf44c5438d989466d49a69 | Graziela-Silva/Jogos-Games | /Jogo de adivinhação - Guessing game.py | 846 | 3.59375 | 4 | #Jogo de adivinhação
import random
print('\033[33mTente adivinhar o número que estou pensando! \nDica: ele é inteiro e está entre 1 e 10')
num = random.randint(1,10)
cont = 0
op = 's'
while op != 'n':
n = int(input('\033[35mEm qual número eu pensei? '))
if n != num:
cont +=1
print('\n\033[31mHá!... |
2b3b74f580a7eb6fcbe713a3d44567d9a58c0ed2 | Ern-st/advent_of_code_2017 | /2/check.py | 472 | 3.546875 | 4 | #!/usr/bin/env python
from decimal import *
f = open("input.txt")
input = f.readlines()
f.close()
lines = [sorted([Decimal(s) for s in line.rstrip().split("\t")]) for line in input]
checksum = 0
for numberSet in lines:
for number in numberSet:
for modulo in numberSet:
if (number / modulo) % 1 == 0 and (number /... |
6ac12a5e160a1451de4275d02dd2db075613c6e6 | orenlivne/euler | /algorithms/mergesort.py | 1,114 | 3.96875 | 4 | '''
============================================================
Merge sort: O(n log n) time.
============================================================
'''
def mergesort(a):
'''Sorts the array a in non-decreasing order.'''
n = len(a)
return a if n == 1 else list(merge(mergesort(a[:n / 2]), mergesort(a[n ... |
bf2565a88c7724cdeb93c4c65bd281e4670019bc | CityQueen/bbs1 | /Abgaben - HBF IT 19A/20190910/Nicole.py | 200 | 3.796875 | 4 | var1= 5
var2= int (input("zahl eingeben"))
var3= int(input("zahl eingeben"))
var4= var1+var2*var3
print (var4)
var5= 10
var6= 3
print (var5//var6)
var7= "Fitness"
print(a.find("F"))
print(a.find("f")) |
f37a5b301f8acb6ca1eac969a8701bdcb9ece2fe | santia-bot1/Luchopython | /palabra.py | 1,003 | 4.28125 | 4 | # Este programa pide a un usuario que escriba una palabra, la cual luego se mostrara en pantalla
# tambien le pide la cantidad de veces que esta se va a repetir, luego que ingresa el valor numerico
# deberia aparecer un lista con la palabra la cual se repite de forma vertical
# el codigo esta dañado, en el momento no ... |
dbd232fee48eb275f97b99bba1a26af659de09e3 | BrianQcq/LeetCode | /src/19_remove_nth_from_linked_list.py | 364 | 3.5625 | 4 | class Node(object):
def __init__(self, val):
self.val = val
self.next = None
class Solution(object):
def remove(self, head, n):
if not head:
return None
first = Node(0)
first.next = head
pos = cur = first
for i in range(n):
pos = pos.next
while pos.next:
cur = cur.next
pos = pos.next
... |
e7f387e17055df16a96c4ab805edd580fad42a8a | margaretmutinda/functions | /assignment.py | 1,066 | 4.21875 | 4 | """
Given a list of dictionaries containing data such as productName, exclPrice
passed to a function as a parameter, together with the Tax Rate.
Calculate the inclPrice of each products.
Then RETURN a list of dictionaries containing the product and their respective incl prices.
e.g
#input
products = [
{
"p... |
a946169dbb7eed9e3aed51b6a725a46e7523431f | J-Cheetham/MIT-OpenCourseware | /6.0002/PS1/ps1a.py | 5,294 | 4.0625 | 4 | ###########################
# 6.0002 Problem Set 1a: Space Cows
# Name:
# Collaborators:
# Time:
from ps1_partition import get_partitions
import time
#================================
# Part A: Transporting Space Cows
#================================
# Problem 1
def load_cows(filename):
"""
Read the conten... |
d91b3c68a5f819694fefaee965ec7afa3575b267 | madhuri-majety/IK | /Leetcode/multiply_strings.py | 1,599 | 4.25 | 4 | """
Given two non-negative integers num1 and num2 represented as strings, return the product of num1 and num2, also represented as a string.
Example 1:
Input: num1 = "2", num2 = "3"
Output: "6"
Example 2:
Input: num1 = "123", num2 = "456"
Output: "56088"
Note:
The length of both num1 and num2 is < 110.
Bo... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.