blob_id stringlengths 40 40 | repo_name stringlengths 5 127 | path stringlengths 2 523 | length_bytes int64 22 545k | score float64 3.5 5.34 | int_score int64 4 5 | text stringlengths 22 545k |
|---|---|---|---|---|---|---|
26eb251ccbddb49204f79816fff50e57e445d15c | meera-ramesh19/sololearn-python | /findingingredientinmenu.py | 485 | 3.703125 | 4 | menu=[]
menu.append(["egg","spam","bacon"])
menu.append(["egg","sausage","bacon"])
menu.append(["egg","spam"])
menu.append(["egg","bacon","spam"])
menu.append(["egg","bacon","sausage","spam"])
menu.append(["spam","bacon","sausage","spam"])
menu.append(["spam","egg","spam","spam","bacon","spam"])
menu.append(["spam","eg... |
5274e58018055ab1ceb8ccc47d6e6d9e176402e2 | meera-ramesh19/sololearn-python | /boolean.py | 170 | 4.125 | 4 | x = True
y = False
z = False
if not x or y:
print("1")
elif not x or not y and z:
print("2")
elif not x or y or not y and x:
print("3")
else:
print("4")
|
1a58bb7bd93e28c9711e53b2df161c1e2505b571 | Garee/leetcode | /python/1_Two_Sum.py | 1,565 | 3.71875 | 4 | """
1. Two Sum (Easy)
Given an array of integers nums and an integer target, return indices of the
two numbers such that they add up to target.
You may assume that each input would have exactly one solution, and you may
not use the same element twice.
You can return the answer in any order.
Constraints:
2 <= num... |
7472e688872952a6c352d4c92884dcd64e20578f | CoetBoet68/turtleCrossingRoad | /car.py | 1,037 | 3.765625 | 4 | from turtle import Turtle
from random import randint
class Car(Turtle):
colours = ["green","yellow", "red", "blue", "violet", "magenta","orange", "cyan", "brown"]
xPos = 250
moveSize = 0
cDis = 20
def __init__(self, xDiff, posy, mSize):
super().__init__()
self.moveSize... |
0e0b5998ee54a2c25a2ae0042525714e4799f7b7 | Gioia31/compito1012 | /es2.py | 358 | 3.609375 | 4 | nparole = input("Scrivere una lista di parole separate da virgole (es. parola1, parola2,..).\n")
listap = nparole.split(", ") #ad ogni , e spazio divide la lista per poi contare le lettere di ogni singola parola
listalungp = []
for parola in listap:
lunp = len(parola)
listalungp.append(lunp)
print("La lunghe... |
081f9b5e3a1e9100941f45b4f9d19786d069ed69 | maniospas/pygrank | /pygrank/benchmarks/printers.py | 4,840 | 3.59375 | 4 | import io
import math
import sys
from typing import Optional
from scipy import stats
import numpy as np
def _fraction2str(num, decimals=2):
"""
Helper method to pretty print percentages.
Args:
num: A number in the range [0,1].
"""
if isinstance(num, str):
return num
if math.isn... |
b9d42c5060da1c81b8e207c73e665441ee45a0e6 | andreffs18/collective-intelligence | /chapter11/gp.py | 1,088 | 3.546875 | 4 | class FunctionWrapper:
def __init__(self, function, child_count, name):
self.function = function
self.child_count = child_count
self.name = name
class Node:
def __init__(self, function_wrapper, children):
self.function = function_wrapper.function
self.name = f... |
0e131fcfc987ed84e89df4bcb52c34cae5ac6aa7 | variablejun/keras__R | /keras/keras44_0_LSTM_Conv1D.py | 2,042 | 3.84375 | 4 | # 실습
# 1~100까지의 데이터를
from tensorflow.keras.models import Sequential, Model
from tensorflow.keras.layers import Dense, SimpleRNN, Dropout, LSTM, GRU, Input, Conv1D, Flatten
import numpy as np
'''
x y
1 2 3 4 5 6
'''
import numpy as np
x_data = np.array(range(1,101))
x_predict = np.array(range(96,105))
'''
96... |
196dcecaf7c1f56bd9b8367d8d5bc9301d10bd10 | variablejun/keras__R | /keras/keras42_cifar10_lstm.py | 2,504 | 4 | 4 | #모델링완성 하시오 32,32,3
# 모델링 완성
import numpy as np
import matplotlib.pyplot as plt
from tensorflow.keras.datasets import cifar10
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense, SimpleRNN, Dropout, LSTM, GRU, Input
(x_train, y_train), (x_test, y_test) = cifar10.load_data()
print(x_... |
5b6fd30b450f09cb724bf5ca88ab9640df63a2d6 | variablejun/keras__R | /keras/keras16_summary.py | 1,495 | 3.75 | 4 | import numpy as np
# 데이터구성
x = np.array([range(100),range(301,401),range(1,101),range(100),range(401,501)])
x = np.transpose(x)
y = np.array([range(711,811),range(101,201)])
y = np.transpose(y)
print(x.shape , y.shape) # 100,5 100,2
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import ... |
a8caeea6fec6cf32d63aa507764675774ff335ee | variablejun/keras__R | /keras/keras32_cifar100_dnn.py | 4,325 | 3.5625 | 4 | #overfit 극복
# 훈련데이터를 최대한 많이
# 노멀라이제이션(정규화) 사용
# 드롭아웃
import numpy as np
import matplotlib.pyplot as plt
from tensorflow.keras.datasets import cifar100
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Conv2D, Dense, Flatten, MaxPooling2D, Dropout, GlobalAveragePooling2D
(x_train, y_tra... |
5ba6d1c1e1a1bea6ed68d452128afdd3b3aaf887 | brianmego/erlang_practice | /mego/qsort.py | 226 | 3.6875 | 4 | def qsort(arr):
if len(arr) == 0:
return []
pivot = arr[0]
tail = arr[1:]
return (
qsort([x for x in tail if x < pivot]) +
[pivot] +
qsort([x for x in tail if x >= pivot])
)
|
988676052412d3a7a8618ee5243e17ce1c7373e2 | Spookso/draughts | /movement_update.py | 9,068 | 4.15625 | 4 | import time
# Checks that the piece is moving the right way for its type
def direction_check(board, start_row, start_col, end_row):
# if it is a normal piece, checks it is moving forward only
if board[start_row][start_col] == 1:
if end_row > start_row:
# print("Wrong Direction for Piece Typ... |
19508b0b36e260ddb27c4d99fa8184ac97339899 | judgedreadnaught/FinanceWebService | /volume.py | 2,820 | 3.65625 | 4 | import streamlit as st
import pandas as pd
import numpy as np
import yfinance as yf
import datetime as dt
from dateutil.relativedelta import relativedelta
from pandas_datareader import data as pdr
import math
from pandas_datareader import data as pdr
import yahoo_fin
import yahoo_fin.stock_info as si
yf.pdr_override()... |
35fb471859033685a8ba66332fa876df5a0d34dd | AndyDeany/sunni-remake | /lib/moves/move.py | 1,109 | 3.859375 | 4 | """Module for base universal move related classes and functions."""
class Move:
"""Class representing a character's move."""
@classmethod
def initialise(cls, game):
cls.game = game
def __init__(self, mana_cost):
self._sound = None
self.mana_cost = mana_cost
def play_soun... |
ccb3c0039b8fe2cf0db132c602c61a5865738f5f | AndyDeany/sunni-remake | /lib/keys.py | 2,341 | 3.703125 | 4 | import pygame
class Key:
all = {}
"""Class for representing a key on the keyboard."""
def __init__(self, keycode):
self.keycode = keycode
self.just_pressed = False
self.is_pressed = False
self.all[self.keycode] = self
def __bool__(self):
return self.just_pres... |
236a2e5b0a41339ac412f61e0db44832bc0efba6 | echang26/sudoku | /sudoku_final.py | 16,235 | 4.125 | 4 | import random
import sys
import argparse
from collections import defaultdict
#To play the game in the command line, run python sudoku_final.py --game
#To simply create & see a puzzle solve itself, run python sudoku_final.py without any arguments
### VARIABLES WE WILL USE LATER ON
ROWS = "ABCDEFGHI"
COLS = "123456789"... |
ee616fdba77fcdcf943c98413fbe55450584ad4d | hendrmat/cis457proj2 | /ChatClient.py | 5,822 | 3.578125 | 4 | # Matt Hendrick
# CIS 457
# Project 2
# This is the client side of the chat application
import socket
import threading
import tkinter
from tkinter import *
#from project2 import ChatGUI
#from project2 import ChatServer
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_address = socket.getho... |
0663a8b9c6160492925b0c5668ca98936fd241bf | vanng822/geosearch | /search/filters.py | 1,348 | 3.625 | 4 | from utils import get_distance
class Filter(object):
def apply(self, items):
""" Implementing specific filter task on result
Args:
result: list of result items
Returns:
list of filtered items
"""
raise NotImplementedError()
clas... |
29fe61f617c6a60b9498ba30c1804ab4e75fe242 | shitijseth/3D-Solar-System-Simulator | /finalproject.py | 8,554 | 3.65625 | 4 | from tkinter import *
import math
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation
window = Tk()
window.title("Solar System 3D Simulaor")
window.geometry('700x400')
lbl = Label(window, text="Click here to start simulation -> ")
lbl.grid(column=50, row=0)
lbl = Labe... |
d5eeac3fb4884487b3b8acbd63d5ff09e058c09a | nong2013/Apple-to-Raspberry-Pi | /Threading/countdown.py | 2,400 | 3.859375 | 4 | ##!/usr/bin/python
#
#Run a clock for a specified time with a specified interval
from tkinter import *
import threading
import _thread
from datetime import datetime, timedelta
from time import sleep
# a flag to determine if the processing loop stops
exitFlag = 1
# The thread class subclassed--
#overwrite __init__()... |
a8d363524dc77a216dbf6b331181ac9f05c7b4d8 | nong2013/Apple-to-Raspberry-Pi | /Early Lessons/python_strings_demo.py | 852 | 4.28125 | 4 | #python_Strings_demo
my_string ="and now for SOMEthing completely different"
my_silly_string ="silly walks"
pi_value= 3.1415926
integer_value = 123
print (my_string + ' -- The Ministry of ' + my_silly_string )
print (len(my_string))
print (my_string.capitalize())
print (my_string.upper())
print (my_string.lower())
p... |
cb9a6a25bb5215e00b97f4e55f4d64386a983eb7 | radroid/pdf-manager | /pdf_splitter.py | 6,609 | 4.0625 | 4 | """The module splits a PDF into two different PDFs at
a specified page number."""
from pathlib import Path
from PyPDF2 import PdfFileReader, PdfFileWriter
class PdfSplitter:
"""The class manages splitting of PDFs files.
Attributes:
pdf_file (PdfFileReader Object): the file object is used to read th... |
5d0b36d011b44ca7bb29e86d503590442918691d | baileyelysse/CEOProgram | /strings.py | 890 | 3.875 | 4 | """
title: strings
author: Bailey Patterson
date: 7/18/18 2:54 PM
"""
def how_eligible(essay):
# Returns how many categories are in a string
categories = 0
if "?" in essay:
categories += 1
else:
categories += 0
if ""''"" in essay:
categories += 1
else:
categorie... |
88992318794bff2acc9fefb8f7ce45786e095a8c | kgleijm/mock_data_to_postgreSQL | /postgres connection.py | 1,539 | 3.890625 | 4 | import random
import string # gives us easy access to an alphabetic list of uppercase characters
import psycopg2 # handles postgreSQL connection
import names # spits out random names
print(names.get_full_name())
# get list of all chars not represented in our database
listOfChars = list(string.ascii_uppercase)
# cre... |
09dcca918dee39291a7de4a3e15cbe89e3e7dfd6 | vinayakentc/BridgeLabz | /AlgorithmProg/VendingMachine.py | 1,042 | 4.3125 | 4 | # 10. Find the Fewest Notes to be returned for Vending Machine
# a. Desc > There is 1, 2, 5, 10, 50, 100, 500 and 1000 Rs Notes which can be
# returned by Vending Machine. Write a Program to calculate the minimum number
# of Notes as well as the Notes to be returned by the Vending Machine as a
# Change
# b. I/P > rea... |
402d9c848d6d0a6abfae084d76944b9faad4785a | vinayakentc/BridgeLabz | /ObjectOrientedPrograms/StockReport.py | 1,376 | 3.9375 | 4 | class Stocks:
def __init__(self, name, price, number):
self.name = name
self.price = price
self.number = number
class Portfolio:
"""This class contains methods for creating a portfolio for stock account
"""
def __init__(self):
self.value = 0
self.portfolio = []... |
032e58342dd4dd263ae96aabb6563dad78d68b15 | vinayakentc/BridgeLabz | /DataStructProg/Palindrome_Checker.py | 1,363 | 4.46875 | 4 | # PalindromeChecker
# a. Desc > A palindrome is a string that reads the same forward and backward, for
# example, radar, toot, and madam. We would like to construct an algorithm to
# input a string of characters and check whether it is a palindrome.
# b. I/P > Take a String as an Input
# c. Logic > The solution to ... |
25fab75d27473ef6b0949ddcbb0a2678eefbf108 | vinayakentc/BridgeLabz | /FunctionalProg/Factors.py | 1,012 | 4.21875 | 4 | # 6. Factors
# a. Desc > Computes the prime factorization of N using brute force.
# b. I/P > Number to find the prime factors
# c. Logic > Traverse till i*i <= N instead of i <= N for efficiency .
# d. O/P > Print the prime factors of number N
# ----------------------------------------------------------------------... |
8475bd109f4efb302b35f5d16ef5aaf358d43ad6 | vinayakentc/BridgeLabz | /DataStructProg/UnOrderedList.py | 1,985 | 4.28125 | 4 | # UnOrdered List
# a. Desc > Read the Text from a file, split it into words and arrange it as Linked List.
# Take a user input to search a Word in the List. If the Word is not found then add it
# to the list, and if it found then remove the word from the List. In the end save the
# list into a file
# b. I/P > Read fr... |
a0c8c7647d684e6aa48b1fe9aa76613b2c5436e2 | vinayakentc/BridgeLabz | /DataStructProg/Prime_anagram_Queue.py | 988 | 4.03125 | 4 | # Add the Prime Numbers that are Anagram in the Range of 0 - 1000
# in a Queue using the Linked List and Print the Anagrams from the Queue.
# Note no Collection Library can be used.
# --------------------------------------------------------------------------
from DataStructProg.Primes_util import Prime
from DataStructP... |
c324ede28a7c6bec9f7f9bc58d47ccf42851d0f0 | acse-yq3018/CMEECourseWork | /Week3/Code/get_TreeHeight.py | 790 | 3.890625 | 4 | #!/usr/bin/env python3
"""calculate treeheight via python"""
__appname__ = 'get_TreeHeight.py'
__author__ = 'Yuxin Qin (yq3018@imperial.ac.uk)'
__version__ = '0.0.1'
#import
import sys
import csv
import math
# read and write csv
f = open(sys.argv[1],'r')
g = open("../Result/" + sys.argv[1].split('.csv')[0].split('/... |
43571e37ad1874a2fae40dda3072bf32b5a7129c | acse-yq3018/CMEECourseWork | /Week2/Code/lc1.py | 1,521 | 4.21875 | 4 | #!/usr/bin/env python3
"""Use list comprehension and loops to extract target data"""
__appname__ = 'lc1.py'
__author__ = 'Yuxin Qin (yq3018@imperial.ac.uk)'
__version__ = '0.0.1'
###################################################################
birds = ( ('Passerculus sandwichensis','Savannah sparrow',18.7),
... |
92b7be10799cab430e99c1f0b422993511e39831 | josephhyatt/python_snippets | /fill_list_with_random_numbers.py | 236 | 4 | 4 | from random import randint
minimum = int(input("Insert minimum number: "))
maximum = int(input("Insert maximum number: "))
y = int(input("Insert range of random numbers: "))
x = [randint(minimum, maximum) for i in range(y)]
print(x) |
ecdab4779ef50d91930195f0e2199b8314b8ee47 | josephhyatt/python_snippets | /check_for_greatest_of_3_numbers.py | 405 | 4.1875 | 4 | user_input_0 = int(input("Insert 1st number: "))
user_input_1 = int(input("Insert 2nd number: "))
user_input_2 = int(input("Insert 3rd number: "))
print("The biggest number is: ", end="")
if user_input_1 <= user_input_0 >= user_input_2:
print(user_input_0)
elif user_input_0 <= user_input_1 >= user_input_2:
print(u... |
93b4b52cbabc2ab27d0ce967e2642bb34bd89c69 | coherent17/sort-algorithm | /sorting/heapsort.py | 824 | 4.09375 | 4 | def heapify(array,size,i):
largest=i
left_children=2*i+1
right_children=2*i+2
if left_children<size and array[left_children]>array[largest]:
largest=left_children
if right_children<size and array[right_children]>array[largest]:
largest=right_children
# //check need to swap ... |
851c04fab2eb9ab0a090f701246bc15241dd3201 | xf97/myLeetCodeSolutions | /src/257.py | 965 | 3.90625 | 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 binaryTreePaths(self, root: TreeNode) -> List[str]:
#递归实现
#深度优先遍历
if root == None:
return list()
... |
2dc75f48f4873327fa755ee62d2f989789e6bbda | xf97/myLeetCodeSolutions | /src/2.py | 1,426 | 3.734375 | 4 | # Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
#time defeat: 76%
#space defeat: 5%
#总体想法-分治,逐步向下
class Solution:
def addTwoNodes(self, _resultNode, _node1, _node2, _carry):
#终止情况
if _node1 == None and _n... |
a80fa37e05b6acfa74463fa9dddf9e3643336eaf | xf97/myLeetCodeSolutions | /src/1047.py | 1,966 | 3.59375 | 4 | class Solution:
def removeDuplicates(self, S: str) -> str:
#简单题我要重拳出击了
'''
学会思考用新的数据结构的一天(尽管程序效率一般但是一次提交就通过!)
time defeat: 5.06%
space defeat: 31.34%
'''
#边界条件
if not S:
return S
else:
'''
#普适情况
#... |
7c2032486a95fe0266477aaa5b8c3ad10a95794d | xf97/myLeetCodeSolutions | /src/337.py | 1,980 | 3.6875 | 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 dfs(self, node):
if not node:
#空节点
return 0, 0
#后序遍历,从底向上累加
... |
87e8c704d5eb42d0b675956af4308eac251450fe | xf97/myLeetCodeSolutions | /src/701.py | 910 | 3.90625 | 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
'''
基本思路-根据搜索二叉树的性质,搜索到合适的位置
构造新节点,然后组合二叉树,二叉树可用递归
time defeat: 32.36%
space defeat: 47.90%
time consuming: less than 15 mins
''... |
66efc7357be1d7a26b0fbbae8f6554ece9dbac0a | xf97/myLeetCodeSolutions | /src/31.py | 1,600 | 3.578125 | 4 | class Solution:
def nextPermutation(self, nums: List[int]) -> None:
"""
Do not return anything, modify nums in-place instead.
"""
#这种题是真的不会,看了题解,现在懂了
#题目保证数组非空
#这题就小饶字节一命,看看题解再做
#时间复杂度On,空间复杂度O1
#边界处理
length = len(nums)
if length == 1... |
9c2710e80f374efc217e8c9627ad3a65960fa2b5 | xf97/myLeetCodeSolutions | /src/407.py | 1,093 | 3.796875 | 4 | # Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
'''
时间击败: 62%
空间击败: 18%
'''
class Solution:
def sumOfLeftLeaves(self, root: TreeNode) -> int:
#递归遍历
result = list() #左叶子数组
#极端情... |
8ff90aca382e7854aeabdbc1c79e746b076e9d9a | xf97/myLeetCodeSolutions | /src/88.py | 1,471 | 3.75 | 4 | class Solution:
def merge(self, nums1: List[int], m: int, nums2: List[int], n: int) -> None:
"""
Do not return anything, modify nums1 in-place instead.
"""
#干翻字节!
#字节怎么现在都是简单题了,你不给力呀,整点得劲的给兄弟试试呀
#归并排序
#先看看使用额外空间Om+n的解法
#边界情况
#两次提交,注意python的深度赋值... |
03d3d2fad977f06d401676d7964d5bf89572af98 | xf97/myLeetCodeSolutions | /src/653.py | 1,344 | 3.6875 | 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 findTarget(self, root: TreeNode, k: int) -> bool:
#最简单的方法,中序遍历,获取从小到大的序列
#然后双指针向中间,时间复杂度... |
9f04cfc697b7094cff6af814ea3a7b6a157dfeb8 | lakshsharma07/training2019 | /day13/Day_13.py | 20,881 | 3.796875 | 4 | """
Histogram
"""
import numpy as np
import matplotlib.pyplot as plt
data = np.random.randn(1000)
plt.hist(data)
plt.hist(data, normed=True, bins=30)
#plt.hist(data, bins=30, normed=True, alpha=0.5,
# histtype='stepfilled', color='steelblue',
# edgecolor='none');
"""
2D plottin... |
d1683db8e58069a27bc14490f507b1a9deedb8d3 | lakshsharma07/training2019 | /day22/deliveryfleet.py | 2,278 | 3.703125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Tue Jun 4 10:47:08 2019
@author: Lakshay
"""
"""
Q1. (Create a program that fulfills the following specification.)
deliveryfleet.csv
Import deliveryfleet.csv file
Here we need Two driver features: mean distance driven per day (Distance_feature) and the mean percentage of tim... |
fb6db0fe2597bed0a639b315521994730fcdb47b | lakshsharma07/training2019 | /day11/solution/national_share.py | 1,139 | 3.5625 | 4 | """
Code Challenge
https://en.wikipedia.org/wiki/List_of_states_and_union_territories_of_India_by_area
Scrap the data from State/Territory and National Share (%) columns for top 6
states basis on National Share (%).
Create a Pie Chart using MatPlotLib and explode the state with largest national share %.
"""
# s... |
4381904c0e68aa2d6e4d4338e48046eebc29ef25 | lakshsharma07/training2019 | /day13/solution/baltimore.py | 3,118 | 3.765625 | 4 | """
Code Challenge
Name:
Baltimore City Analysis
Filename:
baltimore.py
Problem Statement:
Read the Baltimore_City_Employee_Salaries_FY2014.csv file
and perform the following task :
0. remove the dollar signs in the AnnualSalary field and assign it as a float
0. Group the data on JobTit... |
7e6e481c41c7f2a6b377781206b99d6dbae722d0 | lakshsharma07/training2019 | /day9/challenge1.py | 3,084 | 3.546875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Thu May 16 11:34:22 2019
@author: Lakshay
"""
"""
Code Challenge 1
Write a python code to insert records to a mongo/sqlite/MySQL database
named db_University for 10 students with fields like
Student_Name, Student_Age, Student_Roll_no, Student_Branch.
"""
import sqlite3
from ... |
fde92a6833220f1c1642d32e740e5b00e7e090a8 | lakshsharma07/training2019 | /day6/book_shop1.py | 2,075 | 3.875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Mon May 13 11:40:51 2019
@author: Lakshay
"""
"""
Code Challenge
Name:
Book Shop
Filename:
book_shop1.py
Problem Statement:
Imagine an accounting routine used in a book shop.
It works on a list with sublists, which look like this:
Order Numbe... |
0f15c3f46348e8d545514bd9f7e404a307a93673 | lakshsharma07/training2019 | /day12/Automobile.py | 732 | 3.703125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Tue May 21 11:58:12 2019
@author: Lakshay
"""
"""
Code Challenge
Name:
Exploratory Data Analysis - Automobile
Filename:
automobile.py
Dataset:
Automobile.csv
Problem Statement:
Perform the following task :
1. Handle the missing values for ... |
696a6d17444c534b3da6ef868569bb27cf0cae38 | lakshsharma07/training2019 | /day1/ridecost_cal.py | 234 | 3.953125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Tue May 7 11:58:21 2019
@author: Lakshay
"""
distance_travel = int(input())
fuel_cost = int(input())
average = int(input())
total_cost=((distance_travel*2)/average)*fuel_cost
print(total_cost) |
b91376b39cbbc550f1fae0340f9dccfd38e28904 | lakshsharma07/training2019 | /day11/solution/space_numpy.py | 557 | 4.03125 | 4 | """
Code Challenge
Name:
Space Seperated data
Filename:
space_numpy.py
Problem Statement:
Take 9 space separated numbers from user.
Write a python code to convert it into a 3x3 NumPy array of integers.
Input:
6 9 2 3 5 8 1 5 4
Output:
[[6 9 2]
[3 5 8]
[1 5 4]]
"""
imp... |
6fa584c7919448cdaf7f2333a935c636d97730d0 | lakshsharma07/training2019 | /day4/Python_Dungeon_game_MiniProject.py | 1,346 | 4.09375 | 4 | # Dungeon Game
"""
Challenge 1
It would be a 2 dimensional maze game
We would put the player in a random room in the grid
We would also put a monster in a random room in the grid
We would out a door in a random room in the grid
The player would then move around the grid to find the door
Don’... |
7d46a845ad0bed2298511f782e37faee1f7701ac | afurkanyegin/Python | /The Art of Doing Code 40 Challenging Python Programs Today/2-MPH to MPS Conversion App.py | 262 | 4.15625 | 4 | print("Welcome to the MPH to MPS Conversion App")
speed_in_miles=float(input("What is your speed in miles:"))
speed_in_meters=speed_in_miles * 0.4474
rounded_speed_in_meters=round(speed_in_meters,2)
print(f"Your speed in MPS is: {rounded_speed_in_meters}")
|
d0750f6a1a4ce391db6dbc0c17be3e7ade85fd66 | Julian-Azange/Python_Basico | /variables.py | 386 | 3.59375 | 4 | name = "Julian"
print(name)
x = 100
# case sensitive
book = "Digital Fortress"
Book = "Digital Fortress"
# Conventiones
book_name = "Digital Fortress" #Snake Case
bookName = "Digital Fortress" #Camel Case
BookName = "Digital Fortress" #Pascal Case
PI = 3.1416
#Dinamico se puede cambiar el valor de la variable...
#... |
9ff38ef5762843be10593ea173a34bf9cda1ce80 | Julian-Azange/Python_Basico | /loops.py | 408 | 3.984375 | 4 | foods = ['apple', 'bread', 'cheese', 'milk', 'banana', 'graves']
""" print(foods[0])
print(foods[1])
print(foods[2])
print(foods[3])
print(foods[4]) """
print("")
print(" FOR")
print("")
for food in foods:
if food == "cheese":
# break # se detiene el ciclo
continue
print(food)
print("")
print(... |
f5c8c53655ab606451b896bdcca334b8f7206edc | AndreiAvram99/Mancala | /components/label.py | 2,157 | 3.75 | 4 | from config import *
class Label:
""" Label docstring
Description:
_________
This class deals with labels drawing
Attributes:
---------
text: `str`
Label text
x: `float`
Label x position
y: `float`
Label y positi... |
7dd9d18ecab86caf2d7763d4fa7d91e35a4412b6 | pgroves95/py_stats | /mean.py | 250 | 3.875 | 4 | def mean(num_list):
sum = 0
for num in num_list:
sum += num
mean = sum / len(num_list)
return mean
# test cases
print(mean([1, 1, 1, 1]))
print(mean([1, 1, 2, 2]))
print(mean([1, 2, 3, 5]))
print(mean([20, 233, 12, 3.22]))
|
95bdeb5ab50a55c46bcce195cf1b8b199347cad8 | tylerwray/project-euler | /6_square_sum_difference.py | 716 | 4.03125 | 4 | # The sum of the squares of the first ten natural numbers is:
# 1^2 + 2^2 + ... + 10^2 = 385
# The square of the sum of the first ten natural numbers is:
# (1 + 2 + ... + 10)^2 = 55^2 = 3025
# Hence the difference between the sum of the squares of the first ten natural numbers
# and the square of the sum is 3025 - ... |
7a16dd03e157d208fc574fa25488993f185d1a30 | TonyVH/Python-Programming | /Chapter 07/eligible.py | 641 | 3.875 | 4 | # eligible.py
# Program to determine if someone is eligible for the
# US senate, or the US representatives
def main():
age = eval(input('Enter your age: '))
years = eval(input('Enter the number of years you have been a citizen: '))
if age >= 30 and years >= 9:
print('You are eligible to run for th... |
23a71da2a35150b6dd70cc4f5507cce6c37b87a6 | TonyVH/Python-Programming | /Chapter 02/Calculator.py | 541 | 4.25 | 4 | # Calculator.py
# This is a simple, interactive calulator program
def calculator():
print('Calculator guide:')
print('Use + to add')
print('Use - to subtract')
print('Use * to multiply')
print('Use / to divide')
print('Use ** for exponentials')
print('Use // for floor division')
print('U... |
42641191913cfb89cd44aae5a228f306bda3b620 | TonyVH/Python-Programming | /Chapter 07/BMI.py | 512 | 4.09375 | 4 | # BMI.py
# Calculates Body Mass Index and prints our if
# the user is in, aobve, or below the healthy range
def main():
pounds = eval(input('Enter your weight in pound: '))
height = eval(input('Enter your height in inches: '))
BMI = (pounds*720)/(height**2)
if BMI < 19:
health = 'below'
e... |
c71637009a6f1411428c88d9a95cf8077054574f | TonyVH/Python-Programming | /Chapter 06/eachSquared.py | 354 | 3.984375 | 4 | # eachSquared.py
# Program to square each number in a list
def square(x):
return x*x
def eachSquared(numList):
numList = [square(i) for i in numList]
return numList
def main():
numbers = input('Enter a list of numbers: ').split()
numbers = [int(i) for i in numbers]
newList = eachSquared(num... |
0c7a6dc53b0e75076918ef422b5cf3da28b052a1 | TonyVH/Python-Programming | /Chapter 05/acronym.py | 330 | 4.34375 | 4 | # acronym.py
# Program to create an acronym from a user given sentence/phrase
def main():
print('This program will create an acronym from a word or phrase\n')
phrase = input('Enter a sentence or phrase: ')
phrase = phrase.split()
for words in phrase:
print(words[0].upper(), end='')
print(... |
948609996e1dc5db9b57390c45686dbedcc9fede | TonyVH/Python-Programming | /Chapter 09/racquetball.py | 3,320 | 3.828125 | 4 | # racquetball_.py
import random
def main():
printIntro()
probA, probB, n, m = getInputs()
winsA, winsB, shutoutsA, shutoutsB = simMMatches(probA, probB, n, m)
printSummary(winsA, winsB, shutoutsA, shutoutsB)
def printIntro():
print('This program simulates a game of racquetball between two')
p... |
739ba6b1b587041d102834ebba709b4193b6528a | makatoap9039/01-Lucky_Unicorn | /02_yes_no_v2.py | 628 | 4.09375 | 4 | show_instructions = ""
while show_instructions.lower() != "xxx":
# ask users if they have played before
show_instructions = input("have you played this before?").lower()
# if they say yes, output program continues
if show_instructions == "xxx":
break
elif show_instructions == "yes" or sh... |
986d6719c16be133bcfe83a7d523fd58489b714a | edelille/Learning-Python | /Chapter 1/04-divisors.py | 301 | 4.09375 | 4 | def findDivisors(list, n):
for x in range(n, 0, -1):
if n%x == 0:
list.append(x)
if __name__ == '__main__':
n = int(input('Enter a number to find all divisors of: '))
listOfDivisors = []
findDivisors(listOfDivisors, n)
for x in listOfDivisors:
print(x) |
7f6d4730e8c710268ae4d039797fc8038f5b97bb | zhangweisgithub/demo | /python_basic/列表与元组/列表交集差集并集.py | 539 | 3.921875 | 4 | # !/usr/bin/env python
# -*- coding: utf-8 -*-
"""
如果使用set中的函数,需要把列表先转换为集合
"""
a = [1, 2, 3, 4]
b = [4, 3, 5, 6]
jj1 = [i for i in a if i in b]
jj2 = list(set(a).intersection(set(b))) # 交集
print(jj1)
print(jj2)
bj1 = list(set(a).union(set(b))) # 并集
print(bj1)
# 求差集
cj1 = list(set(a).difference(... |
83275c5e3dc2d6403c2b0a42fa18f2de33d6bcce | zhangweisgithub/demo | /python_basic/字典/字典中合并相同的key.py | 660 | 3.875 | 4 | # !/usr/bin/env python
# -*- coding: utf-8 -*-
list1 = [{"a": 123}, {"a": 23}, {"b": 12}]
"""方法一"""
dic = {}
for i in list1:
for k, v in i.items():
dic.setdefault(k, []).append(v)
print(dic)
"""方法二"""
print([{k: v} for k, v in dic.items()])
"""===================="""
a = {'2710': None, 'heads': 0, 'tail... |
3de896ed80d8450a9bba7f7d179b116778ef9499 | zhangweisgithub/demo | /python_basic/列表与元组/两个列表判断其不同元素.py | 229 | 3.5625 | 4 | # !/usr/bin/env python
# -*- coding: utf-8 -*-
a = [1, 2, 3, 4]
b = [1, 2, 3, 4, 5]
m = [x for x in a if x in b]
print("same:", m)
n = [y for y in (a + b) if y not in b]
k = [y for y in (a + b) if y not in a]
print(n)
print(k)
|
3ec25f6eaa2942b742909bfa1a74a25581dd6dd1 | zhangweisgithub/demo | /python_basic/列表与元组/切片.py | 963 | 3.703125 | 4 | # -*- coding: utf-8 -*-
# @Time : 2018-05-03 23:18
# @Email : Yzh_smlie@163.com
# @File : 下标和切片切片.py
"""字符串[开始索引:结束索引:步长]"""
num_str = "0123456789"
# 1. 截取从 2 ~ 5 位置 的字符串
print(num_str[2:6])
# 2. 截取从 2 ~ `末尾` 的字符串
print(num_str[2:])
# 3. 截取从 `开始` ~ 5 位置 的字符串
print(num_str[:6])
# 4. 截取完整的字符串
print(num_str[:... |
bd6dea495974d27f43e51df3b048ae90a6a66c26 | zhangweisgithub/demo | /python_module/argparse_module/case1.py | 1,645 | 3.96875 | 4 | """
参考:
https://www.bilibili.com/video/BV1U4411j7xb?from=search&seid=3388872340225112052
官方文档:
https://docs.python.org/3/library/argparse.html#default
添加互斥组的时候, 两个参数只能选择其中的一个参数作为输入
verbose: 冗余的
"""
import math
import argparse
parse = argparse.ArgumentParser(description="Calculate volume of Cylinder")
parse.add_argumen... |
b0150f42d7b776b252962d36a347475514d647e7 | zhangweisgithub/demo | /platform/swagger解析/get_item_by_key_demo.py | 1,527 | 3.546875 | 4 | # !/usr/bin/env python
# -*- coding: utf-8 -*-
def get_item_by_key(obj, key, result=None):
if isinstance(obj, dict):
for k in obj:
if key == k:
if isinstance(result, list):
if isinstance(obj[k], list):
result.extend(obj[k]) # 如果value... |
d489adae1d6673883135fa5686dd6729a0384fc0 | zhangweisgithub/demo | /regular/字符串切割.py | 288 | 3.515625 | 4 | # !/usr/bin/env python
# -*- coding: utf-8 -*-
"""
s="info:xiaoZhang 33 shandong",用正则切分字符串输出['info', 'xiaoZhang', '33', 'shandong']
|表示或,根据冒号或者空格切分
"""
import re
s = "info:xiaozhang 33 shandong"
res = re.split(r":| ", s)
print(res)
|
dcec4375e5f1a49954743ed74bbad78a50d38803 | zhangweisgithub/demo | /python_basic/上下文管理器/case1.py | 1,277 | 3.875 | 4 | # !/usr/bin/env python
# -*- coding: utf-8 -*-
"""
with关键字和上下文管理器
https://blog.csdn.net/u010339879/article/details/103340517
什么是上下文管理器?
任何实现了 __enter__() 和 __exit__() 方法的对象都可称之为上下文管理器
实现了 __enter__() 和 __exit__() 方法的对象就可以使用 with 语句
上下文管理的作用 和 目的
上下文管理 对象 是为了存在的目的 是管理 with 语句, 而 with 语句 目的是为了 简化 tyr/ finally 这种模式
这种 模... |
d47af16a297879c68f7b3761b0ddf847dbbfc223 | zhangweisgithub/demo | /python_basic/其他/闭包.py | 1,038 | 3.515625 | 4 | # -*- coding: utf-8 -*-
# @Time : 2018-05-17 15:47
# @Email : Yzh_smlie@163.com
# @File : 闭包.py
# 闭包函数的实例
# outer是外部函数 a和b都是外函数的临时变量
def outer(a):
b = 10
# inner是内函数
def inner():
# 在内函数中 用到了外函数的临时变量
print(a + b)
# 外函数的返回值是内函数的引用
return inner
if __name__ == '__main__':
... |
f895215289ae0705510722f035082c657bcbfc7e | zhangweisgithub/demo | /regular/数据提取.py | 440 | 3.515625 | 4 | # !/usr/bin/env python
# -*- coding: utf-8 -*-
"""<div class="nam">中国</div>,用正则匹配出标签里面的内容(“中国”),其中class的类名是不确定的"""
import re
str = '<div class="name">中国</div>'
# .代表可有可无,*代表任意字符 (.*?)提取文本
res = re.findall(r'<div class=".*">(.*?)</div>', str)
print(res)
# 数据替换
a = "张明 93分"
ret = re.sub(r"\d+", "100", a)
print(r... |
433a50201f6701711216a57bd7839d86ca667331 | zhangweisgithub/demo | /python_basic/其他/range的参数.py | 508 | 4.25 | 4 | # !/usr/bin/env python
# -*- coding: utf-8 -*-
# range(start, stop[, step])
print(list(range(5))) # [0, 1, 2, 3, 4] 默认是0-4
print(list(range(0, 5))) # [0, 1, 2, 3, 4]
print(list(range(1, 7))) # [1, 2, 3, 4, 5, 6]
print(list(range(3, 20, 3))) # [3, 6, 9, 12, 15, 18] 第三个参数代表的是step
print(list(range(10, 0, -1)))... |
a5e07f98fb6d18fc88a88495e1aadb105b7fb5a5 | zhangweisgithub/demo | /algorithm/冒泡排序.py | 1,468 | 4.1875 | 4 | # !/usr/bin/env python
# -*- coding: utf-8 -*-
"""
基本思想: 冒泡排序,类似于水中冒泡,较大的数沉下去,较小的数慢慢冒起来,假设从小到大,即为较大的数慢慢往后排,较小的数慢慢往前排。
直观表达,每一趟遍历,将一个最大的数移到序列末
冒泡排序的时间复杂度是O(N^2)
冒泡排序的思想: 每次比较两个相邻的元素, 如果他们的顺序错误就把他们交换位置
冒泡排序原理: 每一趟只能将一个数归位, 如果有n个数进行排序,只需将n-1个数归位, 也就是说要进行n-1趟操作(已经归位的数不用再比较)
缺点: 冒泡排序解决了桶排序浪费空间的问题, 但是冒泡排序的效率特别低
"""
def bu... |
7a2db719c449520ceced920dee70ba7bce3ccef3 | ahammadshawki8/DSA-Implementations-in-Python | /CHAPTER 09 (priority queues)/bottom_up_heap.py | 667 | 3.765625 | 4 | from heap_priority_queue import *
class BottomUPHeap(HeapPriorityQueue):
def __init__(self,contents=()):
"""Create a new priority queue.
By default, queue will be empty. If contents is given, it should be as
an iterable sequence of (k,v) tuples specifying the initial contents.
"""
... |
15cbdd28a9dc217883e497729e4560a1300243ca | ahammadshawki8/DSA-Implementations-in-Python | /CHAPTER 11 (search trees)/after_algo_in_binary_st.py | 643 | 3.90625 | 4 | # this is a part of binary search tree class.
# The right, left and parent functions can be found in the binary search tree implementation.
def after(p):
if right(p) is not None: # successor is leftmost position in p's right subtree
walk = right(p)
while left(walk) is not None:
walk ... |
6b22a5233d5817086b6d278afe627e902353e4f4 | ahammadshawki8/DSA-Implementations-in-Python | /CHAPTER 10 (maps, hash tables and skip lists)/skip_list_class.py | 2,252 | 3.5625 | 4 | from random import randint, seed
class SkipList:
class Node:
__slot__ = "elem","next"
def __int__(self,height=0,elem=None):
self.elem = elem
self.next = [None]*height
def __init__(self):
self.head = SkipList.Node()
self.len = 0
self.maxHeigh... |
b7761051d28b7c7001b80a02d6c3553a947dd994 | ahammadshawki8/DSA-Implementations-in-Python | /CHAPTER 11 (search trees)/tree_map_class.py | 9,771 | 3.78125 | 4 | from map_base_class import *
from linked_binary_tree import *
class TreeMap(LinkedBinaryTree,MapBase):
"""Sorted map implementation using binary search tree."""
#----------------------------override Position class------------------------
class Position(LinkedBinaryTree.Position):
def key(self)... |
46aac921ea726c4142720ea013893ec6a5d2fdeb | ahammadshawki8/DSA-Implementations-in-Python | /CHAPTER 10 (maps, hash tables and skip lists)/sorted_table_map.py | 4,845 | 3.90625 | 4 | from map_base_class import *
class SortedTableMap(MapBase):
"""Map implemetation using a sorted table."""
#----------------------------nonpulic behavious-----------------------------
def _find_index(self,k,low,high):
"""Return index of the leftmost item with key greater than or equal to k.
... |
bfa449a9ca786ee6c7c6ba0de7bc51bfc91d4b30 | ahammadshawki8/DSA-Implementations-in-Python | /CHAPTER 05 (array_based_sequences)/caesar ciphar.py | 1,062 | 3.828125 | 4 | # Caesar_Cipher class
class CaesarCipher:
def __init__(self,shift):
encoder=["k"]*26
decoder=["k"]*26
for k in range(26):
encoder[k] = chr((k + shift) % 26 + ord( "A" ))
decoder[k] = chr((k - shift) % 26 + ord( "A" ))
self.forward = "".join(... |
a087f718d7c3264dc2186f6a72ef2b3e33aef5cc | ahammadshawki8/DSA-Implementations-in-Python | /CHAPTER 08 (trees)/inorder_traversals.py | 880 | 3.890625 | 4 | # the functions of this code belong to BinaryTree class
from binary_tree_abc import *
class TreeTraversals(BinaryTree):
def inorder(self):
"""Generate a inorder iteration of positions in the tree."""
if not self.is_empty():
for p in self._subtree_inorder(self.root()):
yi... |
950bb3e6ed1390287064a6c5e757c9e682dccd7a | ahammadshawki8/DSA-Implementations-in-Python | /CHAPTER 12 (sorting and selection)/node_class.py | 376 | 3.765625 | 4 | # simple implementation of Node class.
class Node:
"""Lightweight, non-public class for storing a singly linked list"""
__slots__ = "_element", "_next" # streamline memory usage.
def __init__(self,element,next):
self._element = element # reference to user's element
self.... |
b9a58a6c50e1c9e0afa856842f908ac7fef057ce | ahammadshawki8/DSA-Implementations-in-Python | /CHAPTER 13 (text processing)/doubly_linked_list.py | 1,604 | 3.578125 | 4 | from doubly_node_class import *
class _DoublyLinkedBase:
"""A base class providing a doubly linked list representation."""
def __init__(self):
"""Create an empty list."""
self._header = self._Node(None,None,None)
self._trailer = self._Node(None,None,None)
self._header._next = s... |
1bcd526e6e0efd5c566f629a2d4945e2c41b759b | Yurcik45/python-train | /pynative_exercises/2.py | 264 | 4.34375 | 4 | #2 Отображение трех строк «Name», «Is», «James» как «Name ** Is ** James»
string_1 = "Name"
string_2 = "Is"
string_3 = "James"
print(string_1 + "**" + string_2 + "**" + string_3)
# or
print(string_1, string_2, string_3, sep="**") |
4e0eaa58615f6198d884c55a464cc5ee439f6b2f | jvjvalerio/Google-MDP-2021 | /Day_8_Fish_Tank_Project.pyde | 1,387 | 3.5625 | 4 | def setup():
size(600, 600)
background(0, 0, 255)
# Parameters for the drawFish() function
fishRed = random(255)
fishGreen = random(255)
fishBlue = random(255)
fishWidth = 150
fishHeight = 75
drawFish(fishRed, fishGreen, fishBlue, fishWidth, fishHeight)
# Parameters... |
09a9c8b940b0d85932ccd59e2c627c3c2b50f4f2 | AKolar5/Data_Structures | /Binary_Search_Tree.py | 10,887 | 4.09375 | 4 | class Binary_Search_Tree:
# TODO.I have provided the public method skeletons. You will need
# to add private methods to support the recursive algorithms
# discussed in class
class __BST_Node:
# TODO The Node class is private. You may add any attributes and
# methods you need. Recall that attributes in ... |
fbdc74efd75f369c0be4cb1869ec99c60a0d7004 | frolpaxa/Programming-in-Python | /1. Diving in Python/Week 2/to_json.py | 592 | 3.5 | 4 | import json
import functools
def to_json(func):
@functools.wraps(func)
def wrapped(*args, **kwargs):
result = json.dumps(func(*args, **kwargs))
return result
return wrapped
@to_json
def get_data():
return {'data': 42}
@to_json
def get_list():
return [1, 2, 4]
if __name__ == '... |
bc8b23bd6574e9bc1d3d941448d7cecd2d7d93f0 | kashifahmed-git/project-files | /Python/Date_Asg2.py | 2,459 | 4.09375 | 4 | import datetime
from datetime import date
from datetime import timedelta
import calendar
"""
t1 = datetime.datetime.strptime("2021-3-1","%Y-%m-%d")
start_day = date.isoweekday(t1)
print(start_day)
t2 = datetime.datetime.strptime("2021,3,8","%Y,%m,%d")
# end_day = date.isoweekday(t2)
end = calendar.weekday... |
222d3abc4c3dff29861b066fb0741007e8997342 | vpgle/py | /7.seven/input_test.py | 145 | 3.5 | 4 | # -*- coding:gb18030 -*-
message = input("룺")
if "FFF" == message:
print("ȷ")
else:
print("WRONG!")
|
4a877673cec3fd08b83bb5d6200eb603e7ff6265 | vpgle/py | /7.seven/7-4.py | 254 | 3.671875 | 4 | # -*- coding: gb18030 -*-
# print("7-4")
prompt = "Please add ingredients: "
prompt += "\n(Enter 'quit' to the end)"
while True:
message = input(prompt)
if message != 'quit':
print("We will add " + message)
else:
break
|
5431d012e0290d691856e565167c32f1d5d2b46f | vpgle/py | /7.seven/7-3.py | 174 | 3.75 | 4 | # -*- coding: gb18030 -*-
ten = input("һ֣ ")
if int(ten) % 10 == 0:
print(ten + "10ı")
else:
print(ten + "10ı")
|
4192cf08639693d2efe9c2467e5341176dd99fcb | aayush7484/Training | /searchelement.py | 145 | 3.890625 | 4 | list1=list(map(int,input().split(" ")))
ele=int(input())
if ele in list1:
print("Element Exists")
else:
print("Element does not exists")
|
d09ee749ac4d4a253f3d8527e5cc225fb6c6a297 | XXQ2/CrawlAndScrape | /chapter_4/8.error_handling_with_retrying.py | 1,146 | 3.703125 | 4 | # retryingを使ってリトライ処理を簡潔に書く
import requests
from retrying import retry
# 一時的なエラーを表すステータスコード
TEMPORARY_ERROR_CODES = (408, 500, 502, 503, 504)
def main():
response = fetch('http://httpbin.org/status/200,404,503')
if 200 <= response.status_code < 300:
print("success!")
else:
print("Error!")... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.