blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
c1d928908697a3b201e0446d899b917796cd1e25 | mgparvez/Machine-learning | /project 1/Codes/Linear_Regression/linear.py | 4,121 | 4.0625 | 4 |
#----------------------------------------------Basic matrix operations----------------------------------------------
def mul(x,y):
r=[[0 for i in range(len(y[0]))] for j in range(len(x))]
for i in range(len(x)):
for j in range(len(y[0])):
for k in range(len(y)):
r[i][j] +=x[... |
a673e8c994f6d7d2583337e6613622e622b14a60 | jessicabring/comp110-21f-workspace | /exercises/ex02/fortune_cookie.py | 1,420 | 3.828125 | 4 | """Program that outputs one of at least four random, good fortunes."""
<<<<<<< HEAD
__author__ = "730394024"
=======
__author__ = "730243388"
>>>>>>> bfe00d0bc5e66cd0a568dfd7048add409d018ba1
# The randint function is imported from the random library so that
# you are able to generate integers at random.
#
# Document... |
7869bef66b42800dca1cbb319d84775a6374bb2d | AbdulFaiz123/project | /Q-2.py | 219 | 4.1875 | 4 | #2. Write a program to accept a number “n” from the user; then display the sum of the following series:
n=int(input("enter the value of n"))
sum=1
for i in range(1,n):
sum+=1/1
print(f"sum of series={sum}")
|
6c953f6d724ee7f1fd34371663ace711147554f0 | wa57/info108 | /Lab2/Lab2Problem1.py | 497 | 4.03125 | 4 | #Project Name: Lab 2 Problem 1
#Date: 4/4/16
#Programmer Name: Will Ashman
#Project Description: Lab 2 Homework
KILOMETERS_TO_MILES = 0.6214
#WA - gather input and pass kilometers to conversion
def main():
kilometers = float(input('Distance in kilometers: '))
showMiles(kilometers)
#WA - perform conversion of... |
2987d15451771373a1762a37aeb3c82c1d6a6308 | hongliang5623/vanyar | /script/array/area2.py | 1,317 | 3.6875 | 4 | # -*- coding: utf-8 -*-
def largestRectangleArea(height):
stack, i, area=[], 0, 0
while i<len(height):
print 'len(stack):%s, height[%s] :%s, stack:' % (
len(stack), i, height[i]), stack
last_s = stack[len(stack)-1] if stack else None
print 'last_s:%s, area:%s' % (last_s, ar... |
7842e0c7d3b1b5e9240716be12486f1bc9a9f12b | RaulOrtizMateos/Tarea-02 | /porcentajes.py | 638 | 3.5625 | 4 | #encoding: UTF-8
# Autor: Raul Ortiz Mateos, 01375407
# Descripcion: te dan el numero de hombres y mujeres y debes calcular el porcentaje de ambos
# A partir de aquí escribe tu programa
numeroDeMujeres=13
numeroDeHombres=13
HyM=numeroDeMujeres + numeroDeHombres
PorcentajeDeMujeres= numeroDeMujeres * 100 / HyM
Porc... |
4ee1259129e7435e90e8923e27ade040242636f5 | zhengxiaocai/baseex | /01lxf/pyex005.py | 178 | 3.625 | 4 | # 循环
# 语法结构
# while expression:
# expr_true_suite
# 简单while示例:循环打印1~10
i = 1
while i < 11:
print(str(i)+' ',end='')
i += 1
|
b6894699a2aec81af3a7f15c78fe367d37e2c194 | backman-git/leetcode | /sol6.py | 1,080 | 3.5 | 4 |
class Solution(object):
def __init__(self):
self.picW=0
self.picH=0
def inbound(self,x,y):
if 0<=x and x<self.picW and 0<=y and y <self.picH:
return True
else:
return False
def lonePixel(self,pic,x,y):
if (self.inbound(x,y+1) is False or pic[y+1][x] == "W" ) and(self.inbound(x+1,y) is False ... |
f74aaf7b94d572ced2511191dac83ab493b805bb | bmahesh123/Pythoncode | /BasicPython/concatlist_9.py | 176 | 3.703125 | 4 | def list_concat(list):
output= ''
for data in list:
output = output + str(data)
print(str(data))
return output
print(list_concat([2, 4, 6, 8, 10])) |
65c767ff8d15b17bd9c6046321e79a1eecf8ee45 | dr-dos-ok/Code_Jam_Webscraper | /solutions_python/Problem_75/961.py | 3,316 | 3.5 | 4 | #!/usr/bin/python
import sys, re
try:
input_name = sys.argv[1] # Read in the supplied input file name
except IndexError: # If no name was supplied:
print 'You have not specified an input file.\n' # Return error that no input file name was supplied
sy... |
8fbcc36004571b87448e7f765a4b6445ec585a73 | xingchenshunyu/pythontest | /demo5.py | 338 | 3.5625 | 4 | # encoding= utf-8
'''
for for/else
主要用于 遍历/循环 序列,集合或者字典
'''
a = [[1,2,3],[4,5,6]]
for n in a:
for m in n:
if m == 2:
break # break终止循环
# continue暂停循环
print(m)
else: # for循环一般不使用else
print('EOF') |
4e830f66e3e67a1a05e11acc2f55aafaf6ef700f | arianacabral/Introduction-to-Python | /Atividade 5/Q25.py | 550 | 3.9375 | 4 | # Escreva um programa que leia dois números inteiros positivos e calcule o valor do primeiro número elevado ao segundo número. Não utilize o operador **
numero = [int(input("Informe a base da exponenciação")), int(input("Informe o expoente da exponenciação"))]
if(numero[0] >= 0 & numero[1] >= 0):
resultado = 1
... |
2891438699b09c289252b15b05212c973a147a75 | cmj123/machine_learning_class | /introduction_to_machine_learning_and_deep_learning_in_python/pca.py | 1,295 | 3.53125 | 4 | # Import the libraries
import numpy as np
from sklearn.decomposition import PCA
from matplotlib import pyplot as plt
from sklearn.datasets import load_digits
import matplotlib.cm as cm
# 8x8 pixel per image - > 64 features !!! Humans are not able to cope with this
# This is why we use PCA -> reduce the dimensions: we ... |
e93415ddc35bd6d6d606b30924fd2caaeaa1498d | Naveen1331/DSA_Algorithms | /Prime_number.py | 563 | 4.15625 | 4 | #Method1
num = -1
if num<=0:
print("Number is not a prime Number")
else:
for i in range(2,num):
if num % i==0:
print("Number is not a Prime Number")
break
else:
print("Number is prime Number")
#find all the prime numbers in the given range
start=in... |
dd65f1cb997e94145e4ef1b7a280722c290f678a | stasvorosh/pythonintask | /BIZa/2014/Zyabko_A_A/Task_3_45.py | 537 | 3.703125 | 4 | # Задача № 3. Вариант 45
# Программа вводит имя и запрашивает его псевдоним
# Зябко Антон
#13. 04. 2016
print("Мартин Андерсон \nПод каким псевданимом он был известен?")
psev=input("Ваш ответ:")
if (psev)!=("Нексё"):
print("Неверно!")
input("\n\n\nНажмите Enter для завершения")
exit
else:
print("Все верно! М... |
768ace048d26d54b989704ba1c3ed6ec016a559f | KodianKodes/alx-higher_level_programming-1 | /0x04-python-more_data_structures/9-multiply_by_2.py | 298 | 3.9375 | 4 | #!/usr/bin/python3
def multiply_by_2(a_dictionary):
if a_dictionary is not None:
dict = {}
tmp = {}
for key, value in a_dictionary.items():
newval = value * 2
tmp = {key: newval}
dict.update(tmp)
return (dict)
return None
|
92cedf86a31c0c30819693b54e577d3e2e146994 | xavierliang-XL/git-geek | /geekprogramming/assignment/assignment01/Q4.py | 189 | 3.75 | 4 | list=(1,2,3,4,5,6)
counto=0
counte=0
for i in range(0,len(list)):
if list[i]%2==0:
counte+=1
continue
counto+=1
print(f'odd num:{counto}')
print(f'even num{counte}') |
a3d2139a8d6a0bc54ce802ccfbca3ce2952a30fb | cgi0911/LeetCodePractice | /lc0020_ValidParatheses/lc0020.py | 765 | 3.875 | 4 | class Solution(object):
def isValid(self, s):
"""
:type s: str
:rtype: bool
"""
stk = [] # Empty list as stack
match = {')': '(', ']': '[', '}': '{'}
for c in s:
if (c == '(' or c == '[' or c == '{'):
stk.append(c)
e... |
2d8aced1c2fe32e35dc06882bb61e79569485b87 | Jafoor/Leet-Code-Solved-Problems | /Python Language/Queue/4 . size.py | 327 | 3.78125 | 4 | class Queue:
#declearing stack
def __init__(self):
self.queue = list()
#pushing values
def Add(self, data):
self.queue.insert(0,data)
#size of Queue
def size(self):
return len(self.queue)
queue = Queue()
queue.Add("Mon")
queue.Add("Sun")
queue.Add("Kun")
print(queue.s... |
8f3bfd1498f999191f9ba3d04e04d5b6b925ea3e | satoshun-algorithm-example/atcoder | /past20191214/is_it_a_number.py | 177 | 3.71875 | 4 | def main():
s = input()
digits = '0123456789'
for c in s:
if c not in digits:
print('error')
return
print(int(s) * 2)
main()
|
3a2d4f07a94746d8fbd634df8bad89bce6e5ff8e | varunkumar032/lockdown-leetcode | /july2020/solutions/day26_AddDigits.py | 506 | 4.15625 | 4 | # Given a non-negative integer num, repeatedly add all its digits until the result has only one digit.
# Example:
# Input: 38
# Output: 2
# Explanation: The process is like: 3 + 8 = 11, 1 + 1 = 2.
# Since 2 has only one digit, return it.
def addDigits(num):
if len(str(num)) == 1:
return num... |
17bbfd739f10d34fc034af87c4fe6892c72ba879 | adamomfg/lpthw | /ex4ec3.py | 1,309 | 4.5 | 4 | # This is going to assign the int variable 100 to the name cars.
cars = 100
# This is going to assign to the variable space_in_a_car the float value 4.0.
space_in_a_car = 4.0
# This is going to assign the int value of 30 to the variable cars.
drivers = 30
# This is going to assign the int value of 90 to the variable pa... |
11dd98a92581a6ae4be53e29c99d5dcc3b708b41 | NiuNiu-jupiter/Leetcode | /399. Evaluate Division.py | 2,428 | 4.0625 | 4 | """
Equations are given in the format A / B = k, where A and B are variables represented as strings, and k is a real number (floating point number). Given some queries, return the answers. If the answer does not exist, return -1.0.
Example:
Given a / b = 2.0, b / c = 3.0.
queries are: a / c = ?, b ... |
bcc790c07651589b87788bebf42d7083b734d446 | joetechem/cs_python | /cs_python/foundations/interactive_programs/user_input/while_loops/lists_and_dictionaries/remove_instances.py | 1,607 | 4.5625 | 5 | # Python 2.7
# The following example is a rendition from Python Crash Course by Eric Matthes
# The transect example is inspired by my experience in field biology
# Remember, if we want to remove an item from a list, we use the remove() function.
# This worked, because the value we wanted to remove only appeared once ... |
52f5a9e01762e980a71e3aa7d6bc71252f0bcc0c | jellier/HetaoHomeWork | /easy-py-master/220918 3.9-for循环/code_3_9.py | 594 | 3.65625 | 4 | # 获取教程、习题、案例,共同学习、讨论、打卡
# 请关注:Crossin的编程教室
# QQ群:155816967,微信:sunset24678
for i in range(5):
print(i)
n = int(input("输入n:"))
# 正整数版1
for i in range(6, n, 6):
print(i)
# 正整数版2
for i in range(1, n):
if i % 2 == 0 and i % 3 == 0:
print(i)
# 正整数版3
i = 1
while i * 6 < n:
print(i * 6)
i += 1... |
3bea1986ede522226004d204c2627095f6fb59bb | 1tejagowtham/Rail_network_using_graphs | /script.py | 1,685 | 3.78125 | 4 | from random import randrange
from graph import Graph
from vertex import Vertex
def print_graph(graph):
for vertex in graph.graph_dict:
print("")
print(vertex + " connected to")
vertex_neighbors = graph.graph_dict[vertex].edges
if len(vertex_neighbors) == 0:
print("No edges!")
for adjacent_v... |
4e0b600741dec46cff3208a9c82c15bd3a17fe04 | Mahajan09/Hacktoberfest-Python | /labels.py | 349 | 3.5625 | 4 | from tkinter import *
root= Tk()
root.title("calculator")
root.geometry("300x300")
label1 = Label(root, text="Write Here")
label1.grid(row=0, column=0)
label2 = Label(root, text="Write Again")
label2.grid(row =1, column=0)
entry1= Entry(root)
entry2=Entry(root)
entry1.grid(row=0, column=0)
entry2.grid(row=1,... |
ffa1b9ddc8de1d0b4323c9654328f31e9f8a648c | salman079/python | /helloworld/If_else 2.py | 322 | 3.9375 | 4 | weight = int(input('Weight? '))
print (type(weight))
kg_lb = input('(L)bs or (K)g? ')
if kg_lb.lower() == 'l':
converted = weight / 2.2
print(f'converted to {converted} kg')
elif kg_lb.upper() == 'K':
converted = weight * 2.2
print(f'converted to {converted} lbs')
else:
print('select correct option... |
eb42a00600d06efb20f8cd6fae09b1801a38106a | ananyae-24/ML-repo | /regression/mySimple_linear_regression.py | 657 | 3.71875 | 4 | import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
dataset=pd.read_csv("Salary_Data.csv")
X=dataset.iloc[:,:-1].values
y=dataset.iloc[:,-1].values
from sklearn.model_selection import train_test_split
X_train,X_test,y_train,y_test=train_test_split(X, y,test_size=.2,random_state=1)
from sklearn.linear... |
e6df16251b397b52f7ae063f89336148e1c9df00 | connordear/projecteuler_problems | /python solutions/ProjectEuler2.py | 585 | 3.84375 | 4 | #Each new term in the Fibonacci sequence is generated by adding the previous two
#terms. By starting with 1 and 2, the first 10 terms will be:
#1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...
#By considering the terms in the Fibonacci sequence whose values do
#not exceed four million, find the sum of the even-valued terms.
# F... |
157d4e49061334970ea6940378d07ef2cd1108f5 | ihsin/durak | /website/durak_game/deck.py | 1,117 | 4.09375 | 4 | from random import shuffle
from .card import Card
class Deck:
"""Class representing a deck of cards
Attributes:
cards: List[Card]
The cards in the deck
"""
def __init__(self, lowest_card: int = Card.SIX):
"""Initialize the deck
Only cards with symbols greater... |
87c41ca80eb0f6226023ff9abc9d9767c4660a35 | ohyoungjooung2/pycode | /pairfind.py | 368 | 3.703125 | 4 | #Find pair count. below ar pair count would be
#(10,10),(10,10),(20,20)=>count is 3
ar=[10,20,20,10,10,30,50,10,20]
ar=[6,5,2,3,5,2,2,1,1,5,1,3,3,3,5]
def findpaircn(ar):
from collections import Counter
d=dict(Counter(ar))
print(d)
r=0
for v in d.values():
if v >= 2:
r+=(v//2)
... |
a121f32dc88c2febee13789935dd3ab6f222f91f | mdimovich/PythonCode | /Old Tutorial Code/pythonTut14.py | 769 | 4.3125 | 4 | # Enter a string to hide in uppercase
# Secret Message:
# Original Message:
# 1. Accept uppercase string from user
# 2. Run through the string converting each character to unicode and putting them in a new string
# 3. Print Secret Message
# 4. Convert back to characters by cycling through 2 at a time and print the orig... |
dd1643c3f2295ed144cc953938ecbb5bd5b3cb11 | iwj/manning | /chapter11/qa_2.py | 208 | 3.65625 | 4 | import time
start_time = int(raw_input("How many seconds? "))
for i in range(start_time, 0, -1):
print i,
for j in range(i, 0, -1):
print "*",
print
time.sleep(1)
print "BLAST OFF!"
|
fec18fd4167eba9b193cdd1e22f57c121f020894 | burhansaydin/SnakeGame | /scoreboard.py | 1,078 | 3.65625 | 4 | from turtle import Turtle
FONT = ("Arial", 14, "normal")
ALIGNMENT = "center"
class ScoreBoard(Turtle):
def __init__(self):
super().__init__()
with open("data.txt") as f:
current_score = int(f.read())
self.high_score = current_score
self.pu()
self.score = 0
... |
7b729404e042160c58770ff752e7feb60bc854c8 | mutaharrikihsan12/Data-Science-Study | /1st Exam - Python Fundamental/Muhammad Ihsan M_Exam1_Python Fundamental.py | 2,966 | 3.921875 | 4 |
print('Name : Muhammad Ihsan Mutaharrik')
print('Class : JC Data Science')
print('Exam 1_Python Fundamental_Answer')
print('\n')
#Jawaban no 2
def countVowel(word):
word = word.lower()
word = list(word)
vocal_list = []
for item in word:
if item in 'aiueo':
v... |
ba708484729736992551511e464c188209133aaf | yonilip/cs_logic | /code/propositions/syntax.py | 9,049 | 3.953125 | 4 | """ (c) This file is part of the course
Mathematical Logic through Programming
by Gonczarowski and Nisan.
File name: code/propositions/syntax.py """
NOT = '~'
AND = '&'
OR = '|'
NOR = '-|'
NAND = '-&'
IMPLIES = '->'
IFF = '<->'
MUX_GATE = '?'
MUX_SEP = ':'
MUX = MUX_GATE + MUX_SEP
T_str = 'T'
F_str = 'F'
... |
c54c63ed1434c62d0cda2d6565e612fcda2d114d | Environmental-Informatics/building-more-complex-programs-with-python-brucewong23 | /program_5.2.py | 1,003 | 4.3125 | 4 | ####################
# Header
# Jan. 22 2020
# Shizhang Wang
# 0027521360
# this program checks Fermat's last theorem in exercise 5.2 in thinkpython 2
"""
Created on Wed Jan 22 14:28:19 2020
@author: wang2846
"""
### prompt to ask for user input after providing basic information
def user_input():
print('Enter a, b... |
dec97d415a535cf6dfdb29e742e2a9ea3d7a7a56 | Carrollkx/jianzhi-offer | /空格替换.py | 970 | 4.0625 | 4 | #-*- coding:UTF-8 -*-
'''
请实现一个函数,将一个字符串中的空格替换成“%20”。
例如,当字符串为We Are Happy.则经过替换之后的字符串为We%20Are%20Happy。
'''
class Solution:
def replace_space(self, s):
if type(s) is not str:
return
spacereplace = []
for item in s:
if item == ' ':
spacereplace.appe... |
1308e9fae47b7a76fca92eb574368bb0966739be | renatomarquesteles/estudos-python | /Maratona de programaçao/Aquecimento Final 2018/problema_B.py | 389 | 3.53125 | 4 | D = int(input())
l1 = input().split()
l2 = input().split()
l3 = input().split()
digito = []
result = ''
braille = [
'.***..',
'*.....',
'*.*...',
'**....',
'**.*..',
'*..*..',
'***...',
'****..',
'*.**..',
'.**...',
]
for i in range(D):
digito.append(l1[i] + l2[i] + l3[i])
... |
38a7fb5ace822ac273fba9faea205e01b6727c36 | akanksha6082/Assignments | /assignment_01/ArmstrongNumber.py | 714 | 4 | 4 | def find_order(number):
i = len(str(number))
return i
if __name__ == "__main__":
# take input from the user
while True:
try:
LowerLimit = int(input("Enter lower range: "))
UpperLimit = int(input("Enter upper range: "))
except ValueError:
print("Impr... |
4274860039eb36592b70ba3cdf8453c16518f0ff | dreaM-107/Checkers-AI-BOT | /checkers/piece.py | 1,060 | 3.578125 | 4 | import pygame
from .constants import white, black, square_side, grey, crown
class Piece:
padding = 18
outline = 2
def __init__(self, row, col, color):
self.row = row
self.col = col
self.color = color
self.king = False
self.x = 0
self.y = 0
... |
077ca2a31a8e8636f3aeb4222f5209bcedc21f6f | 4nything/Proyectos-Python | /MadLibs.py | 1,301 | 3.828125 | 4 | mainText = ["On monday at 7:30pm, I was walking to ",
" when I met my cousin ",
" , and we started to talk. After 15 minutes talking, I remembered that I left the ",
" in the oven, so I started to run to ",
". When I arrived there, a ",
" was looking at me in ... |
da35acc8506c03997e7ec3c74016f1339219e16f | 2082033549/FCXPYN | /homework2/shuchujishu.py | 214 | 3.75 | 4 | #3 编写一个函数, 传入一个数字列表, 输出列表中的奇数;
from random import randint
list1=[randint(0,100) for _ in range(1,11)]
print("奇数有:")
for i in list1:
if i%2==1:
print(i) |
9aeaa2835947b49f548fa480e513c0844b515838 | Sonny-skyez/CSV_Report_Processing | /Main.py | 4,330 | 3.578125 | 4 | #!/usr/bin/env python
'''CSV Report Processing
This script is intended to read CSV input file from current working
directory and write proper report file aggregated by date
and country code.
Example input line:
01/21/2019,Mandiana,883,0.38%
Example output line:
2019-01-21,GIN,883,3
Scripts supports only ... |
e32c47450adb08e5d7cd6ebaadf2f929a0b83b85 | shilingzi/LearnPythonBIT | /chapter2/practice/PythonDraw.py | 1,449 | 3.984375 | 4 | """
实例2: Python蟒蛇绘制
描述
这是"实例"题,与课上讲解实例相同,请作答检验学习效果。
使用turtle库,绘制一个蟒蛇形状的图形。... |
8d5e1ffb9d30f0c849b839ad5996c224d1df2ce8 | RandyG3/TheGreatCourses | /Python/12. Python Standard Library, Modules, Packages/ImportOS.py | 303 | 3.625 | 4 | import os
prefix = '/Users/tbear03/'
path = input('Enter the directory: ')
path = prefix + path
num_files = 0
with os.scandir(path) as it:
for entry in it:
if not entry.name.startswith('.') and entry.is_file():
num_files += 1
print('Directory contains', num_files, 'Files.')
|
486b3e3c77ce91267ca357f62735af4a968a657c | TrevorSpitzley/AcademicRepo | /DiscreteMathProjects/Homework1.py | 3,455 | 4.34375 | 4 | # This file is for programming set #1, in MTH 325
# We are writing two functions. One function will determine the degree of a given vertex.
# The other function will take a degree sequence and determine if the degree sequence represents a
# valid tree. All code written here is that of my own.
# The first function must... |
beccd55fa5326c5becb4f04ed24a292c35e15bbf | dlogushiv/AutomationTrainee | /OOP/Figures/main.py | 1,632 | 3.625 | 4 | from OOP.Figures.Circle import Circle
from OOP.Figures.Ellipse import Ellipse
from OOP.Figures.Rectangle import Rectangle
from OOP.Figures.Square import Square
from OOP.Figures.Triangle import Triangle
from OOP.Figures.EquilateralTriangle import EquilateralTriangle
from OOP.Figures.IsoscelesTriangle import IsoscelesTri... |
e4910c7a6677b2c060d0e6bc608c75d55482ed97 | Bruledamien/Fontstellations | /Scripts/proccess png/resize_and_crop_pngs_smart.py | 1,488 | 3.578125 | 4 | '''
Script to resize pngs to a smaller/compressed size as of August 13, 2016.
'''
import json
import os
from math import floor
from PIL import Image
# Careful : this version is based on the graph_node_2 file and can lead to errors if files missing in path dir.
# previous version of script just processes list of file... |
a21e1ff5160efa6790f7741172c8e1b96b9b7b7f | DevPopat/ConnectFourBoardGame | /connect_four_board.py | 17,148 | 4.28125 | 4 |
#Importing an object column, in order to use its attributes and functions
from column import Column
#Importing an object chip, in order to use its attributes and functions
from chip import Chip
#Creating a Board object, containing information about whole board- which includes the game board and cells in the board
c... |
406a587268088b28f632b9d8743aada8eac3d2c1 | mingzhouzhu22/numerical_linalg | /polynomial_interpolation.py | 1,858 | 3.875 | 4 | import numpy as np
import numpy.linalg as la
import matplotlib.pyplot as plt
"""
Benjamin Pachev
Math 510, Bigham Young University
Python code for 12.2 from Trefethen
"""
def vandermonde(x, deg=None):
"""
Contruct the vandermonde matrix at the data points defined by x.
If deg is provided, the matrix will... |
f4463562c54851804987188ec184cc657c0eaf76 | tisnik/python-programming-courses | /Pandas/examples/20_check_types_1.py | 1,039 | 3.6875 | 4 | #!/usr/bin/env python3
# vim: set fileencoding=utf-8
"""Reading CSV file that contains column with integer values (some are missing)."""
import pandas
from voluptuous import Schema
def print_data_frame(df):
"""Print the whole data frame."""
print("Data frame")
print("---------------------------")
pr... |
17ebb5839ffe29bc40dc702a7f60f8ff91039caa | Benlewis3k/Project-Euler | /ProjectEuler4.py | 546 | 4.3125 | 4 | """ A palindromic number reads the same both ways. The largest palindrome
made from the product of two 2-digit numbers is 9009 = 91 x 99.
Find the largest palindrome made from the product of two 3-digit numbers."""
def find_pal(x,y):
max_pal = 0
for i in range(x,y+1):
for j in range(i+1, y+1):
... |
ffd1e7d9a0777dda04c40342e261591abafbc586 | Daneidy1807/CreditosIII | /07/ejercicio3.py | 447 | 3.96875 | 4 | """
Ejercicio 3. Escribir un programa que muestre los cuadrados
(un numero multiplicado por si mismo) de los 60 primeros numeros
naturales. Resolverlo con for y con while
"""
"""
# WHILE
contador = 0
while contador <= 60:
cuadrado = contador*contador
print(f"El cuadrado de {contador} es {cuadrado}")
cont... |
fd3b159eee33b63963490efd2f3247d32f5e95af | Star-Coder-7/OOProgramming | /accounts.py | 1,929 | 3.78125 | 4 | import datetime
import pytz
import random
class Account:
"""Simple account class with __balance (money)."""
@staticmethod # A method where self is not needed
def _currentTime():
utcTime = datetime.datetime.utcnow()
return pytz.utc.localize(utcTime)
def __init__(self, name, balance)... |
2a98033f997648a477bc3e9f09f347f2e024563e | gabrieleliasdev/python-mentoring | /ex21.py | 516 | 3.859375 | 4 | def adicionar(a, b):
print(f"Adicionar {a} + {b}")
return a + b
def subtrair(a, b):
print(f"Subtração: {a} - {b}")
return a - b
def multiplicar(a, b):
print(f"Multiplicar {a} * {b}")
return a * b
def dividir (a, b):
print(f"Divisão {a} / {b}")
return a / b
print("Vamos fazer alguns c... |
b8ad6b5e30fd5649dc0c2bd2a1b29600e9f4235b | ghdehrl12345/student.py | /student.py | 1,599 | 3.515625 | 4 | DB_STUDENT = [
{
"name" : "도기",
"code" : "#000000"
},
{
"name" : "지섭",
"code" : "#111111"
}
]
def startApp():
print("+++++++++++++++++++++++++++++++++++++++++++++")
print("1. student list")
print("2. create student")
print("3. delete student")
print("... |
41f61b2380d2b46cbd964dc10e3dd6e4ac4b9962 | xiaoxinw/challenge | /py_solutions/add_two_nums.py | 2,095 | 3.734375 | 4 | # coding: utf-8
# Definition for singly-linked list.
class ListNode(object):
def __init__(self, value):
self.val = value
self.next = None
def to_representation(self):
cur = self
values = []
while cur:
values.append(str(cur.val))
c... |
e41bc2c8865c67d92db3b8f0625751820935bf78 | esslushy/Swahili-Translator | /swahiliTranslator.py | 2,225 | 4.125 | 4 | quit = False
#AddTense
def addTense(suffix, verb):
tense = input("What tense? (past/present/future): ")
if(tense.lower() == "past"):
print(suffix + "li" + verb)
return
elif(tense.lower() == "present"):
print(suffix + "na" + verb)
return
elif(tense.lower() == "future"):
print(suffix + "ta" + verb)
return... |
dadf37d3c4839e2546b3da1377b2e4e0a93983f8 | GoldenRaven/python_learning_note | /nowcoder/huawei/18.py | 719 | 3.921875 | 4 | def my_key(string):
return string.upper()
while True:
try:
s = input()
# s = 'A Famous Saying: Much Ado About Nothing (2012/8).'
l = []
ll = []
for i, v in enumerate(s):
if not v.isalpha():
l.append((i, v))
else:
ll.... |
5571befd2fca979ce6eeef0d48400197ef49f340 | ZCKaufman/python_programming | /spiralmatrix.py | 2,938 | 3.53125 | 4 | import unittest
class MyMatrix:
matrix = [[int]]
listNum = 0
listSize = 0
def spiralOrder(self, matrix: [[int]]) -> [[int]]:
finalList = []
while(True):
if(len(matrix) != 0):
# Local Variable Assignment
i = 0 # Horizontal Index
... |
30cca2c4c91dfc9c36e34f6975efbe7093352b30 | turingtei/Python_Tutorial | /lesson_4a_ex3.py | 602 | 4.03125 | 4 | '''
Given the list 𝚊 in the template, make a new copy 𝚋 of the list 𝚊
using the function 𝚕𝚒𝚜𝚝. Update the first entry in 𝚋 to be zero.
What happened to the first entry in 𝚊? Explain your answer
(in a comment).
'''
# List reference problem
###################################################
# Student should e... |
e8f9840bbc0d7a51e277676226c5a34466f4574b | Weless/leetcode | /python/数组/896. 单调数列.py | 1,063 | 3.71875 | 4 | from typing import List
class Solution:
def isMonotonic(self, A: List[int]) -> bool:
tag = 0
up,down = True,True
for i in range(1,len(A)):
if A[i] < A[i-1]:
up = False
break
if up:
return True
for i in range(1,len(A)):
... |
02a9a899bdd7ac7c59609863b6ac40cf6dc53c37 | cgazeredo/cursopython | /mundo02/aula-14_exercicios-058-melhorando-o-028.py | 613 | 3.875 | 4 | from random import randint
from time import sleep
tentativas = 1
r_num = randint(0, 10)
print('COMPUTADOR: Pensei num número!')
chute = int(input('Tente acertar o numero que o computador pensou de 0 a 10: '))
print('PROCESSANDO...')
sleep(3)
while chute != r_num:
r_num = randint(0, 10)
print('Você errou. O núm... |
19616fa1ade2f9fad9d9e0875bfe1b72555a19b8 | hari-bhandari/closed-examination | /question_1.py | 367 | 4.15625 | 4 | def create_triangle(n):
"""
creates a triangle
Args:
n (int): size or height of triangle.
Returns:
str: The triangle
"""
if n < 0:
return None
completed_string = ''
for i in range(1, n + 1):
completed_string += ('x' * i) + (n - i) * '-' + '\n'
return... |
24ee61541fe04a66c9f763f50b840330735263bf | jay51/wallbreakers | /week4/selection_sort.py | 270 | 3.578125 | 4 |
def s_sort(arr):
for idx, el in enumerate(arr):
min = idx
for i in range(idx +1, len(arr)) :
if arr[i] < arr[min]: min = i
arr[idx] = arr[min]
arr[min] = el
return arr
test = [5, 5, 2, 6, 3]
print(s_sort(test))
|
a03b8e5aaa3772a6ea4b7ef602e97b67361c441a | sigmax6/sigmav | /Python/guessNumber.py | 361 | 3.59375 | 4 | #!/usr/bin/python
################################
#PYTHON TEMPLATE FOR SIGMAX6
#
#
#
################################
#print("Helloworld!")
print("Welcome!")
g = input("Please input your number: ")
guess = int(g)
if guess == 5:
print("You win!")
else:
if guess > 5:
print("Too big!")
else:
... |
9249d057fb85a4bd6344558a75b5fbd896891367 | coldmax88/PyGUI | /Tests/16-modal_dialog.py | 1,689 | 3.671875 | 4 | from GUI import Window, ModalDialog, Label, Button, \
TextField, application
from GUI.StdButtons import DefaultButton, CancelButton
from testing import say
def modal_dialog():
#global dlog ###
dlog = ModalDialog(title = "Spanish Inquisition", size = (200, 140))
dlog.place(Label(text = "Surprise!!!"), left = 20, to... |
e2fd2da9877857a3b2467456fa3a5b628aa1e6da | LeonardoMelloTrindade/Codigos-Python | /Báskara.py | 836 | 4.0625 | 4 | print('-----BÁSKARA-----')
from math import pow, sqrt
print('A estrutura inicial é nx² + nx + n = 0')
a = int(input('Digite o primeiro valor: '))
b = int(input('Digite o segundo valor: '))
c = int(input('Digite o terceiro valor: '))
print(f'{a}x² + {b}x + {c} = 0')
#ACHANDO O DELTA
delta = pow(b, 2) - (4 * a * ... |
783e51dd7fa25afe43987e13bf7236dcb0352034 | mleone18/Yahtzee | /DiceClass.py | 684 | 3.78125 | 4 | from random import randint
class Die():
def __init__(self):
self.numbers = [randint(1,6), randint(1,6), randint(1,6), randint(1,6), randint(1,6)]
print(self.numbers)
def reroll(self):
x = 1
while x < 3:
ans = str(input("What n... |
4010a4c9e624383fa5c0045c2e3373c7ffe035b2 | knishant09/LearnPythonWorks_2 | /Practise/19.py | 131 | 4.28125 | 4 | import os
str = raw_input("Enter the value of string:")
print str
if str[:2] == "Is":
print str
else:
print 'Is' + str
|
48692d1b04d046c7692c6690cce315f278fcb028 | dmcdekker/interview-and-coding-problems | /easy-python-problems/product-except-current/product_except_current.py | 1,356 | 3.59375 | 4 | import unittest
from functools import reduce
def sum_except_current(lst):
result = []
for idx1, num1 in enumerate(lst):
curr_sum = 1
for idx2, num2 in enumerate(lst):
if idx2 != idx1:
curr_sum *= num2
result.append(curr_sum)
return result
def sum_except_... |
ec46dd7a74b3a37b844fccaa5de6304d9b79bb15 | akurnosov/follower | /follower.py | 4,614 | 3.53125 | 4 | import time
import os
import sys
def tail_mode(path_file, deep=10):
"""
Printing new lines in the file
"""
with open(path_file, "r") as f:
lines = f.read().splitlines()
for line in range(-deep, 0):
last_line = lines[line]
print(last_line)
def get_last_n_lines(... |
970d989d0d93fe26412aeec34a946e33c1dfc571 | alonglry/personal-ledger | /ledger/utils/algorithm.py | 1,614 | 3.515625 | 4 | ##############################################################
# name: yield_calculation
# type: function
# import by: ledger/modeles/accounts
# use: calculate yield using Newton's method
##############################################################
# version author description date
# 1.0 awai... |
7003b1983cd4cbf1489b221b7ab87c69eeac2d1b | sebbas711/mision_tic_G11 | /Sesion14/14.16_string_subcadena.py | 279 | 3.65625 | 4 | frase = "Bienvenidos a una nueva sesion del curso de python una version actualizada"
sub_cadena = input("Digite la cadena que desea validar: ")
resultado = frase.rfind(sub_cadena)#Busca en el string y retorna la posicion donde encuentra el parametro que se le envia la funcion |
d61c40c2a5530b53ebd12a75c4a39b720b727c49 | chenyang1999/coding | /pythonOP/Code bundle_0971OS/Chapter 8/p1_c08.py | 8,487 | 3.859375 | 4 | #!/usr/bin/env python3
# Chapter 8 -- Decorators and Mixins -- Cross-Cutting Aspects
# ------------------------------------------------------------
# .. sectnum::
#
# .. contents::
#
# Decorator Example 1
# ================================
# Use of builtin decorators
# ::
import math
class Angle( float ):
_... |
2da39954e12973f9a55c3748ae2d0094c6a9fff2 | luzcn/ml-training | /demo/pandas_demo.py | 1,082 | 3.96875 | 4 | import numpy as np
import pandas as pd
def exercise():
data = pd.read_csv('../src/data/Consumer_Complaints.csv')
# Create a new DataFrame with only the 'Abbrev' and 'Population' columns
states = pd.read_csv('../src/data/states.csv')
states = states[['Abbrev', 'Population']]
states.columns = ['Sta... |
163db4e79a0daf0446a70fa61b9b8cce2ecedba8 | echernenko/python | /py_project/pro1.py | 178 | 3.96875 | 4 | name1 = "Hello"
name1 = "Hi"
name2 = 10
name3 = 10.5
mylist1 = [1, "Hi there", 10.5, name2]
string1 = "h" + "1";
print(mylist1);
print(string1);
# print(type(name2), type(name3));
|
6d8487d65a7be5e0065530f8f297bd55f57b8774 | XBY-fight/leetcode-files | /leetcode/venv/94.py | 822 | 4.09375 | 4 | #!/usr/bin/python
#-*- coding: utf8 -*-
# Definition for a binary tree node.
#二叉树中序遍历
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def inorderTraversal(self, root):
"""
:type root: TreeNode
:rtype: List[in... |
64804819f5631856393c2285ba9c10a44b03dbe3 | lissa0987/2017-osnov-programm | /project/spelcheck.py | 6,486 | 4 | 4 | import re
import sys
#we have two parts of the programm. The first one counts edit distance (the idea was found https://habrahabr.ru/post/117063/ and http://www.let.rug.nl/~kleiweg/lev/). The second one does the checking. The input is txt file with the text that should be edited. The output looks like word - its corr... |
18fb93e24a538bbefc012acb783ff5ce549cefe3 | efaro2014/Dojo-Assignments | /python_stack/python/oop/zoo.py | 2,745 | 4.34375 | 4 | # Start by creating an Animal class, and then at least 3 specific animal classes that inherit from Animal.
# (Maybe lions and tigers and bears, oh my!) Each animal should at least have a name, an age, a health level, and happiness level.
# The Animal class should have a display_info method that shows the animal's name,... |
22c6be7e4498213e558e07aee5488bfba764e4cc | vkagwiria/thecodevillage | /Python Week 4/Day 2/exercise3.py | 929 | 4.5 | 4 | # ask the user for the number of students
# for each student, ask for their name, registration number,name of the school
# for each student, ask for the number of subjects they'd like to enter
# for each subject, record the marks
# output the student details:
# - name of student
# - school name
# - subject and m... |
d28c7ba8299f8a8ff4b6dd9ba6cdd87ff3c5ad50 | oliviervos/python_workbook_174_Solution | /IntroductionToProgramming/E4.py | 231 | 4.03125 | 4 | width = float(raw_input("please enter the width of the room(feet)"))
length = float(raw_input("please enter the length of the room(feet)"))
area = width * length
area_acres = area/43560
print "room area in acres is : ", area_acres
|
fabc26619f387af693244d43fab4f7bea187cf76 | wsilveirasouza/Python_Completo | /secao_3/funcoes2.py | 379 | 3.703125 | 4 | '''
FUNÇÕES (def) em Python - return
'''
def funcao(var):
return var
# print(var)
variavel = funcao('Valor que eu quero')
if variavel:
print(variavel)
else:
print('Nenhum valor.')
# tratamento de exceções
def divisao(n1, n2):
if n1 > 0 and n2 > 0:
return n1 / n2
else:
print('C... |
1bdb7fba342fd239636486f65aff55307a0f1eb1 | Agrn96/Practica1_LF | /cargar_Archivo.py | 2,113 | 3.84375 | 4 | from tkinter import *
from tkinter import filedialog
def cargar_Archivo(lista):
"""Funcion para abrir el archivo que se utiliza para la programa
Args:
lista (class): Listas para guardar informacion del archivo
"""
filename = filedialog.askopenfile(filetypes=(('text files', 'txt'),))
crear... |
9d962f005748003e397afd7fa70c6009392a3a59 | SeperinaJi/PythonExercise | /favorite_languages.py | 1,291 | 4 | 4 | favorite_languages = {
'jony' : 'ruby',
'seperina' : 'python',
'sarah' : 'java',
'lisa' : 'python'
}
print("Seperina's favorite language is " +
favorite_languages['seperina'].title()
+'\n')
for key, value in favorite_languages.items():
print(key.title() +
"'s favorite languag... |
bf271adcfccf7cff2ddf80f11db893e158230961 | AdamZhouSE/pythonHomework | /Code/CodeRecords/2371/49405/248489.py | 242 | 3.640625 | 4 | T = int(input())
for t in range(T):
a = input().lower()
s = ''
for i in range(len(a)):
if a[i].isalpha():
s += a[i]
n = len(s) // 2
if s.endswith(s[:n][::-1]):
print('YES')
else: print('NO') |
b5fc83316c4d4a0f1cbad0018ae786a864a3f653 | HuichuanLI/Artificial-Intelligence-realization | /test_game.py | 1,873 | 3.53125 | 4 | # -*- coding:utf-8 -*-
# @Time : 2020/12/26 9:23 下午
# @Author : huichuan LI
# @File : test_game.py
# @Software: PyCharm
from Game import *
random.seed(666)
f52 = Fig52Game()
ttt = TicTacToe()
def gen_state(to_move='X', x_positions=[], o_positions=[], h=3, v=3):
"""给予一个游戏状态,X在棋盘上的状态,O在棋盘上的位置"""
moves = se... |
0d57c91f24277531c80f9c45789551a22773c27a | Yigang0622/LeetCode | /validSquare.py | 1,206 | 3.53125 | 4 | # LeetCode
# validSquare
# Created by Yigang Zhou on 2020/10/7.
# Copyright © 2020 Yigang Zhou. All rights reserved.
from typing import List
# 593. 有效的正方形
# https://leetcode-cn.com/problems/valid-square/
class Solution:
def distance(self, p1, p2):
return ((p2[1] - p1[1]) ** 2 + (p2[0] - p1[0]) ** 2) **... |
1f9582ee98211594991d7e4f430997ff03d5009e | dikshaa1702/ml | /day25/human_activity_recognition.py | 3,105 | 3.53125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sat Jun 8 09:15:43 2019
@author: DiPu
"""
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
train_data=pd.read_csv("train.csv")
test_data=pd.read_csv("test.csv")
features_train=train_data.iloc[:,:-1].values
labels_train=train_data.iloc[:,-1].values
feature... |
043286abaa5d076974cb48c609533e81f7152c3d | mdyzma/Educational | /Using Databases with Python/week_5_1.py | 1,185 | 3.703125 | 4 | '''
Retrieving GEOData
Download the code from http://www.pythonlearn.com/code/geodata.zip - then unzip the file and edit where.data to add an address nearby where you live - don't reveal your actual location. Then run the geoload.py to lookup all of the entries in where.data (including the new one) and produce the geo... |
e622f23f8d4265bcc6b6d6104155e0bc71329e2d | Aryank47/PythonProgramming | /sumofNnatural.py | 96 | 3.84375 | 4 | n1 = int(input("Enter a number: "))
res = 0
while n1 != 0:
res += n1
n1 -= 1
print(res) |
5d7f8007ef0d61882b7d25061535ab115c701c78 | chicory-gyj/JustDoDo | /pre_test/2forth.py | 103 | 3.578125 | 4 | #!/usr/bin/python
forth=raw_input('enter the year:')[3]
print 'the forth number of the year is '+forth
|
f3c37e9e76743cceb1090aff7cbc299ed5535a45 | CurryMentos/algorithm | /test9.py | 1,301 | 3.515625 | 4 | # !/usr/bin/env python
# -*-coding:utf-8 -*-
"""
# File : test9.py
# Time :2021/6/16 15:22
# Author :zyz
# version :python 3.7
"""
# 猜数字小游戏
import random
l = list(random.sample(range(10), 4))
# print(l) # 打印数组
count = 0 # 猜测次数
max_count = 8 # 最大猜测次数,可修改以增加或降低难度
while count < max_count:
prin... |
5df7507e614c1a2ef8a1bd1716481c4ef702b4e3 | Iverance/leetcode | /449.serialize-and-deserialize-bst.py | 2,617 | 3.859375 | 4 | #
# [449] Serialize and Deserialize BST
#
# https://leetcode.com/problems/serialize-and-deserialize-bst
#
# Medium (42.38%)
# Total Accepted:
# Total Submissions:
# Testcase Example: '[2,1,3]'
#
# Serialization is the process of converting a data structure or object into a
# sequence of bits so that it... |
2f63060d85bd802dcedbff9cfd0926c68eabadd5 | hahiti/4_all | /task_6.py | 231 | 3.8125 | 4 | print ("***********************")
print ("task #6")
print ("***********************")
a = 10
b = 2
if b!=0:
c = a/b
print ("Result of a/b (a=d%d, b=d%d) is %.2f" % (a, b, c))
else:
print ("Error: Division by zero!")
|
3880136c69fc91614b7a144c1efeed587066f330 | MaikelTK/BM01-PI7 | /Opdracht-1/1.1A.py | 488 | 3.75 | 4 | ##Opdracht 1 Decrease and conquer
def decrease_and_conquer(list):
index = 0
#while index < list size
while index < len(list):
index_value = list[index]
while index > 0 and list[index - 1] > index_value:
list[index] = list[index - 1]
index -= 1
print(list)
... |
184af6faa54114dd2117838c21bca85c518d39c7 | nami-h/Python | /printing list items <5 letters long and sorting them.py | 223 | 3.640625 | 4 | visited = ["New York", "Shanghai", "Munich", "Toyko", "Dubai", "Mexico City", "São Paulo", "Hyderabad"]
new=[]
for city in visited:
if len(city)<=5:
new.append(city)
print(new)
n=sorted(new)
print(n)
|
74241bc87065aa6eea8c3341208ce769f34414c0 | davidhawkes11/PythonStdioGames | /src/gamesbyexample/eenymeeny.py | 3,965 | 4.09375 | 4 | """Eeny-Meeny-Miny-Moe, by Al Sweigart al@inventwithpython.com
An elimination game for multiple players. Press Ctrl-C to stop.
More info at https://en.wikipedia.org/wiki/Eeny,_meeny,_miny,_moe
More info at https://en.wikipedia.org/wiki/Josephus_problem"""
__version__ = 1
import random, time, sys
SCREEN_WIDTH = 60
RH... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.