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 |
|---|---|---|---|---|---|---|
f4fc59d24310afd8a4fb778ad743d194cc0c1e2a | Isaac-D-Dawson/Homework-Uploads | /PyCheckIO/MorseDecoder.py | 2,122 | 4.125 | 4 | # Your task is to decrypt the secret message using the Morse code.
# The message will consist of words with 3 spaces between them and 1 space between each letter of each word.
# If the decrypted text starts with a letter then you'll have to print this letter in uppercase.
# example
# Input: The secret message.
# Out... |
86ed5c59f6547324bb855690751aec0328289909 | Isaac-D-Dawson/Homework-Uploads | /PyCheckIO/WordsOrder.py | 2,087 | 4 | 4 | # You have a text and a list of words. You need to check if the words in a list appear in the same order as in the given text.
# Cases you should expect while solving this challenge:
# word from the list is not in the text - your function should return False;
# any word can appear more than once in a text - use only ... |
26f90aa4a30db618faf0a078ed2e653cf18d2ebd | Isaac-D-Dawson/Homework-Uploads | /Co-19-HW/DoubleLetters.py | 908 | 4.09375 | 4 | #DoubleLetters.py 19.03.2020
#Define a function and make it take in strings.
def double_letters(string):
#Set the default output to False
output = False
#Go through every letter in the input, except fort he last one...
for i in range(len(string)-1):
#...and compare it to the next letter i... |
50deb4603696cf2de54543fdc813df491944525c | BerkeleyPlatte/competitiveCode | /weird_string_case.py | 958 | 4.4375 | 4 | #Write a function toWeirdCase (weirdcase in Ruby) that accepts a string, and returns the same string with all even indexed characters in each word upper cased, and all odd
#indexed characters in each word lower cased. The indexing just explained is zero based, so the zero-ith index is even, therefore that character sh... |
04dab541d23a102c7b8ecfa914ec0bd57f41a812 | dmchu/selenium_gr_5 | /git_tests/third_file.py | 107 | 3.6875 | 4 | # 2. Round 5.23222 to two decimal places
x = 5.23225
y = round(x,2)
z = round(x,3)
print(round(z + y))
|
5ca4a58e17454d5f434ba4074d33da0eb23e1e20 | KurutoDenzeru/Python-UETasks | /Sandwich IcedTea.py | 569 | 3.84375 | 4 | import os
os.system
print("Welcome. Products offfered: Sandwich = Php50 & Iced Tea: Php30")
print("Proceed with bill calculation.")
print("-----"*6)
swprice = float(input("Enter no. of sandwich/es: "))
itprice = float(input("Enter no. of iced tea: "))
totalbill = (swprice * 50) + (itprice * 30)
print("The... |
8c1289a125327f4a8ae0c0098d94df45db1129d8 | KurutoDenzeru/Python-UETasks | /Credentials.py | 346 | 3.96875 | 4 | print('name: ')
Name = input();
print('course: ')
Course = input();
print('student number: ')
StudentNumber = input();
print('Year level: ')
YearLevel = input();
print('-------'*6)
print('Hello ' + Number + '\nYour course is ' + Course + '\nAnd your student number is ' + StudentNumber + '\nAnd your year... |
30b86c24fce10c0d8f23823b4d0ddc13f6b939cf | KurutoDenzeru/Python-UETasks | /Even Odd List.py | 734 | 4.03125 | 4 | import os
os.system('cls')
EvenList = []
OddList = []
Number = int(input("Enter an Integer: "))
while (Number!=0): #Until it is 0, It will end the loop.
if (Number%2 !=0):
OddList.append(Number)
else:
EvenList.append(Number)
os.system('cls')
print("Even Numbers: ", EvenList) #Your Text then com... |
89708757e3ec29b31feef559b24ff8b3a336c6e5 | gab-umich/24pts | /fraction.py | 1,979 | 4.1875 | 4 | from math import gcd
# START OF CLASS DEFINITION
# EVERYTHING IS PUBLIC
class Fraction:
"""A simple class that supports integers and four operations."""
numerator = 1
denominator = 1
# Do not modify the __init__ function at all!
def __init__(self, nu, de):
"""Assign numerator and denominat... |
f1b2c741aad927b7626706dbebb7bd8bc2e04619 | NameIsAlex/Python | /program41.py | 83 | 3.6875 | 4 | for numbers in range(0, 100, 5):
print(numbers, end=" ")
print("\nThat's that!")
|
eccbba271b6013c53632cae3328815951e0777db | Luoxsh6/CMEECourseWork | /Week2/code/oaks_debugme.py | 1,205 | 3.5625 | 4 | #!/usr/bin/env python
"""it is using for debugging practice"""
__author__ = 'Xiaosheng Luo (xiaosheng.luo18@imperial.ac.uk)'
__version__ = '2.0.0'
import csv
import sys
import pdb
import re
# Define function
def is_an_oak(name):
""" Returns True if name is starts with 'quercus'
>>> is_an_oak('Fagus sylvati... |
1fb18bf77b33d4e911364ff771b8ea1bb11c20cc | Luoxsh6/CMEECourseWork | /Week2/code/tuple.py | 980 | 4.5625 | 5 | #!/usr/bin/env python
"""Practical of tuple with list comprehension"""
__author__ = 'Xiaosheng Luo (xiaosheng.luo18@imperial.ac.uk)'
__version__ = '0.0.1'
birds = (('Passerculus sandwichensis', 'Savannah sparrow', 18.7),
('Delichon urbica', 'House martin', 19),
('Junco phaeonotus', 'Yellow-eyed junc... |
6c8316a6854d8822b77a57c8e8963bcfb8d106e6 | igorgarbuz/bootcamp_python | /day01/ex02/vector.py | 1,365 | 3.640625 | 4 | class Vector:
def __init__(self, values):
self.values = values
self.length = len(values)
def __add__(self, i):
if not isinstance(i, Vector):
return Vector([v + i for v in self.values])
else:
return Vector([z[0] + z[1] for z in zip(self.values, i.values)])... |
094a18310c38d4f6680e8c6625f43edcd1dfe1c7 | Mekenwaka1/wdi_multilinguist | /multilinguist.py | 3,459 | 3.765625 | 4 | import requests
import json
import random
class Multilinguist:
"""This class represents a world traveller who knows
what languages are spoken in each country around the world
and can cobble together a sentence in most of them
(but not very well)
"""
translatr_base_url = "http://bitmakertranslate.herokuap... |
975a4b5edcaca23f9c5219d546aee9dc2fc62fc6 | MarcoDiFrancesco/LittleProjects | /Python/2020-03-19 Domino algotithm.py | 421 | 4 | 4 | """
Exercise picture
https://i.imgur.com/Ijp6QEe.png
"""
def domino_fast(n):
a, b = 1, 1
for _ in range(2, n):
a, b = b, a + b
return b
def domino(n):
DP = [None] * n
DP[0], DP[1] = 1, 1
for i in range(2, n):
DP[i] = DP[i - 1] + DP[i - 2]
return DP[-1]
if __name__ ==... |
f6e48aab86b9e2ef4f7e260f60aa7d7a3f504d2d | Artx999/MA-178-groupProject | /newtonRaphson/task2.py | 2,107 | 4 | 4 | # Import libraries and Newton Raphsons Method
from newtonFunction import *
# Define a function that expresses the relation between angele 1 and angle 2
def f(o1):
return (-2 * sym.sin(o1) - (17 / 2) * sym.sin(x) + 6) ** 2 + (
-(17 / 2) * sym.cos(x) - 2 * sym.cos(o1) + 10) ** 2 - 49
# Define a functi... |
46e3207fde952fcc0447d375d4429af970ab6d87 | RexBone/Playing-with-Probability | /RSA/permute_prob.py | 1,438 | 3.765625 | 4 | from math import factorial
from math import pow
# of possible RSA key values
rc = pow(6, 9)
rcs = str(rc) #as string
num_digits_to_print = 15
#order matters
def permute_count(n, r):
return factorial(n)/(factorial(n-r))
#order does not matters
def comb_count(n,r):
fn = factorial(n)
print("fn: ", fn)
f... |
176ade5fba65ab3c40900ecfdb9a11cdaa643edc | wyuta/SampleCode | /sample.py | 2,399 | 3.5 | 4 | #!/usr/bin/env python3
# -*- coding: UTF-8 -*-
import requests
import re
from time import sleep
from bs4 import BeautifulSoup
"""
This source is sample programe to crawl and pickup words from Amazon.com.
If there are target words on the Amazon.com site, can pickup.
"""
SENTENCE = "Virtue signalling is society's ver... |
56bcaf69d035461ad2907b9cf35f1aa8f7b4292b | d-e-lu/Courses | /MATH 318/homework1.py | 1,914 | 3.5 | 4 | import numpy as np
import matplotlib.pyplot as plt
def generalized_birthday(n, days):
if n > days:
return True
days = np.random.choice(np.arange(1,days+1), size=n)
days_seen = set()
for day in days:
if day in days_seen:
return True
else:
days_seen.add(day... |
6fe0f6df63f9acb0ad4e906ec77e9a32ace41f30 | nolanbeihl/OOP-Worksheet | /product.py | 928 | 3.875 | 4 | class Product:
def __init__(self, product_cat, product_name, product_price):
self.product_name = product_name
self.product_type = product_cat
self.product_price = product_price
# product_cat = []
# product_name = []
# product_price = [int(i) for i in product_price]
... |
ec32c9acba6c0c44c45a2816f4477c7258a440cc | ejuarezg/NM4P | /Python/nm4p/linreg.py | 1,396 | 3.8125 | 4 | import numpy as np
def linreg(x,y,sigma):
"""Function to perform linear regression (fit a line)
Inputs
x Independent variable
y Dependent variable
sigma Estimated error in y
Outputs
a_fit Fit parameters; a(1) is intercept, a(2) is slope
sig_a ... |
5ebdba2ba73ab716db551f3c4e840740168fc012 | ejuarezg/NM4P | /Python/Raw Python/Ftdemo.py | 1,899 | 3.65625 | 4 | # ftdemo - Discrete Fourier transform demonstration program
# Set up configuration options and special features
import numpy as np
import matplotlib.pyplot as plt
#* Initialize the sine wave time series to be transformed.
N = int(input('Enter the number of points: '))
freq = float(input('Enter frequency of the sine ... |
3d29a1c44b447c46fea32bb1fce6da3f24d4576d | ejuarezg/NM4P | /Python/nm4p/dsmc.py | 8,633 | 3.703125 | 4 | import numpy as np
class sortList:
"""Class used for sorting particles into cells."""
def __init__(self, ncell_in, npart_in):
self.ncell = ncell_in
self.npart = npart_in
self.cell_n = np.zeros(ncell_in, dtype=int)
self.index = np.empty(ncell_in, dtype=int)
self.Xref = np... |
9b6ec7f52421503518ec981ff9b61145fbe03e6b | Ishani2627/PythonAssignment11 | /Class11.py | 555 | 4.15625 | 4 | #Que1
print("1. find valid email address")
import re
email = input("enter an email address : ")
if re.match('^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,})$', email):
print("valid email address")
else:
print("invalid email address")
print("\n")
#Que2
print("2. find valid indian phone numbe... |
e917650940d50fb617331afa108e4b029385fb17 | TriGirlTiff/disney_hangman_pseudocode | /loops_homework.py | 1,277 | 3.953125 | 4 | books = ["Dune", "Pride and Prejudice"]
# Welcome message
print "Brighticorn's Books"
print "-------------------"
print
use_library = True
while use_library:
print "You can add/ view/ check/ exit"
print "There are {} books in list.".format(len(books))
print "******************************"
com... |
676903f9386b4d0757bc10438ccfbe87d35a8bb2 | kannans89/Python_Machine_Learning | /Machine_Learning_algorithms_Python/first_model_build_python_da.py | 1,004 | 4.0625 | 4 | # Simple logistic regression model in Python
# Below are the steps involved:
# Import the required libraries
# Read the data
# Explore and clean the data
# Build logistic regression model
# Interpret the results
# Using already cleaned dataset (Iris) as an example and build a model on this dataset and will look at w... |
b86aa398a4996da0095b63e3742429d227daacd3 | CopperL2021/Python-Pre-Asssessment | /CSV WRITER.py | 899 | 3.6875 | 4 | import csv
#Need to stop words from repeating in csv
fname = input("Enter file name: ")
if len(fname) < 1:
fname = "input_data.txt"
fh = open(fname)
WordAndCounts = dict()
Newlist = list()
Totalstuff = list()
for line in fh:
word1 = line.strip()
words = word1.split()
for word in words:... |
bb41489836d2e854987979e975da767639ea8599 | pviafore/AdventOfCode2020 | /challenge6.py | 1,217 | 3.640625 | 4 | import itertools
from collections import Counter
from itertools import chain
from typing import Iterable
import common.input_data as input_data
def get_sum_of_any_yes_counts(questions: list[str]) -> int:
grouped_data = itertools.groupby(questions, lambda s: s != "")
return sum(get_any_yes_count(q) for has_da... |
8e11531642b2dfb6460f5240499eba2c1fd7e8d9 | YuvalSK/curexc | /cod.py | 1,872 | 4.3125 | 4 | import exrates
import datetime
import sys
def inputdate(date_text):
'''function that inputs a date, and verified if the date is in a vaild format, else return False
'''
try:
datetime.datetime.strptime(date_text, '%Y-%m-%d')
return True
except ValueError:
... |
1114c211c01850695d172cab82d0d544640e2f91 | AdarshRise/Python-Nil-to-Hill | /1. Nil/6. Function.py | 1,618 | 4.53125 | 5 | # Creating Function
# function are created using def
def fun():
print(" function got created ")
def fun2(x):
print("value of x is :",x)
# a bit complex use of function
def fun3(x):
x=x*x
print("value of x*x is ",x)
# above code will execute from here
x=2
fun()
fun2(x)
fun3(x)
print(x) # the valu... |
9d7bd3d747fec88ba7b0567eb89f913f9c5acd34 | michael-trigoboff/cs160.weeks | /week02/shape1.py | 1,270 | 3.703125 | 4 | import turtle as t
# colors coded as strings using names from the Turtle Graphics Colors page
dotColor = 'yellow green'
lineColor = 'firebrick3'
bgColor = 'pale goldenrod'
# window
windowTitle = 'CS 160 - Shape 1'
windowWidth = 600
windowHeight = 600
# turtle speed names
turtleSpeeds = ['fastest', 'fast', 'normal', ... |
252a608b09d3e2c385831d00e5979f2446e11125 | lashsl/Swarm-robot-monitoring | /testframe.py | 889 | 3.5625 | 4 | import cv2
# sample frame for test purposes.This will update during the run time.
frame = cv2.imread("../test.jpg")
# This function is used to store a frame selected by the user.
def testFrame(path):
global frame
print(" got the path : ", path)
cap = cv2.VideoCapture(path)
if not cap.isOpened():
... |
c340c12f6a6bcdf0759113cc823a8cf29150987c | DeniseYuki/python | /ProjetoDesempenhoAlunos.py | 2,320 | 3.65625 | 4 | import tkinter as tk
from tkinter import messagebox, simpledialog
import matplotlib.pyplot as plt
# Criar janela
root = tk.Tk()
root.title("Desempenho dos Alunos")
# Variáveis de entrada
quantidade_alunos = tk.IntVar()
serie = tk.StringVar()
ano = tk.StringVar()
quantidade_questoes = tk.IntVar()
acertos_por_questao =... |
a9917be09fdd70e78780145231214f1bc833ef95 | mpwesthuizen/eng57_python | /dictionairies/dictionairies.py | 1,292 | 4.46875 | 4 | # Dictionairies
# definitions
# a dictionary is a data structure, like a list, but organised with a key and not indexes
# They are organised with key: 'value' pairs
# for example 'zebra': "an african wild animal that looks like a horse but has stripes on its body."
# this means you can search data using keys, rather ... |
aaa9c5076952da3078e1f013bba6722f5880464a | mpwesthuizen/eng57_python | /exercises/dictionairies.py | 3,039 | 4.46875 | 4 | # # Dictonaries
#
# # definition and syntax
#
# # a dictionary is a data structure, like a list, but organized with keys and not indexes.
#
# # They are organized with 'key': 'value' pairs.
#
# # for example 'zebra': 'an African wild animal that looks like a horse but has stripes body'
#
# # This means you can search ... |
cc420b1cf1379755e59808cc17008a8898da2df6 | altarac/sci-tech-lab | /test_info.py | 42,712 | 3.53125 | 4 | class TestInfo:
def __init__(self, year):
self.year = year
self.t = [{
# --------- 1
'concepts': ['Gases','Gases','Gases','Energy changes in reactions','Energy changes in reactions','Reaction rates','Reaction rates','Chemical equilibrium','Chemical equilibrium','Chemical equilib... |
ee32eb3d13a4fc87c0c5020ad7ad3d785d2b8b87 | xiaosanmeng/Capacitated-Facility-Location-Problem | /src/greedy_algorithm.py | 2,289 | 3.625 | 4 | # coding: utf-8
import os
# 算法实现
def greedy_algorithm(N, M, CAPACITY, OPEN_COST, DEMAND, ASSIGNMENT_COST):
'''贪心策略2
params
--------
设备数(int),客户数(int),每个设备的容量(list),每个设备的开启成本(lsit),
每个客户的需求(list),每个客户对应每个设备的分配成本(list[list])
returns
--------
sum_cost(int): 总成本
facilities_isopen(list... |
99b4ef14b4af6a77853a618dfd4b4b494aa737c5 | yingchuanfu/Python | /com/python5/While.py | 525 | 4.09375 | 4 | # -*- coding: UTF-8 -*-
#条件 循环及其它语句
#while循环:与for循环不同,其循环的依据是条件判断
#while语法:当condition为True,则执行Action,否则退出
#while Condition:
# Action
print("实例1:求一组数据的平均值==================")
num_set = [98, 94, 82, 67, 58, 90, 86]
sumOfNum = 0
index = 0
while index < len(num_set):
sumOfNum += num_set[index]
index += 1
... |
a0bc1eb1a6223eaa66eaeb067a6f3f6c31460efc | yingchuanfu/Python | /com/python10/File.py | 2,834 | 3.8125 | 4 | # -*- coding: UTF-8 -*-
#open(file, model, buffering)用于打开文件并返回一个文件对象,open函数的参数中,
#文件名file是强制参数,模式(model)和缓冲(buffering)都是可选的
print("一:打开文件")
#打开文件读取其中全部内容
f = open("F:/python.txt")
print(f.read())
print("二:文件模式")
#二.文件模式参数:r,读模式; a,追加模式; b二进制模式; +,读写模式;w,写入模式
#例1.打开文件,写入文本
f = open("F:/python.txt", 'w')
f.write("learn... |
89f05b07503462748e7cf512d7132e6dcd901390 | yingchuanfu/Python | /com/python7/FunctionClass.py | 856 | 4.28125 | 4 | # -*- coding: UTF-8 -*-
#抽象函数:类(在Python中,类具有封装,继承,多态,但是没有重载)
#self参数
class Person:
#定义类的数据成员:姓名,年龄
name = ''
age = 0
#定义构造函数,用于创建一个类实例,也就是类的具体对象
#通过参数传递,可以赋予对象初始状态
def __init__(self, name, age):
self.name = name
self.age = age
#定义一个函数:打印类实例的基本信息
def printPersionInfo(self... |
0e2c0880fe72d8565d2c11f58ac2dfe344ffd43d | TanvirKaur17/BFS-1 | /BinaryTreeRightSideView.py | 936 | 3.625 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Oct 17 10:00:49 2019
@author: tanvirkaur
"""
import collections
class Solution(object):
def rightSideView(self, root):
"""
:type root: TreeNode
:rtype: List[int]
BFS approach
time complexity = O(V+E)
... |
6c1a77d74b76fe19a4196de8fb90da66edd51974 | ROSAF2/dev4-assignment-test | /problem1/problem1.py | 948 | 3.703125 | 4 | # Joining path in order to import modules from other exercises/problems
import os, sys
sys.path.append(os.path.join(os.path.dirname(os.path.abspath(__file__)), '..'))
# Importing the LinkedList class from problem5
from problem5.problem5 import LinkedList
class Stack:
def __init__(self):
self.stack = Link... |
9ac31f1a937fd537b96a1791479b8b8923a2cc3b | dln-dev/HomeAssistant | /phrases.py | 769 | 3.5 | 4 | # dict of specific phrases
phrases = {
"music_phrases" : ["play", "jam some"],
"time_phrases" : ["time", "clock"],
"close_phrases" : ["kill", "close", "stop"],
"wiki_phrases" : ["wikipedia", "tell me about", "need info on"],
"info_phrases" : ["who is", "who the hell is", "who ... |
1f6282aac444d278f2df2900dfa6227578641939 | dislersd/Intro-Python-II | /src/player.py | 1,160 | 3.65625 | 4 | # Write a class to hold player information, e.g. what room they are in
# currently.
class Player:
def __init__(self, name, room):
self.name = name
self.room = room
self.items = []
def travel(self, direction):
nextRoom = self.room.travel(direction)
if nextRoom is not No... |
b5d4fff49ee51ac36e8b8d9e91d81e6eb7d1c0ed | Saksham018/Python | /Ass-6.py | 686 | 3.84375 | 4 | #Qusetion 1
def sphere(num):
return 4*3.14*num*num
num=int(input("Enter the radius: "))
print(sphere(num))
#Question 2
def perfect(num):
sum=0
for i in range(1,num-1):
if(num%i==0):
sum=sum+i
if(sum==num):
return True
return False
print("List of Perfect numbers is:")
fo... |
8ea3c9ae21e5005994db79fb3b85981a5a3a8aaf | nabarunaguha/sentiment-review-analysis | /Artificial_Neural_Network/SL_NeuralNetwork_AmazonReview.py | 7,564 | 3.84375 | 4 |
#### Assignment2
#### This script includes the implementation of the Neural Networks for the Amazon Sentiment Analysis Dataset.
#### It takes the following libararies - NLTK, pandas, numpy, string, matplotlib, scipy, sklearn.
### @Author: Chaitanya Sri Krishna Lolla, Student ID: 800960353
### Libraries.
import pandas... |
1a97d3b6bf18d7f76b271f0afcd9c733b0c4d326 | romilly/anastasia-bot | /src/controller.py | 1,720 | 3.875 | 4 | """
Control Anastasia's motors from a second micro:bit.
This library detects how you want Anastasia to move based on how you tilt the micro:bit.
It uses the micro:bit radio to send your commands to the robot.
See `motoring.py` for the code that runs on Anastasia.
"""
from microbit import *
import radio
radio.on()
# T... |
739a0d83131b224c957c84e05bf4cc7d32b015d7 | tamim36/Problem-Solving | /Hackerrank-Python/FindingTheAverage.py | 260 | 3.953125 | 4 | numOfStudents = int(input())
myDict = {}
for _ in range(numOfStudents):
name, a, b, c = input().split()
avgMarks = float(float(a)+float(b)+float(c))/3
myDict[name] = avgMarks
student = str(input())
print('%.2f' % myDict[student])
|
1fdefbc30204165a5016d9b3179772fdba3eb2d9 | mingddo/sunday_algorithm | /8일차_tree/범대장/SWEA_5177_이진힙_박승범.py | 685 | 3.53125 | 4 | import sys
sys.stdin = open("input.txt", "r")
def heap_push(n):
global heap_cnt
heap_cnt += 1
heap[heap_cnt] = n
child = heap_cnt
parent = child // 2
while parent and heap[parent] >= heap[child]:
heap[parent], heap[child] = heap[child], heap[parent]
child = parent
parent... |
cc3774a43b724020d8b7e0d1903e7421b2388bb6 | loloschleicher/Python-AnalysisNumeric | /Guide5/ExcercisesMatrix.py | 1,138 | 3.640625 | 4 | import numpy as np
#declaracion de matrices
a = np.matrix([[4, 7], [1, 2], [5, 6]])
b = np.matrix([[4, 3, 7], [1, 2, 7], [1, 0, 4]])
c = np.matrix([[3], [6], [1]])
d = np.matrix([[9, 4, 3, -6], [2, -1, 7, 5]])
e = np.matrix([[1, 5, 8], [7, 2, 3], [4, 0, 6]])
f = np.matrix([[3, 0, 1], [1, 7, 3]])
g = np.matrix([[7, 6, ... |
c0901965ca658c1eb3a7c93624513527f4559564 | Mayank-Chandra/LinkedList | /LinkedLIst.py | 1,135 | 4.28125 | 4 | class Node:
def __init__(self,data):
self.data=data
self.next=None
class LinkedList:
def __init__(self):
self.head=None
def push(self,new_data):
new_node=Node(new_data)
new_node.next=self.head
self.head=new_node
def insertAfter(self,prev_node,new_data):
... |
31ef03ebd585bbe5ce06c97c4f94391f183a7007 | shi0524/notebook | /algorithm/sort_algorithm/Code_04_mergeSort.py | 1,426 | 3.640625 | 4 |
#! --*-- coding: utf-8 --*--
"""
归并排序
"""
from tools import time_it, random_list
@time_it
def merge_sort01(lst):
""" 递归版本
"""
if not lst or len(lst) == 1:
return
process(lst, 0, len(lst)-1);
def process(lst, L, R):
if (L == R):
return
mid = (L + R) / 2
# mid = L + ((R - L) >> 1) # python int 永不越界
... |
a452c7eabc98b93c0e9a42690daa3448403e201d | shi0524/notebook | /LeetCode/Code_1006_Clumsy.py | 2,771 | 3.75 | 4 | #! --*-- coding: utf-8 --*--
"""
1006. 笨阶乘
通常,正整数 n 的阶乘是所有小于或等于 n 的正整数的乘积。例如,factorial(10) = 10 * 9 * 8 * 7 * 6 * 5 * 4 * 3 * 2 * 1。
相反,我们设计了一个笨阶乘
clumsy:在整数的递减序列中,我们以一个固定顺序的操作符序列来依次替换原有的乘法操作符:乘法(*),除法(/),加法(+)和减法(-)。
例如,clumsy(10) = 10 * 9 / 8 + 7 - 6 * 5 / 4 + 3 - 2 * 1。
然而,这些运算仍然使用通常的算术运算顺序:我们在任何加、减步骤之前执行所有的乘法和除法... |
fc78e85199164a95411cfb14411be9128603366e | JeweL645/restart | /slicing.py | 473 | 4.125 | 4 |
fav_food = ["pizza","pasta","bbq_rice","nachos","milk_shakes","ice_cream"]
#print(fav_food)
for food in fav_food:
print(food.title()+"!!")
print("First three items in the list are:\n")
for food in fav_food[:3]:
print(food.title())
print("The three item in the middle of the list are :")
for foo... |
f5d8d4fa34f1ec4f64fd5ed658ec133e5dbd65fe | JeweL645/restart | /checking.py | 546 | 3.9375 | 4 | print("Let's play an interesting game")
i = 1
while i != 0 :
x = int(input('Take a number in your mind: '))
# print(x)
x1 = int(input('Take the same number from Aladin: '))
# print(x1)
x2 = int(input('I am giving you: '))
x3 = x2 // 2
# print(x2)
half = (x + x1 + x2) // 2
... |
50f4d793969fcbaa38facccc87bf512c2e5c2eb1 | JeweL645/restart | /ki korbo.py | 245 | 4.09375 | 4 |
for value in range(1,6):
print(value)
numbers = list(range(1,6))
print(numbers)
even_numbers = list(range(0,101,2))
print(type(even_numbers))
print(even_numbers)
odd_numbers = list(range(1,100,2))
print(odd_numbers)
|
094cba8f1224a5f7a03a12e3d24121a0a8943985 | JeweL645/restart | /information_about_a_person.py | 225 | 3.578125 | 4 |
person_1 = {'first_name': 'elias', 'last_name': 'islam', 'age': 25, 'city':'dhaka'}
print(person_1['first_name'].title())
print(person_1['last_name'].title())
print(person_1['age'])
print(person_1['city'].title())
|
b960df88b7fd16e734ddebfa51b9b390ff3fcd2a | sambavsphere/python_training | /boolean+expressions.py | 7,521 | 3.71875 | 4 |
# coding: utf-8
# In[1]:
a=10
b=20
print a+b
# In[2]:
print a>b
# In[3]:
print a<b
# In[4]:
print a<=b
# In[5]:
print a>=b
# In[6]:
print a==b
# In[7]:
print a is b
# In[8]:
print "sub" in "actual substring"
# In[9]:
a=10
b=a
# In[10]:
a==b
# In[11]:
a is b
# In[12]:
a=10
b=10
# In... |
8e2780eebe6db86f3354ba3c58970cc58446789d | yfeizhang/MNIST_Neural_Network | /Logistic_Regression.py | 2,023 | 3.859375 | 4 | import numpy as np
'''
Simply train and test the logistic regression which would be one layer
in the neural network model.
'''
# load the data
def data_loader(file):
a = np.genfromtxt(file, delimiter=',', skip_header=0)
x = a[:, 1:] / 255.0
y = a[:, 0]
return (x, y)
x_train, y_train = data_loader('m... |
14747b8deb82a5e32d3bbae8fe1d5db55dd0398a | SicklySilverMoon/NumberCruncher | /formulas/incorrectConstant.py | 893 | 3.640625 | 4 | from decimal import Decimal
def incorrect(): # This constant is caused doing the steps for pi in a wrong order which results in a very different number
incorrect_constant = Decimal(0)
term = Decimal(1)
current_iteration = Decimal(0)
C = Decimal(426880)*Decimal(10005).sqrt()
M = Decimal(1) # nam... |
76d34d3424c0ce7fb27b39e855a6b8bd8159b11e | kiwiapple87/codecombat | /CloudripMountain/Power_points.py | 1,462 | 3.796875 | 4 | # You need to find and kill 3 skeletons.
# Skeletons and useful items can be summoned in the points of Power.
# You should move to the point and say the spell "VENI".
# To find the required points use the map from the wizard.
# 0 is a wrong point. Positive numbers are skeletons or useful items.
spell = "VENI"
# The ma... |
70429c61c26e4b1411f157a22a1a87b10eeba9a6 | kiwiapple87/codecombat | /CloudripMountain/cannon landing force.py | 940 | 3.8125 | 4 | # We should send some soldiers to defend the mountain village.
# Also we need clear out old fire traps.
# For both of those goals we'll use the artillery!
# The artillery can launch soldiers and anti-trap shells over the mountains.
# The scout prepared a map of the landing zone.
# The map is 2 dimensional array, where... |
125ab038dcff3ee21179001ee4952db152050fef | cczeus/project-euler | /problems/problem020.py | 160 | 3.5625 | 4 | def main():
num = 1
for i in range(100):
num *= (i + 1)
num = str(num)
sum = 0
for c in num:
sum += int(c)
return sum |
e985482425532871b5b1f86bd98f4029eb768a0c | cczeus/project-euler | /problems/problem044.py | 514 | 3.609375 | 4 | def isPentagonal(n):
num = ((24 * float(n) + 1) ** .5 + 1) / 6
return num == int(num)
def getPentagonal(n):
return n * (3 * n - 1) / 2
def main():
x = 2
x1 = getPentagonal(x)
y = 1
y1 = getPentagonal(y)
while not isPentagonal(x1 + y1) or not isPentagonal(x1 - y1):
if y == 1:
... |
466bbd162c8b21449f723805baac56735c55b675 | isilanes/myeuler | /p128/p128.py | 1,929 | 3.953125 | 4 | def f0(nth):
print("--- f0 ---")
def isprime(num):
'''Returns True if num is prime, False otherwise.'''
if num == 1:
return False
if num in [2,3,5,7]:
return True
if num % 10 in [0,2,4,5,6,8]:
return False
i = 3
while i*i <... |
ef098d4640dfab0d617e4166f4499413c5ed2df9 | isilanes/myeuler | /p125/p125.py | 1,064 | 3.75 | 4 | #--------------------------------------------------------------------#
def f0():
print("--- f0 ---")
def is_palindromic(n):
s = str(n)
return s == s[::-1]
# List of all squares up to 10**8:
sq = [ x*x for x in range(1,10**4+1) ]
# Get N = 2, 3... consecutive squares, add them up,... |
4515aa73c189c8c5c545aa27addc3f4b4f214034 | isilanes/myeuler | /p047/p047.py | 1,453 | 3.75 | 4 | def f1():
i = 13
while True:
delta = 1
if factor_amount(i) == 4:
delta += 1
if factor_amount(i+1) == 4:
delta += 1
if factor_amount(i+2) == 4:
delta += 1
if factor_amount(i+3) == 4:
... |
00eb56701d9275209d82290c43cc195fa25c75b9 | isilanes/myeuler | /p130/p130.py | 1,402 | 3.5625 | 4 | import timeit
#------------------------------------------------------------------------------#
def f0(ncomp):
print("--- f0 ---")
def A(n):
'''Returns A(n) for n.'''
k = 1
rem = 1
while True:
rem = (rem + pow(10, k, n)) % n
if not rem:
... |
36cbad1385e0bd3d42ada61fa0c59101706e4069 | isilanes/myeuler | /p037/p037.py | 2,595 | 3.6875 | 4 | def f1():
# Sieve to find all primes up to max. If not enough, increase max.
max = 1000000
composites = {}
primes = [2]
for mult in range(3,max,2):
if not mult in composites:
primes.append(mult)
for i in range(mult*mult, max, 2*mult):
composites[i] = T... |
398bff61b69e793b4072d376490b15872e4a1176 | isilanes/myeuler | /p084/p084.py | 2,918 | 3.75 | 4 | #--------------------------------------------------------------------#
def f0():
print("--- f0 ---")
import random
class Square:
def __init__(self, goto):
# Possible outcomes of picking a card in a square. goto
# is an array of outcomes, where each outcome is the index
... |
10c4abace4bfa2c456b065e0ff978dea75ecf5a7 | isilanes/myeuler | /p069/p069.py | 5,344 | 3.859375 | 4 | #--------------------------------------------------------------------#
def f0():
print("--- f0 ---")
def get_primes(max):
# Sieve to find all primes up to max:
composites = {}
primes = [2]
for mult in range(3,max,2):
if not mult in composites:
# Log ... |
9ce7b9d3f654a42360f52815788dadbf0960ada1 | isilanes/myeuler | /p052/p052.py | 1,012 | 3.515625 | 4 | #--------------------------------------------------------------------#
def f1():
print("--- f1 ---")
i = 1
while True:
idigits = f1_1(i)
valid = True
for mult in [2,3,4,5,6]:
imult = i * mult
imultdigits = f1_1(imult)
if imultdigits != idigits:
... |
64e5b665d675ec4515faf7e151a89c0b1473925b | isilanes/myeuler | /p060/p060.py | 7,821 | 3.6875 | 4 | #--------------------------------------------------------------------#
def f1(nmax):
#
# TOO SLOW!
#
print("--- f1 ---")
class Kosher(object):
def __init__(self, primes):
self.primes = primes
def are(self,a,b):
'''
Returns True if prime... |
c171809868a3e6702ab3ee0201d0c48a5000bf93 | isilanes/myeuler | /p387/p387.py | 3,562 | 3.765625 | 4 | """
A Harshad or Niven number is a number that is divisible by the sum of its digits.
201 is a Harshad number because it is divisible by 3 (the sum of its digits.)
When we truncate the last digit from 201, we get 20, which is a Harshad number.
When we truncate the last digit from 20, we get 2, which is also a Harsha... |
d801b31ce1ade188d4f801138f99ea264fbdb9ed | nicholasz2510/zipf-from-text | /zipf.py | 781 | 4.0625 | 4 | from tkinter import filedialog
from tkinter import *
from collections import Counter
import string
import matplotlib.pyplot as plt
def word_count(string_to_count):
text = string_to_count
for char in string.punctuation:
text = text.replace(char, ' ')
text = text.lower()
word_list = text.split... |
e6b74712a20da8d7d6a4952f0a666e4cccf3a4ea | palosaari/artificial_intelligence | /Crobot.py | 13,809 | 3.703125 | 4 | """
Artificial Intelligence 521495A Programming Exercise. University of Oulu.
Antti Palosaari <crope@iki.fi>
This Reversi/Othello algorithm uses following techniques:
* multitasking
* Minimax with Alpha-beta pruning
* Many different evaluation methods
* iterative deepening search tree
"""
import reversi.ReversiAlgorit... |
722bd9c4fd947ebaabc4a6140bd8b81f81187dbd | simonneutert/python-binary-tree-excercise | /binary-tree/classes/binary_tree.py | 974 | 3.578125 | 4 | class BinaryTree():
def __init__(self, root_value):
self.left_branch = None
self.right_branch = None
self.root_value = root_value
def setNodeValue(self, value):
self.root_value = value
def getNodeValue(self):
return self.root_value
def getRightChild(self):
... |
934fe26fc182aa85ac99e34a11451019e74d339d | SimonCWatts/CS50x | /mario easy.py | 204 | 4.0625 | 4 | h = -1
while h < 1 or h > 8:
height = input("Height: ")
try:
h = int(height)
except ValueError:
pass
for step in range(h):
print(" " * (h - step - 1) + "#" * (step + 1))
|
c9e76e7b1310e13b58489bae737196028c5b63c2 | Jinhui-L/Leecode_summary | /LinkedList.py | 10,071 | 4.0625 | 4 | # -*- coding: utf-8 -*-
"""
-------------------------------------------------
File Name: LinkedList
Description :
Author : amilyxy
date: 2019/9/15
-------------------------------------------------
"""
'''
63. Reverse Linked List: 反转链表
describe: 反转一个单链表。
示例:
... |
046d5e86e46f214976780e5b3509b7eaebb43647 | Bodhinaut/python_codewars | /solving_num.py | 207 | 3.578125 | 4 | value = []
items = [x for x in input("Please input 4 digit binary numbers seperated by commas: ").split(',')]
for p in items:
intp = int(p, 2)
if not intp % 5:
value.append(p)
print (','.join(value))
|
29e519ff97374a07feab16d3334caeb754f35fc1 | Bodhinaut/python_codewars | /permutations/file_io_permutations.py | 367 | 3.6875 | 4 | filename = 'sample_input.txt'
# with open(filename) as file_object:
# contents = file_object.read()
# print(contents.rstrip() )
# with open(filename) as file_object:
# for line in file_object:
# print(line.rstrip() )
with open(filename) as file_object:
lines = file_object.readlines()
test = []
for line in li... |
d7e9b71c54e64526ae127c3b76519aca5082f745 | Bodhinaut/python_codewars | /pony_express.py | 229 | 3.578125 | 4 | def riders(stations):
riders, travelled = 1, 0
for miles in stations:
if travelled + miles > 100:
riders += 1
travelled = miles
else:
travelled += miles
return(riders)
print(riders([36, 8, 32, 45]) ) # test case |
d203cbbfc9fc03000483a54282da0b63e6aeea5e | fraglord94/hackerrank-solutions | /caesar_cipher.py | 340 | 3.5625 | 4 | #!/bin/python3
import sys
n = int(input().strip())
s = input().strip()
k = int(input().strip())
for hour in s:
c = ord(hour)
#upper case
if(c>=65 and c<=90):
print(chr(65 + (c+k-65)%26),end='')
elif(c>=97and c<=122):
print(chr(97 + (c+k-97)%26),end='')
else:
... |
e0b36a0f63d52996ac5fb16466f421e3f021f2da | shreyansh-sh1/twoc-python-assingment3 | /question1.py | 118 | 4.03125 | 4 | print("Enter string to be reversed: ")
x=input()
y=x[::-1]
print("Reversed string: ")
print(y)
# Code by shreyansh sharma |
3385fa3de715a2ed711235a006af9c17067af7ca | marcyves/Python-Pratique | /jeux/ferme/ferme02.py | 2,583 | 3.921875 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Petit jeu de simulation de ferme
Garanti sans OGM
(c) Marc Augier 2016
m.augier@me.com
Règles du jeu:
--------------
Un paysan possède au départ :
- un terrain de 100 ha.
- un stock de 1000 tonnes de blé.
Tous les ans, il plante du blé, et son terrain lui produit ... |
a684026388d719fa7fc13fbf4ee33678e4be06ab | dylanvanh/Polygon-area-calculator | /shape_calculator.py | 1,768 | 3.84375 | 4 | import math
class Rectangle:
def __init__(self,width,height):
self.width = width
self.height = height
def set_width(self,width):
self.width = width
def set_height(self,height):
self.height = height
def get_area(self):
return self.width*self.height
def... |
9520f47de86deb7248418f921ebe666b27be4a61 | jcjc2019/edX-MIT6.00.1x-IntroToComputerScience-ProgrammingUsingPython | /Final/problem4.py | 954 | 3.921875 | 4 | #MIT final exam
#Problem 4- part 1
#This function returns a list of all possible sublists in L of length n without skipping elements in L.
def getSublists(L, n):
newlist = []
for i in range (len(L)-n+1):
newlist.append(L[i:i+n])
return newlist
#problem 4 part 2
#Write a function called... |
461085bffe23b8dd9873de328d4a859beb12e3ab | jcjc2019/edX-MIT6.00.1x-IntroToComputerScience-ProgrammingUsingPython | /Program2-ndigits.py | 405 | 4.125 | 4 | # below is the function to count the number of digits in a number
def ndigits(x):
# when x is more than 0
if x > 0:
#change type to string, count the length of the string
return len(str(int(x)))
# when x is less than 0
elif x < 0:
#get the absolute value, change type to string, a... |
125b99fb5315fd11df13449e0fa4d6b12dbdda5d | Dante-Gaius/CP1404_Practicals | /cp1404practicals/Prac_02/string_formatting.py | 178 | 4.28125 | 4 | # TODO: Using a for loop with the range function and string formatting,
# produce the following output:
# 0
# 50
# 100
for i in range(0, 101, 50):
print("{:3}".format(i))
|
3439f7f78788d82f77f80abc3fb6f21c05e2ed29 | dashmoment/leet | /pow_x_n.py | 611 | 3.875 | 4 | """
Implement pow(x, n).
"""
"""
#Recursive Method
class Solution:
def myPow(self, x, n):
if n == 0: return 1
if n < 0:
n = -n
x = 1.0/x
if n%2 == 0:
return self.myPow(x, n/2)*self.myPow(x, n/2)
else:
return self.myPow(x, n/... |
8aaf314ca06198603339c8d1c54c81218dceb8a7 | dashmoment/leet | /word_break.py | 1,125 | 4.03125 | 4 | """
Given a non-empty string s and a dictionary wordDict containing a list of non-empty words, determine if s can be segmented into a space-separated sequence of one or more dictionary words. You may assume the dictionary does not contain duplicate words.
For example, given
s = "leetcode",
dict = ["leet", "code"].
Re... |
269db482b7c081dbd0dfa140cdb9f1a9a84848b1 | dashmoment/leet | /sort_color.py | 753 | 3.75 | 4 | class Solution(object):
def sortColors(self, nums):
"""
:type nums: List[int]
:rtype: void Do not return anything, modify nums in-place instead.
"""
color_dict = {0:[],1:[],2:[]}
for i in range(len(nums)):
color_dict[nums[i]].ap... |
bbfcf6773236c4a413044ad1b42bae8a4f88afea | vedantsharma2001/Daily-Python-Programming | /1.Write a Python Program to Calculate Average Of Numbers Given in the list.py | 98 | 3.796875 | 4 | a=list(map(int,input("Enter the numbers in the list:").split(",")))
avg=sum(a)/len(a)
print(avg) |
9a645db29aab1b16041d31c46bd9c1b0ec0a3f05 | vedantsharma2001/Daily-Python-Programming | /Set B/3. Write a Python program to remove the characters which have odd index values of a given string.py | 260 | 3.9375 | 4 | main_string=input("Enter the string:")
final_string=""
for i in range(len(main_string)):
if i % 2 == 0:
final_string=final_string+main_string[i]
print(final_string)
OR
a=input("Enter the string:")
b=a[1::2]
print(b) |
cd50f0cdd0c36f5156aa1002761da055c73f7178 | alxndrsemenov/alxndrsemenov | /Lab2/task4.py | 1,043 | 4.0625 | 4 | # Пользователь вводит строку из нескольких слов, разделённых пробелами. Вывести каждое слово с новой строки.
# Строки необходимо пронумеровать. Если в слово длинное, выводить только первые 10 букв в слове.
#запрашиваем ввод строки
string=str(input("Введите строку: "))
#создаем список из строки используя в качестве ... |
a9aa82ed8c666d76e7f9d34b9eea69e036b691f3 | SouzaCadu/guppe | /Secao_04_Lista_Ex_53e/ex_25.py | 219 | 3.578125 | 4 | """
Conversor de acres em metros quadrados
"""
print(f"Conversor de acres em metros quadrados. \n"
f"Insira o valor em acres:")
a = float(input())
print(f"{a} acres equivalem a {a * 4048.58} metros quadrados.") |
a5028a588635c1b58138c45e0a0a445fa9c68b09 | SouzaCadu/guppe | /Secao_06_Lista_Ex_62e/ex_58.py | 795 | 3.84375 | 4 | """
faça um programa que some os números primos existentes
em um intervalo dado por A e B, informados pelo usuário
"""
print("Digite um intervalo para saber a soma dos números primos existem nele.")
int1 = int(input("Digite o primeiro número inteiro: "))
if int1 == 1:
print("Valor inválido.")
int1 = int(input(... |
04623021d338f1b390d12cb951a37b86a828ab30 | SouzaCadu/guppe | /Secao_12_Modulos/12_80_Oq_sao_modulos_Random.py | 1,413 | 4.34375 | 4 | """
Módulos e módulo Random
Em Python módulos são outros arquivos Python com funções. Devem ser instalados e/ou importados.
O módulo Random possui diversas funções para gerar números pseudo aleatórios.
Existem duas formas de utilizar um módulo:
Importando todo o módulo todas as funções, atributos, classes e proprie... |
4e4b8c08dc19a4ebac62671df4c1cdb6e44a7ab0 | SouzaCadu/guppe | /Secao_07_Lista_Ex_25e/ex_21.py | 1,722 | 3.75 | 4 | """
faça um programa que leia duas matrizes 2 x 2
com valores reais e ofereça as seguintes opções:
- somar as duas matrizes
- subtrair a primeira da segunda
- adicionar uma constante às duas matrizes
- imprimir as matrizes
"""
soma = 0
matriz_soma = []
sub = 0
matriz_sub = []
matriz3 = []
valores = ('insira o valor',... |
a9bf4a010a607e31ea77c3d391b0a118e2a70a83 | SouzaCadu/guppe | /Secao_07_Lista_Ex_39e/ex_15.py | 509 | 3.875 | 4 | """
faça um programa que leia um vetor de 20 posições
e elimine os valores repetidos
"""
print("Insira 20 números, os valores repetidos serão eliminados ao final.")
v1 = []
count = 1
while count <= 20:
valor = int(input(f"Digite {count} de 20 números: "))
v1.append(valor)
count += 1
if count > 20:
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.