blob_id stringlengths 40 40 | repo_name stringlengths 5 127 | path stringlengths 2 523 | length_bytes int64 22 3.06M | score float64 3.5 5.34 | int_score int64 4 5 | text stringlengths 22 3.06M |
|---|---|---|---|---|---|---|
7601d4e5c01fe1e0f377ae459465a4cb0a4f3edf | sam505/Median-of-3-integers | /Median.py | 1,423 | 4.34375 | 4 | # Obtains the median of three integers that the user inputs
def median():
Num_one = input ("Enter your first integer: ")
Num_two = input ("Enter your second integer: ")
Num_three = input("Enter the third integer: ")
if (int (Num_one) < int (Num_two) and int (Num_one) > int (Num_three)):
print ("... |
38ef1f6a57999b2b3dc41b72a7c9339abdfff632 | jiye-ML/tensorflow_study | /study_api/study_matplotlib.py | 7,794 | 4.125 | 4 | '''
学习 matplotlib 图形库
https://morvanzhou.github.io/tutorials/data-manipulation/plt/3-2-Bar/
'''
import matplotlib.pyplot as plt
import numpy as np
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.gridspec as gridspec
''' 基本使用 '''
# 开始
def hello_world():
x = np.linspace(-1, 1, 50)
y = 2 * x... |
f9d5ed731f6aa0badce5bb5528234399a06b7e6d | megulus/code-challenges | /src/cracking_code_interview/one_away.py | 1,193 | 3.953125 | 4 | """
There are three allowable string edits:
- remove a character
- add a character
- replace a character
Given two strings, write a function to determine whether they are one edit
(or zero edits) away
"""
def is_one_away(str1, str2):
if str1 == str2:
return True
if abs(len(str1) - len(str2)) > 1:
return Fa... |
80738173b7d82f1bf34f3d2a0ce6d081bbf074e5 | megulus/code-challenges | /src/phils_challenges/calendar.py | 1,917 | 3.609375 | 4 | STARTYEAR = 1753
STARTDAY = 1
STARTMONTH = 1
MONTHS = {
1: 'January',
2: 'February',
3: 'March',
4: 'April',
5: 'May',
6: 'June',
7: 'July',
8: 'August',
9: 'September',
10: 'October',
11: 'November',
12: 'December'
}
DAYS = {
0: 'Monday',
1: 'Tuesday',
2: 'We... |
2a1b8a2228ce437ac99524607387bf1376c860c3 | sarinat/Project_Algorithm | /model/searchnsort.py | 565 | 3.71875 | 4 |
#=============Classes for searching and sorting =================
class My_searching:
def linear_search(self,pi,source):
for i in source:
if pi in i:
return int(source.index(i))
return False
class My_sorting:
def insertion_sort(self,list_a,index):
for i in... |
95a042bf2c0f6a649769615218391e44a88ad8c4 | sdjukic/DataStructuresInPython | /Nodes.py | 498 | 3.625 | 4 | # Node class that is base for all recursive datastructures
class Node(object):
def __init__(self, data=None, next=None):
self._node_data = data
self.next = next
def __str__(self):
return repr(self._node_data)
class BinaryNode(object):
def __init__(self, data=None, right_child=None, left... |
d63f3014189730c8afbe7f91add852ef729e22f0 | inwk6312fall2019/dss-Tarang97 | /Chapter12-Tuples/Ex12.2.py | 1,579 | 4.21875 | 4 | fin = open('words.txt')
# is_anagram() will take a single text from 'words.txt', sorts it and lower the cases and
# append the original word in the list which will be the default value of sorted_dict() values;
# but, the sorted_word will be in sorted_dict() dictionary along with its value.
def is_anagram(text):
... |
94b19019633272e7bd0ddfa1ece221b8a1ae914d | constantinirimia/Stock-Market-Prediction-using-Machine-Learning-Algorithms | /Artificial_Neural_Network_LSTM.py | 4,907 | 3.984375 | 4 | '''
In this program I implemented a artificial neural network to predict the price of Apple stock -AAPL,
of the 13th month using as values the last 12 month averages
'''
import math
import pandas as pd
import numpy as np
import pandas as pd
from sklearn.preprocessing import MinMaxScaler
from keras.models impo... |
a8c9c4dde14a815ba977fbabab1c7ed21241a39e | walter-agf/Practica_6 | /Doc/Experimentos/Punto_8.py | 516 | 3.5625 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Apr 27 09:19:25 2020
@author: gualteros
"""
def contar(w):
cont = 0
for i in range (0,len(w)):
if w[i] == "," :
cont += 1
if w[i+1] == ",":
cont -= 1
return cont
word = (input("Ingrese un texto... |
eda1e4896914b149c0b4d2ebdf9d9897bdad9aba | Skripnikov/K16-1-Skripnikov | /s.py | 110 | 4.03125 | 4 | name = input("What your name?: ")
if name == "Vlad":
print("Ooo, Hello Vlad!")
else:
print("Who are you?") |
003f7100eb14c66e4cb37cc083aead9252cb7446 | mleyfman/abstract-card-game | /AbstractGame.py | 284 | 3.671875 | 4 | class AbstractGame:
"""Abstract class for running a card game"""
def __init__(self, players=[], deck=None):
self.players = list(players)
self.deck = deck
def play_game(self):
"""Override this function for custom game logic"""
pass
|
bf085ec55d43a61557fa7177b0ce85513a03570b | YunaAnn/LearningPython | /Basics/Break&continue.py | 747 | 4.0625 | 4 | def break_statement():
print('Break if "l" -> Hello world!')
for val in 'Hello world!':
if val == 'l':
break
print(val)
print('The end.')
def continue_statement():
print(' ------------------ ')
print('Continue if "l" -> Hello world!')
for val in 'Hello world!':
... |
30907a6c7f52b6767dd2e95606e50632a6f440e5 | YunaAnn/LearningPython | /Basics/Loops-for.py | 1,197 | 3.875 | 4 |
def sum_all_numbers_stored_in_a_list():
list_of_numbers = [5, 1, 7, 4, 10, 2, 3, 9, 8]
sum = 0
for val in list_of_numbers:
sum = sum + val
print(5, 1, 7, 4, 10, 2, 3, 9, 8,sep='+')
print('=', sum)
def range_function():
print(range(10))
print(list(range(10)))
print(list(range(1... |
5431f42ec87c58d3c8bb6212361f724a74cb8836 | paarinmodi/PythonBeginner | /Python_NP_Station/F_String.py | 535 | 3.953125 | 4 | print('My Grandfather\'s name is Kanaylal Modi')
print('My Grandfather\'s name is Kanaylal Modi')
("My Grandfather's name is Kanaylal Modi")
name='Paarin Modi \'The Great'
print(name)
Paarin Modi 'The Great
favorite_number=3
type(favorite_number)
<class 'int'>
favorite_number="3"
type(favorite_number)
<class 'str'>
moo... |
6e5e12f4d4d5960e787cb3f43d8262207b4b89ae | u-zii/likelion_week4 | /practice.py | 2,674 | 3.59375 | 4 | ## 1번문제 ##
num=int(input("money를 입력하세요 : "))
def what(x):
if x>=10000:
print("고기를 먹는다")
elif x>=5000:
print("국밥을 먹는다")
else:
print("라면을 먹는다")
what(num)
## 2번문제 ##
fruits=[]
fruits.append(input("1번 과일을 입력하세요"))
fruits.append(input("2번 과일을 입력하세요"))
fruits.append(input("3번 과일을 입력하세요... |
2055c96f93ace3ed9e3522707d4534bf678673f5 | Rivals16/dataStructureAndAlgoConcepts | /countingsort.py | 1,084 | 3.828125 | 4 | #! /usr/bin/python3
import time
def countingSort(insertedArray,countArray,sortedArray):
for i in range(len(insertedArray)):
countArray[insertedArray[i]] += 1
print("Counting Array Is : ",countArray)
for i in range(1,len(countArray)):
countArray[i]+=countArray[i-1]
print("Modified Counti... |
8ff14bd737e7d2831108a61ff1c2528969a0ccd0 | akshay-verma/LeetCode | /101_symmetric_tree.py | 1,942 | 3.90625 | 4 | """
Problem 101:
https://leetcode.com/problems/symmetric-tree
"""
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def preOrderTraversal(self, root, result):
if root:
... |
bf0a0135e2488aab99bb96c762a95666f25a332e | akshay-verma/LeetCode | /501_Find_Mode_in_Binary_Search_Tree.py | 1,002 | 3.78125 | 4 | """
501. Find Mode in Binary Search Tree
https://leetcode.com/problems/find-mode-in-binary-search-tree/
"""
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def dfs(self, root, mode):... |
cc2b7ad3f8451a0efccef6304ae212c7bebe8000 | simrit321/heap | /heap.py | 6,466 | 3.75 | 4 | # helper functions
def left(index):
'''Return index's left child index.
'''
return index * 2 + 1
def right(index):
'''Return index's left child index.
'''
return index * 2 + 2
def parent(index):
'''Return index's parent index.'''
return (index - 1) // 2
class MinHeap:... |
244caf73afff5c138a26aed9f68900f7e680d1dc | erik-engel/python_2021 | /mandatory/mandatory-1-erik.py | 3,668 | 4.09375 | 4 | #1. Model an organisation of employees, management and board of directors in 3 sets.
#Board of directors: Benny, Hans, Tine, Mille, Torben, Troels, Søren
#Management: Tine, Trunte, Rane
#Employees: Niels, Anna, Tine, Ole, Trunte, Bent, Rane, Allan, Stine, Claus, James, Lars
bod = {"Benny", "Hans", "Tine", "Mille", ... |
6c2801ad50d50b92fc2b2fd37a423ec731d98612 | chendinghao/ChangeToHTMLorXML | /util.py | 1,483 | 3.828125 | 4 | """
块的收集方法:收集遇到的所有行,直到遇到一个空行,然后返回已经收集到的行,这就是一个块。
之后再次收集,不收集空行和空块。
同时,确保文件的最后一行是空行,否则程序就不知道最后一个块什么时候结束
"""
# coding=utf-8
def lines(file):
“”“
如果去掉 yield '\n' ,并且文件的最后一行不是空行,会发现最后的一个块无法输出
”“”
for line in file: yield line
yield '\n'
# blocks生成器实现了前面说明的方法。当生成一个块后,里面的行会被链接成一个字... |
8d4354d890b46e3c68978895e6b3701d3d350661 | thacdtd/AAI | /gradient-descent/ex.py | 425 | 3.765625 | 4 | # From calculation, it is expected that the local minimum occurs at x=9/4
cur_x = 6 # The algorithm starts at x=6
gamma = 0.01 # step size multiplier
precision = 0.00001
previous_step_size = cur_x
def df(x):
return 4 * x**3 - 9 * x**2
while previous_step_size > precision:
prev_x = cur_x
cur_x += -gamma *... |
bc9354af11d56d91d56b017f5fe63bf8af131641 | wanzongqi/-R- | /solve/41.py | 623 | 3.515625 | 4 | # -*- coding: utf-8 -*-
"""
@author: strA
ProjectEuler-problem-41
"""
def gen_prime(n):
prime = [True]*(n+1)
prime[0] = False
prime[1] = False
for i in range(1,n+1):
if prime[i]:
m = i*2
while m<n:
prime[m] = False
m = m+i
return prim... |
248f8ab1e8cea4a94af7763762d7aa7b82717937 | wanzongqi/-R- | /solve/44.py | 555 | 3.609375 | 4 | # -*- coding: utf-8 -*-
"""
@author: strA
ProjectEuler-problem-44
"""
"""
先写个简单的
"""
import math
def check(n):
if int((1+math.sqrt(1+24*n))/6)==(1+math.sqrt(1+24*n))/6:
return True
else:
return False
def Pentagon(n):
return (n*(3*n-1))//2
i = 1
flag = True
while flag:
j = 1
w... |
35fe96cb91fe25a006e0706444634fc3d23647c3 | wanzongqi/-R- | /solve/12.py | 415 | 3.546875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sun Mar 4 00:46:34 2018
@author: strA
ProjectEuler-problem-12
"""
import math
def factor_count(n):
t = 0
for i in range(1,int(math.sqrt(n))+1):
if n%i == 0:
t += 1
t = 2*t
if math.sqrt(n) - int(math.sqrt(n))<0.001:
t = t-1
retur... |
ca06882d790762caa3ac5eb911468aa445b8ede4 | rbstech/520 | /aula 04/ex_func.py | 427 | 3.859375 | 4 | #!/usr/bin/python3
convidados = []
def adicionar():
'''funcao para adicionar convidados na lista'''
global convidados
qtd = int(input("Digite a quantidade de convidados: "))
print(qtd)
for n in range(qtd):
nome = input('Insira o nome do convidado '+str(n+1)+": ")
convidados.appe... |
40a40ed6d46b5567258631990e697b4b9967862d | zhoushaojun/pythonLearn | /numpyUsage/CodeBeauty/FindAddNumers.py | 1,479 | 3.8125 | 4 | # 寻找快速满足条件两个数
dataList = [5, 6, 1, 4, 7, 9, 8]
# print(dataList)
def heapSort(dataList, start, length):
maxIndex = 0
while start * 2 + 1 < length:
# 查找子节点中最大值
if start * 2 + 2 < length:
maxIndex = start * 2 + 1 if dataList[start * 2 + 1] > dataList[start * 2 + 2] else start * 2 +... |
9e805a66b2cda4c90afc67c31f2ae9bee5653ec6 | gdsa-upc/K-LERA | /DL_features.py | 729 | 3.71875 | 4 | # -*- coding: utf-8 -*-
#Pseudocódigo Deep Learning
''' 1) Leer una imágen de mxm
im.read()
2) hacerle un reshape para crear un vector transpuesto de m^2 píxels
np.reshape()
3) Declarar el modelo de keras que queramos usar.
Modelo=get_alexnet([500,500],nº de lables, true)
4)Pasar la... |
df2ed521a9a2fe9a1f8bfbdf3deb5f90fce6a63d | sakuragi97/HackerRank-Python-Solutions | /30 Days of Code/Day29_Bitwise_AND.py | 474 | 3.734375 | 4 | #!/bin/python3
# def findBitwise(n,k):
# maxBitwise=0
# i=0
# j=i+1
# for i in range(n-1):
# for j in range(n):
# if i&j>maxBitwise and i&j<k:
# maxBitwise=i&j
# print(maxBitwise)
if __name__ == '__main__':
t = int(input())
for t_itr in range(t):
... |
1c4430f3be37984e0ae87bde671416b8424cf83e | oren0e/dl-python | /chapter6/word_embeddings.py | 1,556 | 3.75 | 4 | '''
We will work with the IMDB movie reviews data. We will:
1. Prepare the data
2. restrict the movie reviews to the top 10000 most common words
3. Cut off the reviews after only 20 words.
4. The network will learn 8-dimensional embeddings for each of the 10000 words,
turn the input integer sequences (2D integer tensor... |
1b8cc21c31b5f381963fc24cff708645b856b333 | 11aki/Blackjack | /blackjack.py | 4,550 | 3.515625 | 4 |
import random
Playing = 'Yes'
bal = 1000
bet = 0
suits = ["Spades", "Clubs","Hearts","Diamonds"]
ranks = ["Ace","2","3","4","5","6","7","8","9","10","Jack","Queen","King"]
values = {"Ace":11,"2":2,"3":3,"4":4,"5":5,"6":6,"7":7,"8":8,"9":9,"10":10,"Jack":10,"Queen":10,"King":10}
#################### Card Class ###... |
501bd33d9a67a292b690201842553cbd93e9a1e6 | Brokames/DatabaseVisualizer | /utils/data_gen.py | 5,484 | 3.5 | 4 | import datetime
import enum
import random
from collections import namedtuple
from itertools import islice, starmap
from typing import Any, Dict, Generator, Iterator, Tuple
import pandas as pd
from faker import Faker
class Columns(enum.Enum):
"""Available columns for data generator
NAME[str]: First + Last + ... |
6a98e4477b04720c18143b7f93f4c4317ff67a97 | qianxiaodai/Algorithm | /LeetCode/math_highlights.py | 444 | 3.9375 | 4 | # -*- coding: utf-8 -*-
import math
class Solution:
"""超时"""
def countPrimes(self, n: int) -> int:
count = 0
for i in range(2, n):
if self.isPrime(i):
count += 1
return count
def isPrime(self, n: int) -> int:
for i in range(2, int(math.sqrt(n) +... |
ea5c93d8f01a4851694045ffb8d777558acb0984 | qianxiaodai/Algorithm | /Basic/guess.py | 1,564 | 3.953125 | 4 | # -*- coding: utf-8 -*-
import math
"""
歌德巴赫猜想j
2000以内大于2的偶数能分解为两个素数之和。
"""
def isPrime(n):
for j in range(2, int(math.sqrt(float(n))) + 1):
if n % j == 0:
return False
return True
def getPrime(n):
primes = list()
for j in range(2, n + 1):
if isPrime(j):
pri... |
32118971c5f1acfcd81554eaa09fc9f1e4c48660 | 07Agarg/Course_Programming_Assignments | /Artificial Intelligent/Assignment 1/Solution 1/min_heap.py | 2,589 | 3.53125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Mon Sep 2 04:55:04 2019
@author: ashima
"""
import numpy as np
class Heap:
def __init__(self, Capacity):
self.heap = []
self.length = 0
self.capacity = Capacity
def get_parent(self, index):
return int(index/2)
def isEmpty(s... |
a10c0b370a62e1c80e52f738304304d763055e2d | 07Agarg/Course_Programming_Assignments | /Artificial Intelligent/Assignment 1/Solution 1/AstarNode.py | 865 | 3.71875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Mon Sep 2 05:05:16 2019
@author: ashima
"""
class Node:
def __init__(self, state, parent, g, h):
self.state = state #current_state
self.parent = parent #parent
self.g = g #total cost incurred to ... |
abe22097172d8cc09b071bbbcd5b0114d09946ac | Philippe-Cholet/checkio-mission-next-birthday | /verification/tests.py | 4,895 | 3.6875 | 4 | from datetime import MINYEAR, MAXYEAR, date, timedelta
from random import randint, sample
from string import ascii_uppercase
from my_solution import next_birthday
BASIC_FAMILY = {
'Brian': (1967, 5, 31),
'Léna': (1970, 10, 3),
'Philippe': (1991, 6, 15),
'Yasmine': (1996, 2, 29),
'Emma': (2000, 12,... |
f58a7d93fa29b5801350b4aad34303653ab4a935 | TanapTheTimid/ExpressionSolverExercise | /expression.py | 2,177 | 3.734375 | 4 | def eval(exp):
#algorithm cannot handle 2 signs next to each other
exp = exp.replace("+-","-")
if "(" in exp:
#first open paren
start = exp.find("(")
#find the corresponding closing paren by keeping track of num of open parens until 0 is reached
numparen = 1
... |
c65858019b12bc00cc9733a9fa2de5fd5dda8d14 | asadali08/asadali08 | /Dictionaries.py | 1,662 | 4.375 | 4 | # Chapter 9. Dictionaries
# Dictionary is like a set of items with any label without any organization
purse = dict()# Right now, purse is an empty variable of dictionary category
purse['money'] = 12
purse['candy'] = 3
purse['tissues'] = 75
print(purse)
print(purse['candy'])
purse['money'] = purse['money'] + 8... |
2ee0f1e7152ce48dd69c0692fb6648c2b8a23f0a | Eder-Berno/Practica11_EDA1 | /Grágicas_en_tiempo_de_ejecución.py | 1,874 | 3.5625 | 4 | #Importando bibliotecas
import matplotlib.pyplot as plt
import numpy as np
from mpl_toolkits.mplot3d import Axes3D
#Cargando modulos
import random
from time import time
#Cargando las funciones guardadas en los archivos
from insertionSort import insertionSort_time
#Sólo se necesita llamara a la función prin... |
1ddb981357e0b4de8031bdb08fbd9820c0e61bed | deepsheth3/phishingdata-Analysis | /2nd_data-spam-ham-email_results/spamPolarityScores.py | 3,634 | 3.578125 | 4 | import sys
import csv
import numpy as np
import nltk.data
from nltk.sentiment.vader import SentimentIntensityAnalyzer
from nltk import sentiment
from nltk import word_tokenize
# Adapted from https://programminghistorian.org/en/lessons/sentiment-analysis
if(len(sys.argv) != 3):
print("Usage: python3 spamPolaritySc... |
62a73c88a7b6df3fe6741efe00de04792473582a | shreyakupadhyay/furry-spork-latex | /new_PL_project/lineSegments.py | 4,464 | 3.5 | 4 | '''
Description: Detecting squares from a 2D matrix.
Working status: Final working code for detecting line segments in 2-D matrix.
'''
# and start_node != (row,col))
import sys
# import pandas as pd
coordinates = []
#pts = []
lines = []
extra, sides = 0,0
matrix = []
checks = []
# filename = sys.argv[1] # matrix.tx... |
a3fbe3fa0441f40d6d00fe792dc92e7c0acd2880 | jyj902/Python | /Python/Test_01.py | 286 | 3.734375 | 4 | INPUT =1
while INPUT !=0 :
INPUT = int(input("숫자 입력 :: "))
i=2
while True:
if(INPUT%i == 0):
break
i +=1
if(i == INPUT):
print("소수 입니다.")
else:
print("소수가 아닙니다.")
print("종료 합니다.") |
28dc7a4d6d418166df9a8dad55c7e4beb2d9e5b8 | MichaelCAllan/First-Python-Program | /Michael.py | 158 | 3.984375 | 4 | ints = [1,2,3,4,5]
def listadd(ints):
total = 0
for item in ints:
total += item
return (total)
value = listadd(ints)
print (value)
|
0d49dc317831167e5325ac574df5eafa37dbc73f | Andy-Ho8872/Py-code | /Tkinter/GUI_first.py | 1,793 | 3.5625 | 4 | import tkinter as tk
from PIL import Image, ImageTk
#建立主視窗
win = tk.Tk()
#設定視窗名稱(標題)
win.title("視窗名稱測試")
#設定視窗大小
win.geometry("400x300+800+400") #(寬x高 +X +Y) (用字串表示,後面的 + 前者數字為X軸,後者為Y)---(設定開啟視窗大小預設值及位置)
win.minsize(width=400, height=200) #設定視窗最小值
win.maxsize(width=1024, height=768) #設定視窗最大值
#win.resizable(0, 0)... |
d56c7b7cf04a9375cc7ad1811ca483f1fdbf539f | Andy-Ho8872/Py-code | /20200530.py | 394 | 3.8125 | 4 |
class Cat():
def __init__(self, name, age, gender): # 因為self是class本身 所以第一個不用更動
self.name = name # 在這邊self.的設定 就代表你之後可以用的class屬性
self.age = age
self.gender = gender
Cat_info = Cat("來福", 7 ,"male")
print("姓名:",Cat_info.name,"\n" "年齡:",Cat_info.age,"\n" "性別:",Cat_info.gender)
|
f41b1eeae8a40524834d5879310656caae0f9d2a | LucasSoftware12/EjerciciosPy | /Desafios/9_sensos.py | 2,118 | 3.578125 | 4 | # Un censador recopila ciertos datos aplicando encuestas para el último Censo Nacional de Población y Vivienda. Desea obtener de todas las personas que alcance a encuestar en un día, que porcentaje tiene estudios de primaria, secundaria, carrera técnica, estudios profesionales y estudios de posgrado.
inicio = True
prim... |
edd53043474af7e8aa6c88e60dbafac02d95ace4 | LucasSoftware12/EjerciciosPy | /Desafios/Ejercicios complementarios Condicionales/3_NumeroMayor.py | 453 | 3.921875 | 4 | # Alumno Lucas Medina
print("Ejercicio Número mayor")
numUno = int(input("Ingrese un numero: "))
numDos = int(input("Ingrese un numero: "))
numTres = int(input("Ingrese un numero: "))
if (numUno > numDos) and (numUno > numTres):
print(f"El numero mayor es: {numUno}")
elif (numDos > numUno) and (numDos > numTres)... |
cbdfa681eae3c82c8645345822f9ccfaaa51262f | LucasSoftware12/EjerciciosPy | /Desafios/6_contarSumar.py | 551 | 3.953125 | 4 | while True:
x = int(input("Ingrese el primer numero: "))
z = int(input("Ingrese el segundo numero: "))
if z < x:
print("El segundo numero debe ser mayor al primero, vuelva a ingresarlo")
z = int(input("Ingrese el segundo numero: "))
elif z >= x:
break
cont = 0
cont2 = 0
for i i... |
68376555846fe3e74828dc6ba21da945009484a8 | LucasSoftware12/EjerciciosPy | /Desafios/1_mayorde10.py | 238 | 3.734375 | 4 | # 1) Determinar el número mayor de 10 números ingresados.
mayor = 0
maximo = 10
for i in range(maximo):
num = int(input('Dame un numero: '))
if num > mayor:
mayor = num
print(f"El mayor de los 10 numeros es: {mayor}")
|
da18962e5cab2c784f8cb08336a6bfb61a28772d | SofiaNikolaeva-adey-201/practicheskaya4 | /main2.py | 574 | 3.890625 | 4 | class Person:
def __init__(self, n, s, q = 1):
self.name = n
self.surname = s
self.skill = q
def __del__(self):
print('До свидания, мистер', self.name, self.surname)
def info(self):
return '{1} {0}, {2}'.format(self.name, self.surname, self.skill)
worker ... |
26533d5854323190d839660bb7f41595c9e86789 | justinchen673/Catan-AI | /port.py | 503 | 3.84375 | 4 | """
port.py
This file holds the representation of the Port object, which just holds the
conversion type of the port. resourceType denotes what resource you need to
trade in, and number denotes how many of that resource you need to trade in to
get a resource of your choice.
"""
class Port:
'''
This ... |
b7152d196dff60a8ee56baf10a77cd434862d6c0 | justinchen673/Catan-AI | /board.py | 31,105 | 3.828125 | 4 | """
board.py
This file holds the representation of the board as well as any functions it may
need. It is comprised of the Vertex and Hex classes, which together along some
other structures makes up the Board class.
"""
import copy
from port import Port
from player import Player
class Vertex:
'''
... |
59d35a09fe084cabba6da579babeaabded3b71b8 | beaukinstler/ud036_StarterCode | /entertainment_center.py | 3,062 | 3.625 | 4 | import media
import fresh_tomatoes
# wrapping the job of making a list of movies into a function.
# this function statically builds an array of movies, and returns them.
def make_list_of_movies():
''' this function statically builds Movies() objects,
and returns an array of the Movie() objects '''
a... |
f63e464ce7382566584dd5001f4eb118aa54d20a | Dimitris-Mourtzilas/Plotting-Real-Time-Data | /source_code/main.py | 1,498 | 3.609375 | 4 |
"""
This is program is designed to provide real-time generated data printed
into a csv file.
Further features will include operations on a json file.
"""
from time import *
from random import randint
import csv
class File:
_csv_reader = None
_csv_writer = None
_count = 0
_file = None
def __... |
6033f2105199302bec02fae2146999394e3d8194 | AprajitaChhawi/365DaysOfCode.APRIL | /Day 6 possible words from phone.py | 959 | 3.640625 | 4 | #User function Template for python3
class Solution:
def pos(self,a,lst,dit,string,index,N):
if(len(string)==N):
lst.append(string)
return
cur = dit[a[index]]
for i in range(len(cur)):
self.pos(a,lst,dit,string+cur[i],index+1,N)
def possibleWords(self... |
257338117c3623320284083a0a9f640da89d6701 | AprajitaChhawi/365DaysOfCode.APRIL | /Day 7 check if two arrays are equal.py | 969 | 3.890625 | 4 | #User function Template for python3
class Solution:
#Function to check if two arrays are equal or not.
def check(self,A,B,N):
d={}
for i in A:
if i in d:
d[i]=d[i]+1
else:
d[i]=1
for i in B:
if i not in d or d[i]<=0:
... |
3e8feecdd8c816820a4f663ad9e96eea068475f5 | vincentei/tic-tac-toe | /test.py | 750 | 3.5 | 4 | import unittest
from board import Board
import numpy as np
class TestBoard(unittest.TestCase):
def test_create(self):
b = Board()
equal_elements = np.sum(b.data == np.ones((3,3))*-1)
self.assertEqual(equal_elements,9)
def test_set_piece(self):
b = Board()
b.se... |
2ddad7e073dc0e129cb4da58f53b0a385835dfce | izzyevermore/python-built-in-funcs | /main.py | 562 | 3.8125 | 4 | # Exercise 1
# Grades
# Task: Filter the grades to only display everyone above (and including) 70%
grades = [20,10,90,85,40,75,65,64,12,74,71,98,50]
grades = list(filter(lambda x : x >= 70, grades))
print(grades)
# Exercise 2
# Dog ages
# Convert ages into dog years
dog_ages = [12,8,4,1,2,6,4,4,5]
dog_ages = list(ma... |
26e46d71cbcbf9285f893f2c759c9e3bd9732687 | NavairaRosheen/Task1 | /task1Q6.py | 130 | 3.8125 | 4 | list=[1,2,5,-1,6,0,15]
smallest=min(list)
mini=list[0]
for i in list:
if (i<mini) and (i>smallest):
mini=i
print(mini) |
6b5bde2df0f5bded9656f46e222184df9ebb65da | nhpss921111/Leap-year | /function1.py | 1,143 | 4 | 4 | # -------------題目---------------
"""
寫一個function來判斷是不是閏年(二月會多一天的年)
依照 Wikipedia 的定義
1.公元年分除以4不可整除,為平年
2.公元年分除以4可整除但除以100不可整除,為潤年
3.公元年分除以100可整除但除以400不可整除,為平年
4.公元年分除以400可整除但除以3200不可整除,為潤年
同學可以依照這個定義直接翻譯成程式碼。
function 應該要有一個參數值讓使用者投入(傳遞進去)年分
function 的回傳直(return)應該是布林值,如果是閏年就return True,不就是return Fal... |
ae90634d89b2add6ed79b04c1675465761be5095 | shakib0/BasicPattterns | /pattern7.py | 229 | 3.703125 | 4 | for r in range(5):
for c in range(r+2):
if c<1 :
print((5-r)*' ',r,end = '')
elif c>1:
print('',r,end = '')
while c==2:
c=0
print()
|
622dfa7610474aac2aa08ca4199e324c5a9bd52a | DS-ALGO-S30/PreCourse_2 | /Exercise_5.py | 1,136 | 4.0625 | 4 | import numpy.random as random
# Python program for implementation of Quicksort
# This function is same in both iterative and recursive
def partition(arr, l, h):
#write your code here
ptr=l
pivot=h
for i in range(l,h):
if arr[i]<arr[pivot]:
arr[i], arr[ptr] = arr[ptr],arr[i] # swap
... |
b19a065468ccc7e6db220140e95ff67d8d4bfc9a | Hyun-delv/python-algorithm | /Palindrome.py | 614 | 3.578125 | 4 | from collections import deque
def Palimdrome(s: str) ->bool:
# 리스트 방법을 통해서 풀이
"""
strs = []
for char in s :
if char.isalnum():
strs.append(char.lower())
while len(strs)>1:
if strs.pop(0) != strs.pop():
return False
return True
"""
# ... |
d6bdfd11a791ecdd06062e77a0791eda95f242af | seedor87/pyTexed | /inertion_sort.py | 1,135 | 3.734375 | 4 | from random import randint, uniform
def insertion_sort(list):
ret = list
for j in range(1, len(ret)):
key = ret[j]
i = j
while(i > 0) and ret[i-1] > key:
ret[i] = ret[i-1]
i = i-1
ret[i] = key
return ret
L_than = lambda A, B: A < B
G_than = lambda A... |
eda2bd25cd6719192df085fc58d82a5330e3a130 | eyangs/transferNILM | /appliance_data.py | 1,432 | 3.515625 | 4 | """ A collection of all appliances available. Each appliance has a consumption mean
and standard deviation, as well as a list of houses containing the appliance. """
appliance_data = {
"kettle": {
"mean": 700,
"std": 1000,
"houses": [2, 3, 4, 5, 6, 7, 8, 9, 12, 13, 19, 20],
"channe... |
9a3adac0205258627a994d52259dd5e27dda1051 | eyangs/transferNILM | /remove_space.py | 129 | 3.578125 | 4 | # Removes the spaces from a string. Used for parsing terminal inputs.
def remove_space(string):
return string.replace(" ","") |
dc990e6ecd447a0d729461d3910522b11295b211 | Roshan-Ojha/Agro-Hub | /Answer.py | 355 | 3.609375 | 4 | import sqlite3
conn=sqlite3.connect('answer.db')
c=conn.cursor()
c.execute("""CREATE TABLE IF NOT EXISTS answer (
asked_on text,
answered_on text,
answer text,
photo text,
answerd_by text,
answer_by_email text
... |
14ee4e61bdd207607f67e78ce181252c2e24b03d | VladErm-Data/python | /dz_6.py | 6,861 | 3.53125 | 4 | # 1. Создать класс TrafficLight (светофор) и определить у него один атрибут color (цвет) и метод running (запуск).
# Атрибут реализовать как приватный. В рамках метода реализовать переключение светофора в режимы: красный, желтый,
# зеленый.
# Доп условие я не понял, поэтому не сделал.
from itertools import islice, cy... |
f8327a56682bd0b9e4057defb9b016fd0b56afdd | karagdon/pypy | /48.py | 671 | 4.1875 | 4 | # lexicon = allwoed owrds list
stuff = raw_input('> ')
words = stuff.split()
print "A TUPLE IS SIMPLY A LIST YOU CANT MODIFY"
# lexicon tuples
first_word = ('verb', 'go')
second_word = ('direction', 'north')
third_word = ('direction', 'west')
sentence = [first_word, second_word, third_word]
def convert_numbers(s):
... |
80a5137b9ab2d2ec77805ef71c2513d8fcdf81a0 | karagdon/pypy | /Python_codeAcademy/binary_rep.py | 1,384 | 4.625 | 5 | #bitwise represention
#Base 2:
print bin(1)
#base8
print hex(7)
#base 16
print oct(11)
#BITWISE OPERATORS#
# AND FUNCTION, A&B
# 0b1110
# 0b0101
# 0b0100
print "AND FUNCTION, A&B"
print "======================\n"
print "bin(0b1110 & 0b101)"
print "= ",bin(0b1110&0b101)
# THIS OR THAT, A|B
#The bitwise OR (|... |
729099b198e045ce3cfe0904f325b62ce3e3dc5e | karagdon/pypy | /diveintopython/707.py | 579 | 4.28125 | 4 | ### Regex Summary
# ^ matches
# $ matches the end of a string
# \b matches a word boundary
# \d matches any numeric digit
# \D matches any non-numeric character
# x? matches an optional x character (in other words, it matches an x zero or one times)
# x* matches x zero or more times
# x+ matches x one or more ti... |
25aec7ea0f73f0bf5fee4c5d8905f7d0561bb043 | karagdon/pypy | /learnpythonthw/34.py | 491 | 3.921875 | 4 | animals = ['bear', 'tiger', 'penguin', 'zebra','cat','dog']
bear = animals[0]
print animals
print "............"
print "The animal at 1 is %s" % animals[1]
print "The third (3rd) animal. is %s" % animals[2]
print "The first (1st) animal. is %s" % animals[0]
print "The animal at 3. is %s" % animals[3]
print "The fifth (... |
d865c2adf4c6c528500b3faa8a879c9fbf501303 | mfarukoz/HackerRank | /starcase-.py | 400 | 4.03125 | 4 | def staircase():
n = int(input())
# n icin veri girisi
if 0 < n <= 100:
# n ,0 ile 100 arasında ise
for i in range(1, n):
# 1 den n'e kadar dongu
print(('#' * i).rjust(n))
# n uzunlugunda satıra saga hizalı yıldız yazdırma
print(('#' * n).rjust(n), end='')
# alt satıra gecisi... |
a8e3061f27de656ee077ebb6f3c43a86ef16dde2 | TIEmerald/UNDaniel_Python_Library | /csv_reader/read_value_from_csv.py | 1,738 | 3.609375 | 4 | # -*- coding:utf-8 -*-
import csv
import os
import sys
import inspect
import getopt
def read_key_value_pair_from_csv(file, key, value):
values = None
if value is not None:
values = [value]
results = []
with open(file, mode='r') as csv_file:
csv_reader = csv.DictReader(csv_file)
... |
ba16b62a2d46ec2373bc85d8d1e33852ed2861ca | davsvijayakumar/python-programming | /player/first game creation.py | 521 | 3.984375 | 4 | while (1):
import random
arr=['p','s','sc']
c=random.choice(arr)
v=str(input("enter the your choice form -- s, sc, p:"))
b=str(v)
n=str(c)
print(b)
print(n)
if(c==v):
print("match draw")
elif(b=="s" and n=="sc"):
print("vijay is win")
elif(b=="s" and n=="p"):
print("computer is win")
elif(b=="p" a... |
963d100dfd5d65c50a092b0d6a6784402f760515 | reggieag/Spotify-Puzzles | /reversedbinary/reversedbinary.py | 121 | 3.6875 | 4 | def reverseBinary(x):
x = bin(x)
return int(x[:2]+x[2:][::-1], 2)
a = raw_input()
a = int(a)
print reverseBinary(a)
|
bd00c3566cf764ca82bba1a4af1090581a84d50f | f1uk3r/Daily-Programmer | /Problem-3/dp3-caeser-cipher.py | 715 | 4.1875 | 4 | def translateMessage(do, message, key):
if do == "d":
key = -key
transMessage = ""
for symbol in message:
if symbol.isalpha():
num = ord(symbol)
num += key
if symbol.isupper():
if num > ord("Z"):
num -= 26
elif num < ord("A"):
num += 26
if symbol.islower():
if num > ord("z"):
... |
e2b0a7d7bc76ef3739eace98f62081e78df24b67 | f1uk3r/Daily-Programmer | /Problem-11/Easy/tell-day-from-date.py | 540 | 4.5 | 4 | # python 3
# tell-day-from-date.py #give arguments for date returns day of week
# The program should take three arguments. The first will be a day,
# the second will be month, and the third will be year. Then,
# your program should compute the day of the week that date will fall on.
import datetime
import calendar... |
e849ae5643cfd27401834592cb4e5e2db8dd0339 | aryanxxvii/myAssistant | /my_calendar.py | 3,047 | 3.6875 | 4 | import reminder
import user_notes
import calendar
import datetime
import os
Help = """
Make your planning more efficient with the use of calendar.
You won't miss your favourite events like watching movies,
plan tours, mark birthdays, manage datewise to-do lists and
other benefits by using it in the best poss... |
c6cfa2227a88fc9e9a721ccfffac4b816bbb0039 | Atharva321/Python_GUI-tkinter- | /Submit3.py | 946 | 3.5625 | 4 | from tkinter import *from tkinter import messagebox
root = Tk()
def hl():
messagebox.showinfo("Do you want to conttinue","SUCCESS")
print("Name : ", text_var.get())
print("Branch : ", branch_var.get())
print("College : ", college_var.get())
root.title("Window")
root.geometry("350x250")
mylabel=Label... |
25b11fa2a4a8d5b01b6c20a5edf8c506fc869f0d | kakalinath/Hackfest | /11th.py | 550 | 4 | 4 | #Fibo Simple
Limit = input("Enter Limits >> ")
try:
Limit = int(Limit)
n1,n2 = 0,1
count = 0
if Limit < 0 :
print("Fibonacci Series is 0 !")
elif Limit==1:
print("Fibonacci Series is :", n2)
else:
print("Fibonacci Series >> ")
... |
b9bd13976ab7971faac6cee441b57255d928d7d9 | namho102/ml-recipes | /regr.py | 758 | 3.59375 | 4 |
import matplotlib.pyplot as plt
import numpy as np
from sklearn import datasets, linear_model
N = 50
X = [[2], [3], [4], [7]]
y = [2, 4, 3, 10]
X_test = [[1], [10]]
X_test2 = [[5], [9]]
# y_test = [[6]]
# Create linear regression object
regr = linear_model.LinearRegression()
# Train the model using the training set... |
f7b95be5656ba3ef2d1eadd1169c919d4ad90676 | SeanHildreth/CodingDojo | /python_stack/python_fundamentals/for_loop_basic1.py | 561 | 3.546875 | 4 | for basic in range(151):
print("Number is ", basic)
fives = 5
for count in range(1000001):
print('Number is ', fives)
count += 5
for dojo in range(1,101):
... if dojo % 5 == 0 and dojo % 10 == 0:
... print('Coding Dojo')
... elif dojo % 5 == 0:
... print('Coding')
... e... |
aa9169094c6b112f71a47c1487d80bb762c593d6 | SeanHildreth/CodingDojo | /python_stack/python_OOP/assignments/product.py | 1,366 | 3.640625 | 4 | class Product:
def __init__(self, price, name, weight, brand):
self.price = price
self.name = name
self.weight = weight
self.brand = brand
self.status = 'For Sale'
def sell(self):
self.status = 'Sold'
return self
def add_tax(self, tax):
total =... |
3668ddc967fedbc8d02c0ff1dcdabc98d8393488 | PitiasFessahaie/GAMER | /Banking.py | 1,429 | 3.953125 | 4 |
class Banking():
def __init__(self, balance=100):
self.balance = balance
print("\nWelcome to the ATM Deopsit and Withdrawal Machine!")
def machine(self):
data=self.usage()
if data == True:
self.deposit()
self.display()
else:
self.withd... |
7ced3f8d1bd43326c0828d20a300a4cc3e58a11e | lanhaixuan/Data-Structure | /剑指offer/15.合并两个排序的链表.py | 1,253 | 3.859375 | 4 | # -*- coding: utf-8 -*-
# @Time : 2018/12/6 10:18
# @Author : lanhaixuan
# @Email : jpf199727@gmail.com
# @File : 15 合并两个排序的链表.py
# @Software: PyCharm
'''
输入两个单调递增的链表,输出两个链表合成后的链表,当然我们需要合成后的链表满足单调不减规则。
'''
'''
要注意特殊输入,如果输入是空链表,不能崩溃。
'''
class ListNode:
def __init__(self, x):
self.val = x
... |
edbc74972bc4193c0bdf0196182c5863ab168d44 | lanhaixuan/Data-Structure | /剑指offer/5.用两个栈实现队列.py | 1,109 | 3.890625 | 4 | # -*- coding: utf-8 -*-
# @Time : 2018/12/2 8:53
# @Author : lanhaixuan
# @Email : jpf199727@gmail.com
# @File : 5 用两个栈实现队列.py
# @Software: PyCharm
'''
用两个栈来实现一个队列,完成队列的Push和Pop操作。 队列中的元素为int类型。
'''
'''
需要两个栈Stack1和Stack2,push的时候直接push进Stack1。
pop需要判断Stack1和Stack2中元素的情况,Stack1空的话,直接从Stack2 pop,Stack1不空的话,把St... |
e944a493701484b85f0930ed5c5c716253ed6a9b | NosevichOleksandr/firstrepository | /srezy.py | 205 | 3.75 | 4 | print('hello world')
a = input('write your ... something: ')
if len(a) % 2 == 0:
b = a[:len(a)//2]
c = a[len(a)//2:][::-1]
print(b + c)
else:
print('ты неправильно ввел')
|
763884703173c3ed766a39097bb0fe42ab72ae19 | NosevichOleksandr/firstrepository | /18_10__20_11_20.py | 178 | 3.71875 | 4 | data = [1, 2, 3, [2, 3, '12'], [123], 22, [1, 2]]
answer = []
for i in data:
if isinstance(i,list):
answer.extend(i)
else:
answer.append(i)
print(answer)
|
2c7f663cce98480b163dbea34a34f09c4027dc21 | NosevichOleksandr/firstrepository | /hus;o.f.py | 536 | 3.78125 | 4 | def countpolindroms(a):
a += ' '
word_or_number = ''
answ = ''
for i in a:
if i != ' ':
word_or_number += i
elif i == ' ':
if word_or_number == word_or_number[::-1] and len(word_or_number) > 1:
answ += word_or_number + ' '
word_or_n... |
46890d2654f4c0dcc68273311338af570ec4b7f5 | NiramBtw/leetcode_python_solutions | /26. Remove Duplicates from Sorted Array.py | 732 | 3.53125 | 4 | class Solution(object):
def removeDuplicates(self, nums):
"""
nums= [1,1,2,2,3,4]
create and index of all unique chars in the list
then remove all the rest
return the new index list we make
+ the len of them
"""
# first cond
if len... |
c33e56b18a347e0055347e36894261e1f0bb7c38 | NiramBtw/leetcode_python_solutions | /1. Two Sum.py | 1,135 | 3.640625 | 4 | class Solution:
def twoSum(self,nums,target):
# by try give 1 num vs the target we can cheack if the num(we look)
# + the num we hold = traget
# nums = [2,7,11,15], target = 9
# try use a dict()
comp_map = dict()
for i in range(len(nums)):
... |
646b8ee4ffb125dfa1971e004ebb645a5a9447eb | siumingdev/course-exercises | /Data Structures and Algorithms, UCSD/1. Algorithmic Toolbox/week3_greedy_algorithms/2_maximum_value_of_the_loot/fractional_knapsack.py | 860 | 3.75 | 4 | # Uses python3
import sys
def get_optimal_value(capacity, weights, values):
value = 0.
# write your code here
# build a tuple which is [(v, w, v/w), ...]
vw_tuple = [(values[i], weights[i], 1. * values[i] / weights[i]) for i in range(len(values))]
# print(vw_tuple)
vw_tuple.sort(key=lambda x: x... |
1c427e738788145d19708d54f62415beb637a771 | siumingdev/course-exercises | /Data Structures and Algorithms, UCSD/3. Algorithms on Graphs/week2_decomposition2/3_strongly_connected/strongly_connected.py | 1,608 | 3.59375 | 4 | #Uses python3
import sys
sys.setrecursionlimit(200000)
def toposort(adj):
# print(adj)
visited = [False] * len(adj)
post_order = []
def explore(_x):
visited[_x] = True
for _neighbor_of_x in adj[_x]:
if not visited[_neighbor_of_x]:
explore(_neighbor_of_x)
... |
817446639494fd93cf885e9a527fd040c0cdeee0 | siumingdev/course-exercises | /Data Structures and Algorithms, UCSD/1. Algorithmic Toolbox/week2_algorithmic_warmup/8_last_digit_of_the_sum_of_squares_of_fibonacci_numbers/fibonacci_sum_squares.py | 1,034 | 3.703125 | 4 | # Uses python3
from sys import stdin
def fibonacci_sum_squares_naive(n):
if n <= 1:
return n
previous = 0
current = 1
sum = 1
for _ in range(n - 1):
previous, current = current, previous + current
sum += current * current
return sum % 10
def get_fibonacci_hug... |
9c77351cf0ddb6158bb91a0e73914797c9d770b0 | Oleh6195/BattleShip | /field.py | 6,944 | 3.578125 | 4 | from funcs import has_ship, ship_size, field_to_str, is_valid
from ship import Ship
import random
class Field:
"""
This class representts field
"""
def __init__(self):
self.empty_field = dict()
self.score = 0
letters = "ABCDEFGHIJ"
for let in letters:
self.e... |
cd2653796bca22901b7f979ed126040fdebeeac8 | dev-tanvir/automate_boring | /while_adder.py | 147 | 3.734375 | 4 | #adding from 1 to 100 using while loop
i = 0
total = 0
while True:
total = total + i
if i == 100:
break
i = i + 1
print(total)
|
4db7eb9ce2a95a1a46229b08ab0da06b0f7dd1be | PritishMukherjee123/c-136 | /c-131.py | 8,421 | 3.59375 | 4 | import csv
rows=[]
with open("planetdata.csv","r") as f:
csvreader=csv.reader(f)
for row in csvreader:
rows.append(row)
headers=rows[0]
Planet_data_row=rows[1:]
print(headers)
print(Planet_data_row[0])
headers[0]="row_num"
Solar_System_Planet_Count={}
for Planet_data in Planet_data_row... |
697cac8a717c9c03fac83a47e080f5112f6a4ec2 | 99003766/python_practice | /tryingnew.py | 903 | 3.53125 | 4 | import pandas as pd
from openpyxl import load_workbook
# empty data frame is created
df_total = pd.DataFrame()
res=[]
# all sheets are taken as a list
sheets = ['Sheet1', 'Sheet2', 'Sheet3', 'Sheet4']
# from user email address is taken
yin = input("Enter Official Email Address")
# for loop for reading all the data in d... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.