blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
115fe2f5a85c782bb31ec3d0977aa43374270025 | sushilpoddar/coursera-A_Consice_Introduction_To_Python_Programming | /problem1_3.py | 116 | 3.578125 | 4 | # %%
def problem1_3(n):
my_sum = 0
for i in range(0,n+1):
my_sum += i
print(my_sum)
# %% |
00f155a7b308726f421e4158ce1296ab69b68dc9 | dxxjing/python-test | /base_program/list.py | 814 | 4.125 | 4 | #!/usr/bin/python3
# list 列表 一个列表可以包含任意类型
# 索引值以 0 为开始值,-1 为从末尾的开始位置。
list1 = [1, 'test', 1.2, True]
tinyList = [4, 'tiny']
print(list1) # [1, 'test', 1.2, True]
# 截取
print(list1[0])
print(list1[:])
print(list1[0:])
print(list1[0:2])
print(list1 + tinyList) # 拼接
print(tinyList * 2) # 连续输出
print(list1[0:-1... |
369775e647b4e3d1f368547043d20c5a76a0480d | mrtonks/PythonCourses | /Python Course/IfChallenge/ifchallenge.py | 547 | 4.25 | 4 | # Write down a small program to ask for a name and an age.
# When both values have been entered, check if the person
# is the right age to go on an 18-30 holiday (the must be
# over 18 and under 31).
# If they are, welcome them to the holiday, otherwise print
# a (polite) message refusing them entry.
name = input("What... |
2cf14af9ab27c76111c9a68b9e25132663795875 | choicoding1026/data | /numpy/02_numpy05_색인2_2차원3_boolean색인.py | 729 | 4.03125 | 4 | '''
* numpy 색인
1) python의 기본색인 및 인덱싱 사용
2) fancy 색인 ( 정수형 색인 )
==> 리스트를 활용한 인덱싱
3) boolean 색인
==> 벡터 연산 활용한 논리값으로 색인
'''
import numpy as np
arr1 = np.array([[1,2,3],[10,20,30],[100,200,300]])
print("1. 원본 데이터:\n", arr1)
print("2. 벡터 연산: \n", arr1%2==0)
# [[False True False]
# [True T... |
7604f8499a7805ca09ee77da9eb6a36583e213f7 | tatianadev/python | /hw3/hw3_task4_game/krestiki_noliki.py | 1,959 | 3.703125 | 4 | from game_krestiki_noliki import game_functions, file_functions
import sys
field = [
[' ', ' ', ' '],
[' ', ' ', ' '],
[' ', ' ', ' ']
]
players = [["Player 1", "X"], ["Player 2", "0"]]
print("Welcome to game krestiki-noliki!")
# load saved data from file
saved_data = file_functions.load_from_file()
if ... |
d428ca71ae3c947229432bf5ea32796b6d411d31 | lllirunze/practice | /小乌龟.py | 285 | 3.546875 | 4 | class Turtle:
color='green'
weight=10
legs=4
shell=True
mouth='big mouth'
def climb(self):
print('I am cilmbing...')
def run(self):
print('I am running fast.')
def sleep(self):
print('I wanna go to sleep.')
|
ac441fde7d0d24a17656283e3a455315915e7a93 | samoluoch/Password-Locker | /credential_data.py | 1,366 | 3.765625 | 4 | class Credential:
'''
This is a class that generates instances of usernames, passwords, and the websites
'''
credential_list = []
def __init__ (self, username, password, website):
'''
__init__ method helps in defining credential properties
Args:
username: New credenti... |
ee5a822c2bb1c8035d697ad1fc1e66f2665d32d5 | mariush2/tdt4110 | /øving10/rekursjon.py | 1,055 | 3.953125 | 4 | from math import *
def recursive_sum(n):
if(n == 1):
return 1
else:
return n + recursive_sum(n-1)
def find_smallest_element(numbers, current_min = None):
if(not numbers):
return current_min
#Removes and selects the last item in the list
candid = numbers.pop()
if(curren... |
d176503459ec31c491da537c138f51d66b25bd62 | LittlePetunia/410p3 | /pyminic/minic/mutils.py | 404 | 3.671875 | 4 | import os
import re
# Because Python3 returns a map for map, and python2.7 a list.
def lmap(f, l):
if l is not None:
return [f(x) for x in l]
else:
return None
def locate(pattern = r'\d+[_]', root=os.curdir):
for path, dirs, files in os.walk(os.path.abspath(root)):
for filename in ... |
0be6d4abca1255f0d3ea4c50956ca727b5dc541f | Saumitra8/Login-Registration-System | /Login-Registration System/Clock File/CLOCK-PROJECT-SOURCE-CODE.py | 2,904 | 3.5625 | 4 | from tkinter import*
from PIL import Image,ImageTk,ImageDraw
from datetime import*
import time
from math import *
class Clock:
def __init__(self,root): # This Constructor is used for working on our window
self.root=root
self.root.title("GUI Analog Clock") #---------Set the Title of Windo... |
621a2421b18dad2c135788e201de171493a79fe0 | Typical-dev/C-97-Python-project | /NumberGuessingGame.py | 986 | 4.03125 | 4 | Python 3.9.2 (tags/v3.9.2:1a79785, Feb 19 2021, 13:44:55) [MSC v.1928 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license()" for more information.
>>>
============================================================================================================== RESTART: Shell ==================... |
d5abf20a9517c2c4850313257253a03ebe78aae4 | Navaneet-Butani/python_concept | /OOP_encapsulation.py | 496 | 4.09375 | 4 | class Product():
def __init__(self):
self.__max_price = 1000
def print_price(self):
print("The maximum price of the computer is :{}".format(self.__max_price))
def set_max_price(self, price):
self.__max_price = price
computer = Product()
computer.print_price()
# Change the priva... |
8969e2215d909fd202480fe7102b8d6f1b950db7 | indexcardpills/python-labs | /03_more_datatypes/3_tuples/03_12_list_to_tuple.py | 133 | 3.90625 | 4 | '''
Write a script that takes a list and turns it into a tuple.
'''
list=[5, 6, 7, 8]
list_to_tuple=tuple(list)
print(list_to_tuple) |
c773b9eba6699041f524fbfc43375f5ef600b398 | yh97yhyh/webFullstack | /pythondjango/011.py | 517 | 3.890625 | 4 | # 함수
# def plus(x, y):
# z = x + y
# return z
# print(plus(3, 7))
# def printNum():
# print('one')
# print('two')
# print('three')
# printNum()
# def empty():
# pass
# empty()
# def f(n):
# if n > 1:
# return n * f(n-1)
# else:
# return 1
# print(f(5))
# 함수의 클로저
# de... |
f9a1a53240db6a436e173bba7d9941e025d9cd50 | giant-xf/python | /untitled/1.01-小白成长记/1.01.6-类的继承和重写再调用.py | 770 | 3.71875 | 4 | class Animal(object) :
def eat(self):
print('-----吃-----')
def drink(self):
print('-----喝-----')
def sleep(self):
print('-----睡觉-----')
def run(self):
print('-----跑-----')
def bark(self):
print('----鬼叫-----')
class Dog(Animal) :
def bark(self... |
21c54a4100e8d8df7c97ac4a78e53585c49b2baa | jodigious/RPS | /main.py | 1,960 | 4.40625 | 4 | # This is just me messing around late at night.
import random
print("\nWelcome to Rock, Paper, Scissors!\n")
print("(Best 2 out of 3)\n")
gameover = False
your_score = 0
computer_score = 0
while not gameover:
guess = input("Pick rock, paper, or scissors: ")
if guess.upper() != "ROCK" and guess.upper() != "... |
bf1d894b2cf5021df9ee6177402115c78d16a40c | RamiJaloudi/Python-Scripts | /Good_Examples/bs4_examples_4.py | 1,754 | 3.5 | 4 | from bs4 import BeautifulSoup
import sys
import os
import requests
from ast import literal_eval
def get_links(url):
r = requests.get(url)
contents = r.content
soup = BeautifulSoup(contents)
links = set()
with open("links_methods.txt", "a") as file:
for link in soup.findAll('a'):
... |
adec779ac2a650f283ccfd79a745f3bf206dce77 | lschanne/DailyCodingProblems | /year_2019/month_03/2019_03_04__house_colors.py | 3,678 | 3.921875 | 4 | '''
March 4, 2019
A builder is looking to build a row of N houses that can be of K different
colors. He has a goal of minimizing cost while ensuring that no two neighboring
houses are of the same color.
Given an N by K matrix where the nth row and kth column represents the cost to
build the nth house with kth color, ... |
962bf3dd2b05bb90ba8aa50437e088d5a5d0f9d1 | hudefeng719/uband-python-s1 | /homeworks/A10397/week1/Day06/day06-homework 1-1.py | 624 | 3.84375 | 4 | #!/usr/bin/python
# -*- coding: utf-8 -*-
# @author: Tangxiaocu
# 1. 老妈来到了菜市场,从下标 0 开始买菜,遇到偶数的下标就买
# 遇到奇数的下标就不买,买的数量为下标 + 1 斤
def main():
lst = ['大白菜', '萝卜', '西红柿', '甲鱼', '龙虾', '生姜', '白芍', '西柚', '牛肉', '水饺']
print '老妈来到菜市场 '
for index,lst_item in enumerate(lst):
if index% 2 == 0:
print '看到了 %s,买了 %d 斤' %... |
6164073af571a45db1a8edc21834eb6cf932a117 | amogchandrashekar/Data-Structures-and-Algorithms-Specialization | /Algorithmic Toolbox/week3_greedy_algorithms/fractional_knapsack.py | 2,043 | 3.75 | 4 | """
Problem Description
Task. The goal of this code problem is to implement an algorithm for the fractional knapsack problem.
Input Format. The first line of the input contains the number n of items and the capacity W of a knapsack.
The next n lines define the values and weights of the items. The i-th line contains i... |
33566f7cd7c849d77cfc98abde5169527e26ad03 | Napitok1987/AH_homework | /main.py | 365 | 3.515625 | 4 | import csv
name = input('Enter your name: ')
email = input('Enter your email: ')
phone = input('Enter your phone number: ')
Git_profile = input('Enter link to your Git profile: ')
save = input('Save to CSV? ')
if save == 'yes' or "y":
file = open('results.csv', 'a')
csv_writer = csv.writer(file)
csv_writer... |
b35f18cfcd202aee26f9b7e5543fcf6a561fad1a | AlexValor/ejercicio_json | /Ejer4.py | 438 | 3.96875 | 4 | #Buscar información relacionada.
#4.Pide por teclado el nombre de un campeón y te mostrará su título y su descripción.
import json
from pprint import pprint
with open('campeoneslol.json') as data_file:
data= json.load(data_file)
campeon=input("Dime el nombre de un campeón: ")
for nombre in data:
if nombre["name"... |
a6a6db88fb5ac247b5e6f69f34cee817aaf90e1c | ferpar/nnfs | /src/dotp.py | 265 | 3.53125 | 4 | a = [1, 2, 3]
b = [2, 3, 4]
def calc_dotp(a,b):
if (len(a) == len(b)):
dotp=0
for x,y in zip(a,b):
dotp+=x*y
return dotp
else:
return "vectors must have same dimension for the dot product"
print(calc_dotp(a,b))
|
9eb19711764289712d520801aec3f2c7ed40f5fa | cecilyp/Python-Problem-Set | /problem3_crpage.py | 2,350 | 3.84375 | 4 | # STAT/CS 287
# HW 01
#
# Name: Cecily Page
# Date: September 11 2018
import urllib.request
from os import path
from string import punctuation
import collections
import operator
def words_of_book():
"""Download `A tale of two cities` from Project Gutenberg. Return a list of
words. Punctuation has been remove... |
b7048f0e3cc01387471ba62d0b8f15fa60e56588 | homePattarapong/BasicPython | /whileloop.py | 417 | 3.65625 | 4 | # i = 1
# while i <= 10:
# if i == 10:
# print(i)
# else:
# print(i, end=',')
# i = i+1
# a = 1
# while a < 100:
# print(a)
# a = a+1
b = 1
while True:
print(b, end=' ')
if(b % 10 == 0):
print(end='\n')
b = b+1
if(b == 101):
break
print()
i = 1
whil... |
2cd7939692a2f4874615fed31d16c690635a1675 | charlesezra/analyze-insta-followers | /analyze.py | 1,236 | 3.65625 | 4 | # Compare the following and follower lists
from collections import Counter
def get_data(filename):
data = []
with open(filename) as file:
for line in file:
data.append(line.rstrip("\n"))
return data
def pretty_output(data_list):
count = 0
for data in data_list:
if count... |
ca8ea836f6c46345eacecda8bbd9db840b905c45 | jim-thompson/google-code-challenge | /3.3-string-cleaning/rejects2/solution.py | 1,719 | 3.890625 | 4 | candidate = "";
def answer(chunk, word):
global candidate
candidate = chunk
recurse(chunk, word)
return candidate
def recurse(chunk, word):
global candidate
thiscount = 0
chunk_len = len(chunk)
word_len = len(word)
subchunks = list()
# Simple recursion takes too long, so a... |
2e8de541991d77438e2b5198346f53b6387716e7 | vanu98/Generators | /generators/otp.py | 157 | 3.625 | 4 | import string
from random import *
length = input('otp length?')
ot = string.digits
otp = "".join(choice(ot) for i in range(int(length)))
print(otp) |
7008a8cd6495e11712fb3a6e9f3c8cffa8705f86 | shiran-valansi/problemSolving | /findDictionaryWords.py | 1,846 | 4.15625 | 4 | # Given a class such as:
# And an input text file contains a list of words. The list contains all the words in the English language dictionary (approximately 600,000+ words). Example:
# ==================
# apple
# cat
# table
# dog
# from
# fish
# select
# selected
# ...
# ==================
# Implement the metho... |
e79e50522688442b097c26c54ce6e4638fb990e5 | rangarajacet/phythonprogramming | /player/holiday.py | 192 | 4.1875 | 4 |
print("DAYS:sunday,monday,tuesday,wednesday,thursday,friday,saturday,")
day = input("enter the day:")
if day in ('sunday'):
print("is a holiday")
else:
print("is a not holiday")
|
8ac67817fde031beb2976491d47e0b05811f06f3 | SP2224/My-python-programs | /HOW TO PRINT MULTIPLE SENTENCES OR WORDS IN A SINGLE LINE IN PY3.X.py | 110 | 3.5625 | 4 | print("satya", end=" ")
print("satya prakash")
a = [1, 2, 3, 4]
for i in range(4):
print(a[i], end=" ") |
7acd5dd626bb85ff7c46c3f7cd1d6208223a1960 | nciefeiniu/python-test | /suanfa/arrlist.py | 348 | 3.703125 | 4 | class Solution:
def removeDuplicates(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
for num in nums:
if num not in nums:
self.new_nums.append(num)
return len(self.new_nums),self.new_nums
s = Solution()
nums = s.removeDuplicates([1... |
319fb7d86c630b2664228ad1e72aa8374fbe24dd | sienatime/misc | /causes.py | 2,184 | 3.546875 | 4 | from math import sqrt
def reverselist(l):
tokens = l.split()
for i in range(1, len(tokens)+1):
print tokens[-i],
def count_words(l):
d = {}
for word in l:
val = d.get(word, 0)
d[word] = val + 1
final_list = []
for key,value in d.iteritems():
final_list.append([k... |
994e37d6b64d87f2c83ede628ee5ab30924bc096 | dperry49/pdsnd_github | /bikeshare.py | 7,807 | 4.5 | 4 | import time
import pandas as pd
import numpy as np
CITY_DATA = { 'chicago': 'chicago.csv',
'new york city': 'new_york_city.csv',
'washington': 'washington.csv' }
def get_filters():
"""
Asks user to specify a city, month, and day to analyze.
Returns:
(str) city - name o... |
40cf9e44803ab49a5b51f2534a6676c41f52a907 | sandeepwalia/Algorithms | /Fibonnaci Series Recursive_n.py | 215 | 3.6875 | 4 | #Fibonnaci Series Recursive Solution
#Date Created:01-Aug-2016
#Sandeep Walia
def FibbonaciRecurive(n):
if n==0:
return 0
elif n==1:
return 1
else:
return FibbonaciRecurive(n-1)+FibbonaciRecurive(n-2)
|
b37c45347876c479a73ab87c469dea9f6dcbcd54 | Marceggl/exerciciosPythonBrasil | /2_EstruturaDeDecisao/26.py | 1,210 | 3.890625 | 4 | '''
26. Um posto está vendendo combustíveis com a seguinte tabela de descontos:
a. Álcool:
b. até 20 litros, desconto de 3% por litro
c. acima de 20 litros, desconto de 5% por litro
d. Gasolina:
e. até 20 litros, desconto de 4% por litro
f. acima de 20 litros, desconto de 6% por litro
Escreva um algoritmo que leia o nú... |
75b9a50d5957b9bf76f1c8295378dbc75f434e11 | JokerTongTong/Numpy_learn | /3.6寻找最大值和最小值以及计算数组的取之范围.py | 490 | 4.1875 | 4 | # 3.6寻找最大值和最小值以及计算数组的取之范围
import numpy as np
'''
寻找最大值和最小值以及计算数组的取之范围
max(a)
返回数组a中的最大值
min(a)
返回数组a中的最小值
ptp(a)
返回数组a的范围 等同于 max(a)-min(a)
'''
h,l = np.loadtxt("a.txt",delimiter=",",usecols=(4,5),unpack=True)
max_num = np.max(h)
min_num = np.min(l)
fanwei = np.ptp(h)
print(max_num)
print(min_num)
print("数组... |
a3ecdc050430ced203f8535f1f9e22e804396ef5 | lcscim/python-demo | /project/Python/other/text game.py | 481 | 3.765625 | 4 | import random
secret = random.randint(0,10)
print('-------------------大家好我是老长-------------------')
temp = input("猜一个心里想一个数字:")
guess = int(temp)
i = 1
while guess != secret and i < 3:
i += 1
if guess > secret:
print("大了")
else:
print("小了")
temp = input("重新输入:")
guess = int(temp)
if g... |
819605b76ebfc89f2425d8411ea88b8d13926233 | TheDojoMX/BasicProgramming | /python/password_check.py | 449 | 3.65625 | 4 |
password = "hellodave"
# Condiciones
# if len(password) <= 10:
# print("Tu password no funciona")
# Mayusculas
tiene_mayusculas = False
for char in password:
if char.isupper():
tiene_mayusculas = True
special_chars = ['.', ',', ';', ':', '*', '@', '%', '/']
tiene_car_esp = False
for c in password:... |
10590bfc699fe8c818c8abab00ced8001c8b761f | avetisovalex/geek-python | /homework02/example03.py | 730 | 4.0625 | 4 | monthNumber = int(input("input number of month >>>"))
listWinter = [1, 2, 12]
listSpring = [3, 4, 5]
listSummer = [6, 7, 8]
listAutumn = [9, 10, 11]
if monthNumber in listWinter:
print("it's Winter")
elif monthNumber in listSpring:
print("it's Spring")
elif monthNumber in listSummer:
print("it's Summer")
... |
a5261b262e7040f530b34c47ba483ed50c5a3426 | amgxv/pytelbot | /pytel_bot/calculator.py | 1,840 | 4.03125 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# made with python 3
"""Abstract representation of the basic behaviour of a calculator."""
import logging
class Calculator():
"""Main behaviour"""
def __init__(self,input_str: str):
self.logging = logging.basicConfig(filename='caluclator.log', level=logging... |
289b8aa5ecbea05bcef5965bee0b24f626ddd263 | clodiap/PY4E | /09_exercice1.py | 588 | 3.984375 | 4 | # Exercise 1: [wordlist2]
# Write a program that reads the words in words.txt and stores them as keys in a dictionary. It doesn't matter what the values are. Then you can use the in operator as a fast way to check whether a string is in the dictionary.
filename = input("Enter a file: ")
if len(filename) < 1 : filenam... |
6ebd4fec14135b1c8242b7a0d3b8690a0f27d373 | statisticallyfit/Python | /pythonlanguagetutorials/PythonUNE/Lectures/Lecture7.1_GUI/spanning.py | 2,155 | 3.515625 | 4 | from tkinter import *
from tkinter import ttk
# Creating the widgets
root = Tk()
content = ttk.Frame(root, padding = (3, 3, 12, 12)) # note padding
# another frame in the above content frame
frame = Frame(content, borderwidth=5, relief="sunken", width=200, height=100)
def okClickShowName():
nameVar.set(name... |
3ec570755f651133174e23858bd48c04a2fbe576 | CarlosCBar/Tuples---Dictionaries---Sets | /Tuples - dictionaries - sets.py | 3,923 | 3.703125 | 4 | # TUPLES
ejemplo = ("Pastel",'Panqué',"Muffin")
# Siempre se usan comas, un tuple con solo 1 elemento debe llevar coma forzosamente
vertigo_data = ("Vertigo", 1958, "A. Hitchcock")
#SE PUEDEN GUARDAR TUPLES DENTRO DE LISTAS
scores = [("mia", 75), ("Lee", 90)] #Contiene dos elementos
print(scores[0]) #----... |
f2ca2f7370a552e8fac02790753f9cf77039abb5 | Latinobull/Human-Database | /objects.py | 3,830 | 4.09375 | 4 | from db import Database
from PyInquirer import prompt, Separator
# Human needs name, job, age, salary, bills
DB = Database()
class Bills:
@staticmethod
def Tax(salary):
tax = salary * 0.1175
salary = salary - tax
return salary
@staticmethod
def Groceries(salary):
sala... |
5a89eca02b9f8977a1e5e89d72a92a5e4f5a6e6c | bayardd/cs517_semester_project | /linearInterpolation.py | 1,946 | 3.921875 | 4 | """
Module containing the functions necessary to perform piece wise linear interpolation
"""
NEWLINE = '\n'
TAB = '\t'
def calculateSlope(y1,y2):
"""
Take 2 points y1 and y2 and calculate the slope between them
(Note that the 30 seconds is hardcoded because the distance between all x values is 30)
... |
c530e3eb8a852ac08694b51deee26aedaf114634 | minas528/a2sv | /Introdution to Competitive Programming/D25/SumOfNodesWithEvenValued.py | 1,088 | 3.75 | 4 | # Definition for a binary tree node.
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def sumEvenGrandparent(self, root):
Sum = [0]
def dfs(Node):
if Node is not None and Node.val % 2 ==0 :
... |
ed7f3dde08e0bd46d141486e9719bf05b631de06 | IsaacYouKorea/dovelet | /step1/three.py | 232 | 3.859375 | 4 | a = int(input())
b = int(input())
temp = b
first = temp % 10
temp = int(temp / 10)
second = temp % 10
temp = int(temp / 10)
third = temp % 10
temp = int(temp / 10)
print("%d\n%d\n%d\n%d" % (a * first, a * second, a * third, a * b)) |
f867bf7801fdcf986ee056f3503ef5f783c44ff5 | BobbaAsh/Python | /9 Dec./carnetadr.py | 1,714 | 3.578125 | 4 | """
Gestion de fiche de contact avec
prenom, nom, naissance, couriel
"""
import pickle
### Section class
class CarnetAdr(object):
""" Conteneur de fiches """
carnet_adresse = []
def __init__(self, prenom=None, nomfami=None,
datenaiss=None, courriel=None):
self.prenom ... |
7958405e485444a7e8b76f531d08a2bd34599ca7 | patrick0422/python2020 | /Chap01/ex05_변수.py | 889 | 3.546875 | 4 | # 변수가 저장한 메모리 주소값 확인하기
a = [1,2,3]
print(id(a))
#region 얕은복사 & 깊은복사
# 얕은 복사
b = a
print(id(b)) # 주소는 a와 같음
b.append(4) # a와 b가 가리키는 주소가 같음 a를 호출해도 b와 결과는 같다
print(a, b)
print(f'a is b : {a is b}') # True 리턴
# 깊은 복사
a = [1,2,3]
b = a[:] # a를 통채로 복사
print(a, b)
b[0] = 10
print(a, b) # a= [1,2,3] b= [10,2,3]
print(f... |
8bec276112f1317f576df2b914a832946306c81d | cihares/test | /demo.py | 573 | 3.859375 | 4 |
# # 猜猜猜!!
# import random
# i=0
# num = random.randint(0,9)
#
# while i <3:
# i+=1
# a = int(input("guess: "))
# if num == a:
# print("YOU WIN!!")
# print(num)
# break
# elif i == 3:
# print("YOU LOSE!")
# print(num)
# #字符转换
# num = {
# "1... |
133c3aba32eb77654f2bb09c7751fcb518b6fc13 | QuinneL/hack-the-journey | /user_input/get_user_input.py | 1,129 | 3.75 | 4 | import json
import os
import shutil
'''
prompts the user to answer profile questions
'''
def get_inputs():
name = input("Name:")
d = {}
d['age'] = input("input your age and age of the people that you're traveling with:")
d['date'] = input("Enter the range of date in YYYY-MM-DD, YYYY-MM-DD format:")
d['hobbi... |
faf6c747f532abef53e3e38b5cabac51af32b30f | fanzijian/leet-code-practice | /src/code/code_52.py | 460 | 3.578125 | 4 | #!/usr/bin/env python
#-*- coding: utf-8 -*-
class Solution(object):
def maxSubArray(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
n = len(nums)
cur_max = nums[0]
max_max = nums[0]
for i in xrange(1, n, 1):
cur_max = max(nums[i],... |
4809d5745e01aa8455a0b9d30aef13fc597f8dbb | mogottsch/vehicle-reposition-2 | /src/modules/helpers.py | 1,055 | 3.9375 | 4 | from math import sqrt, sin, cos, atan2, radians
def calc_distance_haversine(coord1, coord2):
"""Returns the distance between two given coordiantes in km.
Parameters
----------
coord1 : tuple, required
tuple containing the latitude and longitude of a coordinate.
coord2 : tuple, required
... |
497e6682128071450eaa4180fbbcd0e3c3633c29 | 34527/Selection | /Water State.py | 286 | 4.1875 | 4 | #Euan McElhoney
#30/09/2014
#Selection Exercises - Water state
state = int(input("Please enter the temperature of the water: "))
if state > 100:
print("The water has boiled")
elif state < 0:
print("The water has frozen")
else:
print("The water has remained a liquid")
|
ae8768794e5b33a3002b44d10dac5a185d4f02de | penny88111/Python- | /matplotlibexercise/matplotlib_15.py | 9,511 | 4 | 4 | # # 15.2 简单的折线图
# import matplotlib.pyplot as plt
# ## 导入pyplot命名为plt
#
# squares = [1, 4, 9, 16, 25]
# ## 建个列表储存平方数,纵坐标值
# plt.plot(squares)
# ## 传递给函数plot,横坐标默认 0,1,2,3,4
# plt.show()
# ## 将图像显示出来,查看器可以缩放,可以保存
# # 15.2.1 题目横纵坐标字体格式
# import matplotlib.pyplot as plt
# ## 导入pyplot命名为plt
#
# squares = [1... |
1da02181c7de871672ec58d0ca79e721a0232367 | kunalkishore/Reinforcement-Learning | /Dynamic Programing /grid_world.py | 2,506 | 3.640625 | 4 | import numpy as np
class Grid():
def __init__(self,height,width,state):
self.height=height
self.width = width
self.i = state[0]
self.j = state[1]
def set_actions_and_rewards(self,actions, rewards):
'''Assuming actions consists of states other than terminal states and w... |
10f63ae8ca8ca6f1a8c1c60b5df9ab57350f0c54 | tjrobinson/LeoPython | /canvas.py | 1,589 | 3.71875 | 4 | import tkinter
import random
print("To draw, hold down the le ft mouse button and move your mouse around.")
print("To change your brush colour, click on one of the squares.")
#colourchoice = input("Press enter here to make the colour random or type 'no' to carry on.")
#colours = {1:"yellow",2:"red",3:"blue"}
#if colour... |
9704f5aa058f9494924cb0b05f7dfbd12ee7719f | shankarkrishnamurthy/problem-solving | /sort-colors.py | 841 | 3.703125 | 4 | class Solution(object):
def sortColors(self, nums):
"""
:type nums: List[int]
:rtype: void Do not return anything, modify nums in-place instead.
"""
def swap(ll, a,b):
t = ll[a]
ll[a] = ll[b]
ll[b] = t
rl = wl = bl = 0
for ... |
336a177304958a55d52e64bc963ea9c049be0d00 | sriram0107/Leetcode-Solutions | /convert-bst-to-greater-tree/convert-bst-to-greater-tree.py | 747 | 3.78125 | 4 | # Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def convertBST(self, root: TreeNode) -> TreeNode:
self.convertTree(root, 0)
return root
... |
71c3647d3a0b33ecdd356df7454dfdbc7161d58e | kshashank03/exercism_python | /robot-name/robot_name.py | 312 | 3.5 | 4 | class Robot:
import random
def __init__(self):
pass
def name(self):
alphabet = [chr(x) for x in range(ord('A'), ord('Z') + 1)]
robo_name = random.choice(alphabet) + random.choice(alphabet) + str(random.choice(range(100,1000)))
print(robo_name)
return robo_name |
1fbb8d378ae98c12c9609e5c2ba9c0f00d276f46 | Shawndace/python9am | /exercise-function/data_rep.py | 276 | 3.734375 | 4 | def my_rep(data, times):
x = 0
while x <= times:
print(data)
x += 1
my_rep("Sandesh", 4)
#
# # ----------------------------------
# def my_reps(name, times):
# x = 1
# while x <= times:
# print(name)
# x += 1
#
# my_reps(1, 1)
|
e192107b1243434f41505f5bf49db231ca74a20b | rajathpatel23/ml_algo_numpy | /Decision_Tree/decision_tree_classifier_appointment_predictor.py | 4,309 | 3.5 | 4 | # CART algorithm Implementation
import pandas as pd
import numpy as np
training_data = pd.read_csv("Kaggle_appointment.csv")
print(training_data.head())
print(training_data.info())
#print(training_data.describe())
patient_id = training_data['PatientId']
appointment_ID = training_data['AppointmentID']
Sch... |
6c0fcf97e0aa94637e2582269a0984bb41003c52 | LeiZhang0724/leetcode_practice | /python/practice/easy/reverse_int.py | 2,743 | 4.15625 | 4 | # Given a signed 32-bit integer x, return x with its digits reversed. If reversing x causes the value to go outside
# the signed 32-bit integer range [-231, 231 - 1], then return 0.
# Assume the environment does not allow you to store 64-bit integers (signed or unsigned).
def reverse(x: int) -> int:
INT_MIN, INT_... |
0ccae0d7309184c6a3a5ff43a9652b0e03661be6 | lasagnadeliciosa/IST652_Scripting_for_Data_Analysis | /IST652 - Lab 3.py | 5,163 | 3.734375 | 4 | #!/usr/bin/env python
# coding: utf-8
# # IST 652 Lab #3
# ### Instructions
# - Complete all 5 questions in this assignment.
# - You may work with others, <b> but the work you submit must be your own </b>. You can differentiate your work by adding comments or changing the values you use to test your code. However, sub... |
e97693da8066f3a6e34251c622d8e8a7ffd5bba5 | damnnhen/Data-Processing | /Homework/Week_3/csvtoJSON.py | 2,767 | 3.6875 | 4 | #!/usr/bin/env
# Name: Daniel Hendriks
# Student number: 11419628
"""
This script converts a CSV file to a JSON file
The data will be used to show the trend of Dutch speed skating medals
"""
#import libraries
import pandas as pds
import csv
from contextlib import closing
from numpy import percentile
import matplotlib... |
c006f15861c1162883295efe72554e5b100b8cf6 | Vincent-48/vince-ke | /Sorted with Keys/Sorted with Keys.py | 214 | 3.765625 | 4 | lst1 = ["abc", "1334", "ca*!?"]
print(sorted(lst1))
# sort by length
print(sorted(lst1, key=len))
lst2 = [(1,3), (2,4), (3,0)]
print(sorted(lst2))
# sort by second element
print(sorted(lst2, key = lambda x: x[1])) |
f9209552635db1e44d0c8b237b95938f54420207 | uniqueyehu/snippet | /python/learnpy/class-2.py | 694 | 3.9375 | 4 | # 访问限制
class Student(object):
"""docstring for Studen"""
def __init__(self, name, score):
self.__name = name
self.__score = score
def print_score(self):
print('%s: %s' % (self.__name, self.__score))
def get_name(self):
return self.__name
def get_score(self):
return self.__score
def s... |
d68c20de0ab8220e1e8dcae142c4742fe085ac2a | npim/BlackJack | /Player.py | 842 | 3.640625 | 4 | class Player:
def __init__(self, name, hand, chips):
self.name = name
self.hand = hand
self.chips = chips
def get_cards(self):
return self.hand.cards
def take_bet(self):
while True:
try:
self.chips.bet = int(input('How many chips would ... |
8a66f66bca79d5779a4f1c1030076379e874c831 | binoytv9/problem-solving-with-algorithms-and-data-structures | /4th chapter/to_str.py | 225 | 3.59375 | 4 | def to_str(n,base):
convert_str = '0123456789ABCDEF'
if n < base:
return convert_str[n]
return to_str(n/base,base) + convert_str[n%base]
print to_str(123,10)
print to_str(123,16)
print to_str(123,8)
print to_str(123,2)
|
ce48f143a0109e3812bb958347debbb95f0fe502 | AI-Pree/puzzles | /backup.py | 2,782 | 3.734375 | 4 | import functools
clues = ( 3, 2, 2, 3, 2, 1,
1, 2, 3, 3, 2, 2,
5, 1, 2, 2, 4, 3,
3, 2, 1, 2, 2, 4)
N = len(clues)/4 #square always gonna have 4 sides
building = [1,2,3,4,5,6]
top = clues[:N]
left = clues[N:2*N]
bot = clues[N*3-1:N*2-1:-1]
right = clues[-1:N*3-1:-1]
grid = [["-" for i in ... |
180a3132732c1c9bd3060c262a608ce4112b5e59 | anupamvamsi/python | /practice/0013_scenario_3.py | 1,528 | 3.765625 | 4 | class Passenger():
def __init__(self, passengerName, passengerAge):
self.passengerName = passengerName
self.passengerAge = passengerAge
def passengers(self, age):
if age >= 60:
return "Senior citizen"
elif age in range(18, 60):
return "Normal"
els... |
0cd0f01a4914118b8bcdf1eb99ee9f078314fb2b | OpenSource-Programming/PythonTraining | /022021/Graeme/Eli/EliFajardo_py_3-3_scores.py | 495 | 4 | 4 | print ("::: EASY GRADES :::")
score = input ("Enter score: ")
try:
score = float(score)
except:
score = -1
print ("Try input numbers")
exit(score)
if 0 <= score <= 1:
if score >= 0.9:
print ("A")
elif score >= 0.8:
print ("B")
elif score >= 0.7:
... |
4b26dc1ef2697ef38b6a53c3d836646c6efffac6 | Praveenias/Project | /AU_Cgpa_Calci.py | 1,445 | 3.71875 | 4 | import pandas as pd
import matplotlib.pyplot as plt
print('******CGPA CALCULATOR*****')
a = input("Enter the department:")
def cgpa(c):
try:
l = []
k = 0
cr= 0
grade = {'o':10,'a+':9,'a':8,'b+':7,'b':6,'ra':0}
b = int(input("ENTER YOUR SEMESTER:"))
if b:
... |
d823b3f161a7868853588659c6018cb2b23534d0 | Strider-Alex/CMPT310-Artificial-Intelligence | /a4/a4.py | 6,708 | 3.515625 | 4 | import random
import math
import time
import copy
#####################################################
#####################################################
# Please enter the number of hours you spent on this
# assignment here
num_hours_i_spent_on_this_assignment = 0
#################################################... |
ab6614a1eb9151b064209a32f4c5bba8d89023f7 | YashAgrawal0/Deep-Learning | /Assignment4/Dummy_Test/main.py | 3,478 | 3.59375 | 4 | #!/usr/bin/env python
# coding: utf-8
# In[42]:
import pandas
import matplotlib.pyplot as plt
import numpy
import matplotlib.pyplot as plt
import pandas
import math
import numpy as np
from keras.models import Sequential
from keras.layers import Dense
from keras.layers import LSTM
from sklearn.preprocessing import Mi... |
fa5423ba6313b0edbfd0d49b07bf4aec9c7f754f | AsanalievBakyt/classwork | /sort_algorithm.py | 259 | 4.03125 | 4 |
def bubbleSort(data):
for i in range(len(data)- 1):
for j in range(len(data)- 1):
if data[j] > data[j +1]:
data[j],data[j + 1] = data[j+1], data[j]
j += 1
return data
print(bubbleSort([3,1,4,5,2]))
|
aa1439c77b0b05ece2b4fe4396ad6e27a062efab | boiidae/py4me | /finding_the_average_in_a_loop.py | 182 | 3.78125 | 4 | count=0
sum=0
print('Before', count, sum)
for value in [9, 41, 12, 3, 74, 15]:
count=count+1
sum=sum+value
print(count, sum, value)
print('After', count, sum, sum/count)
|
172328cf1b55d5800bca948d753a9dbd8c75d34b | SimranIITRpr/CSL622 | /Assignment_4_2015csb1067.py | 1,851 | 3.546875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sat Sep 8 16:11:11 2018
@author: nittin pc
"""
import networkx as nx
import matplotlib.pyplot as plt
import operator
# the get_edge_betweenness function calculates the edge betweenness from scratch the only inbuilt function being used is the
# function which returns a... |
963d44fbe706fbc772c1768631f764b689a7a411 | diegorp22/diegopereira_DCO2004 | /HD00-Pratica01.py | 538 | 3.90625 | 4 |
# coding: utf-8
# # Exercício da prática 1
# **O Processo de modulação explora os três parâmetros da senoide portadora:**
# _Amplitude, Frequência e Fase_
# [aqui](https://pt.wikipedia.org/wiki/Modula%C3%A7%C3%A3o_em_amplitude)
# 
count = 0
for x in line:
if x=='z':
count= count + 1
print (count) |
383d265f9856b4b90dcf357f0b74a1a8a6982a6a | mariobeaulieu/LunchChallenges | /palindrome/palindrome.py | 971 | 3.953125 | 4 | #!/usr/bin/python
import logging
logging.basicConfig(filename='palindrome.log',level=logging.DEBUG)
def palindromize(text,offset):
textLength=len(text)
logging.debug("Processing <%s>"%(text[offset:textLength-offset]))
if textLength == 2*offset:
return
subLength=0
for i in range(1,textLength/2-offset+1):
... |
6c98858f8ba1d2f7e9b37d2249c4b18a457955fd | LayaFlo/PythonProgramming | /PythonProgramming/4.1.While-structure.py | 112 | 3.859375 | 4 | currlap = 0
totallaps = 5
while currlap < totallaps:
print("This is lap ", currlap)
currlap += 1
|
b297efe5f73c1c9b7e5b428e2ca8059633579ae1 | naiyte/ProjectEuler | /1.py | 284 | 4.1875 | 4 | #If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6, 9. The sum of these multiples is 23.
#Find the sum of all the multiples of 3 or 5 below 1000
count = 0
for x in range(0, 1000):
if (x % 3 == 0 or x % 5 == 0):
count = count + x
print(count) |
ee7c4999e6a105dc75c33b1d35ecdf665171c11c | omoore18/cool | /Owen Moore _ Lists.py | 7,225 | 3.96875 | 4 | #Owen Moore
#March 28, 2017
#Unit 5 Lesson 1, Lists
#Intro
print("Oh no! \n",
"The fairy princess has lost her sacred muffin!",)
input()
print("The evil villian, Maltheus the Destroyer, is the one who has stolen her muffin. \n")
input()
print("The princess has now tasked you to retrieve her muffi... |
d8c6ab67a4009add2a8b4fc45aa9023cd270f463 | EricHuang950313/Python | /Folders/Little/Hangman.py | 2,175 | 3.71875 | 4 | man = [
'''
|-----|
|
|
|
|
|
|
_____ | _____
''',
'''
|-----|
O |
|
|
|
|
|
_____ | _____
''',
'''
|-----|
O |
l |
l |
|
|
|
_____ | _____
''',
'''
|--... |
41ce12e595a583cb11e5092bbb009c10c01df798 | cabbagehao/Bees | /SortAlgorithms/A-quick_sort2.py | 720 | 3.734375 | 4 | import random
def _patition(nums, i, j):
pivot = nums[i]
while i < j:
while nums[j] > pivot:
j -= 1
if i == j: break
else:
nums[i] = nums[j]
i += 1
if i == j: break
while nums[i] < pivot:
i += 1
if i == j:... |
42a9ccb83ab61b7c5a3d65d214136e6e6b629c42 | annasw/Project-Euler | /euler7.py | 439 | 3.828125 | 4 | # almost certain there's a cleaner math way to do this
# but it runs in a fraction of a second anyway
from math import sqrt, ceil
def isPrime(n):
if n<2: return False
if n==2 or n==3: return True
if n%2==0: return False
for f in range(3,ceil(sqrt(n))+1,2):
if n%f == 0: return False
return True
primeCount = 2 ... |
874be4609b33f92d028e0f8eb1dddb3e15d5d2fd | Justin-A/Algorithms | /12901.py | 310 | 3.625 | 4 | def solution(a, b):
day = ["FRI", "SAT", "SUN", "MON", "TUE", "WED", "THU"]
month = [31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
day_after = 0
for x in range(a - 1):
day_after += month[x]
day_after += b
answer = day[(day_after % 7) - 1]
return answer |
4d0ef78ed11e70a4d3498a7fd1e9894b5baf210d | Saxamos/Sandbox | /adventofcode/2021/2.py | 594 | 3.578125 | 4 | puzzle = open("2.txt").read().split("\n")
# 1
pos, depth = 0, 0
for line in puzzle:
key, value = line.split(" ")
if key == "forward":
pos += int(value)
elif key == "down":
depth += int(value)
else:
depth -= int(value)
print("solution 1 is:", pos * depth)
# 2
pos, depth, aim ... |
4e80194094f35dac7dfead858f5e50ac9a9e89aa | bjthorpe/Python-Multiprocessing-talk | /multicore_primes.py | 860 | 3.734375 | 4 | # WARNING this code is for demo purposes only and will take a long time to complete
def check_prime(num):
'''Crude Function to check if a number is prime or not'''
# check for factors
for i in range(2,num):
if (num % i) == 0:
print(num,"is not a prime number")
print(i,"... |
ac8897b44c0f210c612ed86b2f71338709824a28 | Davideczech/Python_learning | /divisors.py | 215 | 4 | 4 | number = int(input("Give me the number!"))
div_number = range(2,number+1)
list=[]
for number_div in div_number:
if number % number_div == 0:
list.append(number_div)
print("List of divisors is:",list)
|
93c9bc003ae66ca690bd73df04d78c9ab8c40be6 | JamesLaneProgramming/IrelandGunOwnershipVisualisation | /IrelandGunOwnershipStats.py | 3,952 | 3.5 | 4 | import numpy as np
import matplotlib.pyplot as plt
import csv
#59588 entries
'''The CSV file contains a location field.
This field is redacted for security.'''
ages = []
genders = []
numberOfGuns = []
types = []
def retrieveCSVData():
'''
Extracts data from a CSV file and
Raises
------
IOError:
... |
bd2d89127b8df9a2727d3f1412bcd5b1958ea933 | cooklee/obiektowka | /emp_slawek.py | 426 | 3.5625 | 4 | class Employee:
def __init__(self, id, first_name, last_name):
self.id = id
self.first_name =first_name
self.last_name = last_name
self._salary = None
self.__prawdziwe_imie = 'czesław'
def set_salary(self, amount):
if not (isinstance(amount, (int, float)) and am... |
d42f6e90b26b6ff28ff4552cb4e76fe03ba41a91 | dvphuonguyen/pythonCoBan | /BaiTapCoBan/tinh_tien_ngan_hang.py | 169 | 3.828125 | 4 | money = float(input("Nhap so tien ban dau cua mot nguoi:"))
for index in range(10):
money *= 1.03
print("Tong tien nguoi do nhan duoc sau 10 ki la:", money)
|
2a18f39d1acd676f91f0e2c13efa2a974817f3f9 | bstollnitz/grad-school-portfolio | /dieline-classifier/dieline_classifier/hyperparameters.py | 1,872 | 3.5625 | 4 | import itertools
import pprint
import random
from typing import List, Dict
class Hyperparameters:
def __init__(self, definitions: Dict) -> None:
self.definitions = definitions
self.combinations = Hyperparameters._generate_combinations(definitions)
def sample_combinations(self, co... |
45e91dfd0ca76030ea1228d86b66d1ee6eec4d6b | Ronphillips1133/Guessing-game | /work.py | 1,135 | 4.1875 | 4 | secert_word = ""
guess = ""
guess_count = 0
guess_limit = 3
guess_hint = 1
third_try = 2
guess_help = ''
second_guess = 1
numbers = [10, 9, 8, 7, 6, 5, 4, 3, 2, 1]
out_of_guesses = False
enter_secert = input('Enter Secert Word: ')
secert_word = enter_secert
sentence = "Get Ready To Start"
char_freq = {}
for char in s... |
37f270838752fc0cbdaaff30569cacdae8009c19 | JakobHavtorn/pytorch-utilities | /initialization.py | 1,816 | 3.65625 | 4 | from torch import nn
def calculate_xavier_gain(nonlinearity, param=None):
"""Return the recommended gain value for the given nonlinearity function. The values are as follows:
============ ==========================================
nonlinearity gain
============ ========================================... |
dacf7b25dd815ad77672f783210764f43c7cfded | eladshamailov/Codewars-solutions | /isograms.py | 437 | 4.125 | 4 | """
An isogram is a word that has no repeating letters, consecutive or non-consecutive.
Implement a function that determines whether a string that contains only letters
is an isogram. Assume the empty string is an isogram. Ignore letter case.
"""
def is_isogram(string):
letter_dict = {}
for c in string:
... |
f91fef9b2584df47c833545cfa3987b04960ffcf | andreyac/ProejtoLocadoraPython | /emprestimos.py | 7,246 | 3.640625 | 4 | import csv
import datetime #novo repositório de funções para trabalhar com datas dos emprestimos
arq_filmes = 'filmes.csv' #aqui são definidos os nomes dos arquivos
arq_clientes = 'clientes.csv'
arq_emprestimos = 'emprestimos.csv'
emprestimos = {} #um dicionário vazio para empréstimos
def ler_filmes(filenam... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.