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 |
|---|---|---|---|---|---|---|
1d8e332c138f58671e4d84d1fd1bd138e1be260c | adityaramkumar/LeetCode | /589.py | 428 | 3.59375 | 4 | # Runtime: 124 ms, faster than 56.96% of Python online submissions for N-ary Tree Preorder Traversal.
# Difficulty: Easy
class Solution(object):
def preorder(self, root):
"""
:type root: Node
:rtype: List[int]
"""
if not root:
return []
p_list = [root.val... |
3146090c54d237ba2d17d20780f447a5610a722d | adityaramkumar/LeetCode | /58.py | 298 | 3.71875 | 4 | # Runtime: 20 ms, faster than 99.23% of Python online submissions for Length of Last Word.
# Difficulty: Easy
class Solution(object):
def lengthOfLastWord(self, s):
"""
:type s: str
:rtype: int
"""
return len(s.split()[-1]) if len(s.split()) > 0 else 0
|
fcb2d0b0cced1ec811c4f97be08ba07bc47453d4 | yuvraj1987/Acadgild_Assignment_2- | /.gitignore/Assignment2_list_Comphersion_nested_list.py | 984 | 3.703125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Tue Jun 5 16:27:42 2018
@author: jkdadhich
"""
Text = "acadgild"
Result = [x.upper() for x in Text] # Using Uppercase and iterate over character
Variable = "xyz"
# Mulitpy iteration with range
Result_1 = [ x*k for x in Variable for k in range(1,5)]
# mulitpl... |
4a17f972b166a9366ef4445409b707659fb8843f | abhineetmishra64/Algorithm | /python/sumevenfibo.py | 275 | 3.578125 | 4 | def evenfibo(limit):
if(limit<2):
return 0
ef1=0
ef2=2
sm=ef1+ef2
while(ef2<=limit):
ef3=4*ef2+ef1
if(ef3>limit):
break
ef1=ef2
ef2=ef3
sm=sm+ef2
return sm
limit=9
print(evenfibo(limit))
|
dc3416bc1ecc7f1546818662d475aa2fd7245194 | abhineetmishra64/Algorithm | /python/exam.py | 359 | 3.734375 | 4 | n=int(input("Enter no. of student: "))
std={}
for i in range(n):
info={}
info['name']=input("Enter name: ")
info['age']=int(input("Enter age: "))
info['marks']=int(input("Enter marks: "))
std[i]=info
print(std)
marks=[]
for i in range(n):
marks.append(std[i]['marks'])
print(sum(marks)/n)
ind=m... |
102b3bd3f57932ce61c8eb3cacafb406d15929cd | to-besomeone/algorithm | /181009 - 2562.py | 197 | 3.734375 | 4 | arr = []
for i in range(9):
arr.append(int(input()))
maxValue = arr[0]
j = 0
for i in range(1, 9):
if arr[i] > maxValue :
maxValue = arr[i]
j = i
print(maxValue)
print(j+1) |
91c8697f3842b6adaf0481038f666f8c510d63a6 | to-besomeone/algorithm | /181111-2750_1.py | 314 | 3.59375 | 4 | N = int(input())
mat = [int(input()) for _ in range(N)]
for i in range(N-1, -1, -1): # for i in range(N-1):
for j in range(i): # for j in range(N-1):
if mat[j] > mat[j+1]:
tmp = mat[j]
mat[j] = mat[j+1]
mat[j+1] = tmp
for i in range(N):
print(mat[i]) |
5e6676fe294341190b98333567d7242eebb063a8 | pmillerschmidt/lockers | /https/docs.google.com/document/d/1puiqxz9kzwaWOi65MAb_kQtessXq86-zM4ITiX1Pd3k/lockers.py | 958 | 3.921875 | 4 | import random
from time import sleep
right = 0
i = 0
print("How many lockers and students are there?")
total_lockers = int(raw_input())
print("Cool! There are %d lockers and students" % total_lockers)
print("--------------")
sleep(1)
print("How many time do you want the program to run")
input = int(raw_input())
runs ... |
01c994d42749b26d6a32de3a6682a60f38ccc4eb | quantabox/hackerrank | /10-days-of-statistics/poisson_distribution_ii.py | 810 | 3.796875 | 4 | #!/usr/bin/env python
# Approach I
def fact(y):
if y <= 1:
return 1
return y*(fact(y-1))
poisson_random_variables = [float(x) for x in input().split()]
e = 2.71828
l_A = poisson_random_variables[0] # Machine A repair poisson random variable mean variance
l_B = poisson_random_variables[1] # Machine B r... |
2d425e371bd59c5a0ad3e6807a239378c5e44a12 | jiaoqiyuan/Tests | /Python/python-practice/chapter5-if/toppints.py | 1,428 | 4.25 | 4 | requested_topping = 'mushrooms'
if requested_topping != 'anchovies':
print("Hold the anchovies!")
answer = 17
if answer != 42:
print("That is not the correct answer. Please try again!")
requested_toppings = ['mushrooms', 'extra cheese']
if 'mushrooms' in requested_toppings:
print("Adding mushrooms.")
if 'pepperon... |
45246247635523f9d8a41c9402effce330e9c013 | jiaoqiyuan/Tests | /Python/python-practice/chapter4-uselist/animals.py | 180 | 3.984375 | 4 | animals = ['pig', 'chiken', 'tigger', 'bird', 'bull']
for animal in animals:
print("A dog would make a great pet " + animal)
print("Any of these animals would make a great pet!") |
1e3897dc264c6e7927e677227e6389f05dc7e062 | jiaoqiyuan/Tests | /Python/python-practice/chapter7-while/trival.py | 306 | 4.09375 | 4 | places = []
flag = True
while flag:
place = input("\nIf you could visit some places in the world, where would you go?\nEnter 'quit' to exit!")
if place == 'quit':
flag = False
else:
places.append(place)
print("\nYour places are: ")
for place in places:
print("\n" + place)
|
4be74b37275fdd68dac3287633b5001a4c6b357b | jiaoqiyuan/Tests | /Python/python-practice/chapter4-uselist/pisas.py | 458 | 4.0625 | 4 | pizzas = ['New-York-Style', 'Chicago-Style', 'California-Style', 'Pan-Pizza']
for pizza in pizzas:
print("I like pepperoni pizza " + pizza)
print("I like pizza very much, I really love pizza!")
friend_pizzas = pizzas[:]
pizzas.append('Take and Bake Style')
friend_pizzas.append('Stufffed')
print("My favorite pizza a... |
59d7d9ba327ce1f559135bf000f5acb986578733 | Harishjm/Basic_Python | /Beark_Continue.py | 116 | 3.96875 | 4 | for i in range(0,9):
if(i%2==0):
continue ###break ###this is for printing odd numbersss
print(i) |
fef2bea17ffb60458cf22821fc4503494914b2ea | esselstyn/Homework_1 | /prime.Factor.py | 690 | 3.671875 | 4 | #!/usr/bin/env python
max = int(raw_input('Select the maximum value: '))
max = max + 1
#Make a list of all prime numbers between 1 and max
primes = []
for i in range(1, max):
x = 0
if i < 4:
primes.append(i)
else:
for j in range(2, i-1):
if i % j == 0:
x = 1
if x == 0:
primes.append(i)
##reduce th... |
4b65bba88943870e3121c6009e78563b8109ae5a | nagase2/nagaden | /module/CalcUtil.py | 960 | 3.546875 | 4 |
import datetime
def checkIfPastSpecificTimeInSec(lastTime, currentTime ,pastTimeInSec):
"""前に通知した時間よりも5分(5*60)以上たっているか判定する"""
#lastNotifiedTime =datetime.datetime(2017, 12, 28, 22, 5, 6, 620836)
#currentTime=datetime.datetime.now()
diff = currentTime-lastTime
print(diff.seconds)
if diff... |
48fc03d448664155dcc7edad585aea16e730618b | R0bertWell/estrutura-de-dados | /aula_01/meu_max.py | 663 | 3.78125 | 4 | from math import inf
from time import time
def meu_max(iteravel):
"""
Análise do algorítmo
Tempo de execução, algoritmo O(n)
Em memória O(1)
:param iteravel:
:return:
"""
max_num = -inf
for i in [1, 2, 3, 4, 5, 6]:
if i > max_num:
max_num = i
return max_num
... |
971f92ebcde170ea9c198e1e5aba3b881427113b | shred2042/Forward-Space-Search | /FWD_Space_Search.py | 9,182 | 3.71875 | 4 | # returns true if the smaller set is included in the bigger set
def included(smaller, bigger):
for x in smaller:
if not x in bigger:
return False
return True
#taken from the lab
def NOT(P):
return "NOT_" + P
#main function
def makePlan(problemData):
problem = processInput(problemDa... |
2a74b2bc17b8407ee6bdf8b060e89ce4d59bfe28 | collinskibetkenduiwa/UrlshortenerinPython | /ulshorner.py | 627 | 3.5625 | 4 | import pyperclip,pyshorteners
from tkinter import *
root=Tk()
root.geometry("400*200")
root.title("URL SHORENER")
def urlshortener():
urladdress=url.get()
url_short=pyshorteners.Shortener().tinyurl.short(urladdress)url_address.set(url_short)
def copyurl():
url_short=url
pyperclip.copy(url_short)
La... |
248a5e497ca60c6f26a4a5958e537d5d06cc44f5 | steveding1/CS-1 | /task2.2-exer5.py | 403 | 4.03125 | 4 | #CS-1 Task 2.2 - Exercise 5 from Steve Ding
looping = True
while looping:
try:
celsius = float(input('\nEnter the Celsius temperature: '))
print ('Fahrenheit temperature is: ', (celsius*9/5+32))
ans1 = input('\ncontinue? y/n\n')
if ans1.upper() in ("NO", "N"):
loo... |
d145a98a8a7b5508c248d5163f1a066b8e04fa62 | steveding1/CS-1 | /task3.2-exer1.py | 199 | 4.03125 | 4 | pay = 0
hours = float(input('Enter Hours: '))
rate = float(input('Enter Rate: '))
if hours >40:
pay = 40*rate+(hours-40)*1.5*rate
else:
pay = hours*rate
print ('Pay: ', round(pay,2))
|
610962b96251fd0737edda69ef551c07eff2a598 | hdunlop310/small-projects | /gpa-calculator/calculator.py | 3,030 | 4.4375 | 4 | grades_vs_points = {'A1': 22, "A2": 21, 'A3': 20, 'A4': 19, 'A5': 18,
'B1': 17, 'B2': 16, 'B3': 15,
'C1': 14, 'C2': 13, 'C3': 12,
'D1': 11, 'D2': 10, 'D3': 9,
'E1': 8, 'E2': 7, 'E3': 6,
'F1': 5, 'F2': 4, 'F3': 3,
... |
fb2e5b02517723658017a75b6f743978d16aec12 | LeVeLoV1/GTC_Homeworks | /who_are_you_and_hello.py | 276 | 3.9375 | 4 | def who_are_you_and_hello():
y = True
x = input()
while y:
if x.isalpha() and x[0].istitle() and x[1:].islower():
y = False
else:
x = input()
print('Привет, ', x, '!', sep='')
who_are_you_and_hello()
|
01300e05d6763965061891651bfb312cc60fc95c | LeVeLoV1/GTC_Homeworks | /how_many_tens.py | 81 | 3.515625 | 4 | n = int(input())
q=0
m=1
while 5**m<n:
q += n//5**m
m += 1
print(q) |
2fbf06477ae032549d2a7b497d1689beed7f5a54 | LeVeLoV1/GTC_Homeworks | /Partial sums.py | 181 | 3.5625 | 4 | a = int(input())
def partial_sums(*a):
res = [0]
for i in range(len(a)):
res.append(res[i] + a[i])
return res
print(partial_sums(0, 1, 1.5, 1.75, 1.875)) |
6443be02fee53d170e239f51e5b940eff203d8b9 | mmaoga/bootcamp | /test.py | 269 | 3.578125 | 4 |
# for j in range (0, 10):
# # j += j
# print (j)
# # for friend in ["Mike", "Dennis", "Maoga"]:
# # invitation = "Hi "+friend+". Please come to my party on Saturday!"
# # print (invitation)
# i = 0
# while i < 10:
# i += 1
# print (i)
print ("Welcome") |
9fac6a0305889d4cdbe3bfa868aea21272314850 | mmaoga/bootcamp | /helloworld.py | 711 | 4.21875 | 4 | print ("hello, world")
print ("hi my name is Dennis Manyara")
print("This is my first code")
for _ in range(10):
print("Hello, World")
text = "Hello my world"
print(text)
text = "My name is Dennis Maoga Manyara"
print(text)
print("hello\n"*3)
name = "Dennis M."
print("Hello, World, This is your one and only",n... |
e264e005d7e618d6e875a582298169de37341a1f | ayub567/deep-learning-resources | /keras_xor.py | 936 | 3.734375 | 4 | #!/usr/bin/env python
"""Example of building a model to solve an XOR problem in Keras.
Running this example:
pip install keras
python keras_xor.py
"""
from __future__ import print_function
import keras
import numpy as np
# XOR data.
x = np.array([
[0, 1],
[1, 0],
[0, 0],
[1, 1],
... |
b710454eb9d28cb6220dfb6ba976506983673b21 | hyjoshi14/Hacking-Ciphers-With-Python | /Chp11.py | 3,164 | 4.3125 | 4 | ## Chapter 11 - Detecting English Programmatically""
from __future__ import division ## Similar to operator.truediv
import string, collections, os
os.chdir(r'C:\Users\Dell\Desktop\GithubRepo\Hacking Ciphers With Python')
## To detect if a message is in english, we check the percentage of characters and als... |
25b5b499fa3f8c4198c2c57858c2c0b21b6a701d | gustav-gustav/Python-pokemon | /battle.py | 875 | 3.578125 | 4 | from trainer import Trainer
class Battle:
def __init__(self, trainer1, trainer2):
self.trainer1 = trainer1
self.trainer2 = trainer2
self.trainer1.in_battle = True
self.trainer2.in_battle = True
self.winner = None
self.main()
def main(self):
self.trainer1... |
0c2107948d129a5638e15e286e3a3daee50ca793 | rawiwat/cs-module-project-hash-tables | /applications/word_count/word_count.py | 571 | 3.796875 | 4 | ignore = '":;,.-+=/\|[]{}()*^&'
def word_count(s):
# Your code here
result = {}
filtered_text = [
word.strip(ignore).lower()
for word in s.split()
if word.strip(ignore)
]
for text in filtered_text:
result[text] = result.get(text, 0) + 1
return result
if __nam... |
ac18a46a0d8af0c9178fb69369b311ae13ee21bf | ElenaDelgado/secretnumber | /numbereasy.py | 218 | 3.9375 | 4 | secret = 5
guess = int(raw_input("Guess the secret number (between 1 and 30): "))
if guess == secret:
print "Yes it is number 5!"
else:
print "Your guess is not correct... Secret number is not " + str(guess)
|
41d7eee44bf2c66cc465dd6160308221137a3da8 | jingwanha/algorithm-problems | /leetcode/771_easy.py | 460 | 3.5625 | 4 | # https://leetcode.com/problems/jewels-and-stones/
from collections import Counter
class Solution:
def numJewelsInStones(self, jewels: str, stones: str) -> int:
result = 0
cnt = Counter(stones)
for jewle in jewels:
result+=cnt[jewle]
return result
if __name__=='__ma... |
3783ffc32d99fa6ff6b91f617e634672609afb70 | jingwanha/algorithm-problems | /programers/K번쨰수.py | 314 | 3.5 | 4 | def solution(array, commands):
answer = []
for c in commands:
s_idx , e_idx , target_idx = c
answer.append(sorted(array[s_idx-1:e_idx])[target_idx-1])
return answer
array = [1, 5, 2, 6, 3, 7, 4]
commands = [[2, 5, 3], [4, 4, 1], [1, 7, 3]]
res = solution(array, commands)
print(res)
|
a9ce2df5e3ba5fef5b7d1ea6205b45e881608e08 | jingwanha/algorithm-problems | /leetcode/49_medium(1).py | 888 | 3.65625 | 4 | # https://leetcode.com/problems/group-anagrams/
from typing import List
class Solution:
# 첫 풀이 방법
# 수행시간이 n제곱이기 때문에 Time Limit Exceeded 에러 발생
# defaultdict를 이용하여 n 시간만에 풀이 가능
def groupAnagrams(self, strs: List[str]) -> List[List[str]]:
anagrams = []
while strs:
word = strs.... |
415f650e2d1cc670b0ee9e8361488b6ee850d8f0 | jingwanha/algorithm-problems | /programers/주식가격_lv2.py | 610 | 3.625 | 4 | # https://programmers.co.kr/learn/courses/30/lessons/42584
def solution(prices):
# 정답 초기화
answer = []
for i in range(len(prices), 0, -1): answer.append(i - 1)
# 인덱스가 저장될 임시 리스트
tmp = []
for i, cur_price in enumerate(prices):
while tmp and cur_price < prices[tmp[-1]]: # 가격이 떨어지면
... |
a0716d4c67188d6e9e25e3e2220fa754fad57444 | NewmanJ1987/design_patterns_python | /creational/factory.py | 1,487 | 4.25 | 4 | # Factory pattern: Abstract away the creation of an object from the
# client that is creating object.
TWO_WHEEL_VEHICLE = 1
THREE_WHEEL_VEHICLE = 2
FOUR_WHEEL_VEHICLE = 3
class Vehicle():
def print_vechile(self):
pass
class TwoWheelVehicle(Vehicle):
def __init__(self):
super(TwoWheelVehicle... |
4e26a4c5fd041c40188148825f8af7eed9861e1a | supreme-fiend/FiendNet | /Matrix.py | 2,494 | 3.828125 | 4 | """
Simple tool for matrix operations
"""
import numpy as np
def AdditionError (mat1, mat2):
print ("ADDITION ERROR !!")
print ("CANNOT ADD / SUBTRACT THESE TWO:")
print (mat1.matrix)
print (mat2.matrix)
def MultiplicationError (mat1, mat2):
print ("MULTIPLICATION ERROR !!")
print ("CANNOT MU... |
cd6ebaf06897cfec8d7d1c33fa29090ce8c1e025 | MOULIES/DataStructures | /Merge_Output_Display.py | 999 | 3.515625 | 4 | # from .SingleLinkedList import SingleLinkedList
from Data_structure.SingleLinkeList.SingleLinkedList import SingleLinkedList
class Merge_Output_Print:
def __init__(self):
list1 = SingleLinkedList()
list2 = SingleLinkedList()
print('Create list1')
list1.create_list()... |
3872a8cb98760e976a42f42993eb2011126c4516 | katewen/Python_Study | /study_1.py | 425 | 3.515625 | 4 | import re
from urllib.request import urlopen
from urllib.parse import urlencode
def getWithUrl(url):
res = urlopen(url)
def postWithUrl(url):
data = {'name': 'erik', "age": '25'}
s = urlencode(data)
res = urlopen(url, s.encode())
print(res.read().decode())
def getHTMLContent(url):
res = urlop... |
27c2905d3bdec0938e06c6643aaf113e6c60d62e | felike/hello-world | /learn/python/cpu_test.py | 158 | 3.71875 | 4 | #! /usr/bin/python3
import datetime
print(datetime.datetime.now())
sum = 0
for i in range(1,100000000):
sum +=i
print(sum)
print(datetime.datetime.now())
|
1d16ee571e19b97631a9c7c1382c94aac004f1d8 | danielrwolff/Steganographic-Encryption-Program | /main.py | 2,276 | 3.8125 | 4 | from encrypt import Encryption
from decrypt import Decryption
from rawimage import RawImage
import os
def loadImage(filename) :
if os.path.isfile(filename) :
print "\tOpening", filename
images.append([RawImage(filename),filename])
else :
print "\tImage not found!"
print "==... |
d0420d342a14efe4e226617bda91bae05012e009 | dinnguyen1495/PythonSnakeGame | /snake_game_controller.py | 4,603 | 3.90625 | 4 | """
snake_game_controller.py
Snake game controller
"""
from tkinter import Tk, Canvas, Menu
from turtle import TurtleScreen, RawTurtle
from typing import Any
import time
from snakey import Snake
def get_move_function_from_key(snake: Snake, key: str) -> Any:
"""
Get function for snake's movement when key ... |
ced1ba0dafae2c816b664e3c17225f1c6551d34c | behaoker/BBY162 | /uygulama03.py | 481 | 3.953125 | 4 | çeviriler={"Elma": "Apple", "Karpuz": "Watermelon", "Kavun": "Melon"}
Seçenekler="""
1: Anahtarları Gösterir.
2: Değerleri Gösterir.
3: Çıkış.
"""
while True:
print(Seçenekler)
işlem= input("Yapılacak İşlem:")
if işlem=="1":
print(çeviriler.keys())
elif işlem=="2":
print(çe... |
303fbdd2815a32d580ccd80192cd28da946a2865 | Tej-Singh-Rana/Code-War | /code3.py | 263 | 4.15625 | 4 | #!/bin/python3
#reverse !!
name=input("Enter the word you want to reverse : ")
print(name[::-1],end='') #to reverse infinite not adding value in parameters.
print('\n')
#print(name[4::-1],end='') #to reverse in max 4 index values.
#print('\n')
|
7251016b26478ec76ac2212da12d1893c6eb8182 | davidcphan/rebellion | /src/agent.py | 3,611 | 3.65625 | 4 | from turtle import Turtle
import config as cfg
import random
import functools as f
import math
# Represents an agent
class Agent(Turtle):
# Initialises all parameters of an agent
def __init__(self, x, y):
super().__init__(x, y)
# Agents are initially neutral
self.active = False # wheth... |
d027f50503ad1e0ab782070bb1c4ccfb9941ead6 | changeAwei/homework | /P21016-叶春草/第四周/week4.py | 5,143 | 3.578125 | 4 | #!/usr/bin/env python
#coding=utf-8
'''
1. 什么是杨辉三角和转置矩阵(文字说明即可)?
2. 说明列表和Set集合的相同点和不同点。
3. 请写出Set集合支持的所有方法及说明(例如:add 向Set集合中添加一个元素)
4. 请写出字典支持的所有方法及说明(例如:pop 从字典中移除指定的key并返回其value)
5. 请写出Python内建函数及说明(参考:https://docs.python.org/3/library/functions.html)
'''
print('''
1、杨辉三角是指一个数字组成的等腰三角形,首尾是1,其他数字都是上一行两边数字之和。
转置矩阵是... |
acbfbcc2bc6357c1319468fd1fdb7b9cf328e750 | changeAwei/homework | /P21061-韩道红/第四周作业/fourJob.py | 8,191 | 3.5625 | 4 | # 1. 什么是杨辉三角和转置矩阵(文字说明即可)?
"""杨辉三角是中国古代数学的杰出研究成果之一,它把二项式系数图形化,
把组合数内在的一些代数性质直观地从图形中体现出来,是一种离散型的数与形的结合"""
"""将矩阵的行列互换得到的新矩阵称为转置矩阵,转置矩阵的行列式不变"""
# 2. 说明列表和Set集合的相同点和不同点。
"""
列表使用有序的,set是无序的
列表的元素元素可以重复出现,set的元素不能重复,
set分为可变集合(set)和不可变集合(frozenset)两种,列表没有分类
list,set都是可以使用sort进行排序
list,set都是可迭代的
"""
# 3. 请写出Set集合支持的所有方法及说明... |
f2bea91cc4f1254d1d92e559661ca3f43ccde7d8 | changeAwei/homework | /P21061-韩道红/第三周作业/threeJob.py | 4,315 | 3.59375 | 4 | # 1. 说明列表的浅拷贝和深拷贝的区别
"""
浅拷贝: 通过copy模块里面的浅拷贝函数copy(),对指定的对象进行浅拷贝,浅拷贝会创建一个新的对象,
但是,对于对象中的元素,浅拷贝就只会使用原始元素的引用.
深拷贝: 通过copy模块里面的深拷贝函数deepcopy(),对指定的对象进行深拷贝,跟浅拷贝类似,
深拷贝也会创建一个新的对象,但是,对于对象中的元素,深拷贝都会重新生成一份,而不是简单的使用原始元素的引用
"""
# 2. 说明列表和元组的相同点和不同点
"""
1.列表属于可变序列,他的元素可以随时修改或删除;元组属于不可变序列,其中的元素不可以修改,除非整体替换。
2.列表可以使用append()、extend... |
ab044db0d35cebd0b559924ffbf134d7b6ab5637 | changeAwei/homework | /P21074-刘旭/homework-3/homework3.4.py | 463 | 3.5625 | 4 | # 4、使用选择排序算法实现排序[3, 5, 1, 7, 9, 6, 8]
nums = [3, 5, 1, 7, 9, 6, 8]
length = len(nums)
for i in range(length):
flag = False # 某一趟不用交换 就结束
for j in range(length-1-i):
if nums[j] > nums [j+1]:
temp = nums[j]
nums[j] = nums[j+1]
nums[j+1] = temp
#nums[j],nums... |
90f789b59d35d9564c24afc18bbf8db751aca155 | changeAwei/homework | /P21030-赵鑫/第八周/mycat.py | 839 | 3.8125 | 4 | #1. 使用本周和之前所学习的知识实现cat命令(支持查看内容和-n参数功能即可)
import argparse
class Mycat:
def __init__(self,file,number=False):
self.file = file
self.number = number
def filecontents(self):
with open(self.file) as f:
if self.number:
for i, line in enumerate(f):
... |
b489a3d700f36fce233503ea6bd352b44ffb099c | changeAwei/homework | /P21067-郝哲宇/第四周/第4周作业.py | 7,033 | 3.78125 | 4 | """
1. 什么是杨辉三角和转置矩阵(文字说明即可)?
杨辉三角的本质特征是:
他的俩条斜边有事由数值1组成,二其余的数则是等于他肩上的俩个数之和:
如果用二项式表示其推导式:
(a+b)^n
n=0 (a+b)^0 1 = 1
n=1 (a+b)^1 1 1 = 2
n=2 (a+b)^2 = a^2+2ab+b^2 1 2 1 = 4
n=3 (a+b)^3 = a^3+3a^2b+3ab^2+b^3 1... |
d8a520b5d058f2bd006fd89bfc911de36c42d8e1 | changeAwei/homework | /P21062-刘庆归/第三周/4.sort.py | 211 | 3.671875 | 4 | lst = [3, 5, 1, 7, 9, 6, 8]
for i in range(len(lst)-1):
index = i
for j in range(i+1,len(lst)):
if lst[index] > lst[j]:
index = j
lst[i],lst[index] = lst[index],lst[i]
print(lst)
|
c434cacced85908bed62582a84614bd7b4f0b02d | DivyaKalash/Adams-Bashforth | /Adams_Bashforth/A_B.py | 2,727 | 3.640625 | 4 | import matplotlib.pyplot as plt
from tabulate import tabulate
from art import *
print(logo)
print("*" * 200)
def func(x, y):
"""
:return: returns function value by putting value of x and y.
"""
res = (1 + y)
return res
def predictor(y3, h, f3, f2, f1, f0):
"""
:return:... |
d55dbddcb5f571ff499e7dc5aefd1fb066fe83be | joshmi1902/PC2-2019-2 | /2.py | 884 | 3.65625 | 4 | import os
os.system("cls")
n = []
s = []
e = []
hombres = 0
mujeres = 0
#proceso
while len(n) < 5 and len (e) < 5 and len(s) < 5:
name = input("ingrese nombre: ")
n.append(name)
sexo = input("ingrese sexo: ")
if sexo == "masculino" or sexo == "femenino":
s.append(sexo)
if se... |
0deae1c6773a018bef55d8e1bcbc5477eee7311c | yuuuhui/Basic-python-answers | /梁勇版_4.5rpy.py | 964 | 4.34375 | 4 | day = int(input("Enter today's day :"))
daye = int(input("Enter the number of days elaspsed since today:"))
dayf = day + daye
dayc = dayf % 7
print(dayc)
if day == 0:
print("Today is Sunday")
elif day == 1:
print("Today is Monday")
elif day == 2:
print("Today is Tuesday")
elif day == 3:
... |
290b22fd0649a1009f8b03c8baa15abf28f5fc3e | yuuuhui/Basic-python-answers | /梁勇版_6.38.py | 303 | 3.609375 | 4 | import turtle
def turtlegoto(x,y):
turtle.penup()
turtle.goto(x,y)
turtle.pendown()
def drawline(x1,y1,x2,y2,color = "black",size = 1):
turtle.color(color)
turtle.pensize(size)
turtlegoto(x1,y1)
turtle.goto(x2,y2)
drawline(100,200,300,400)
|
1f0dec4bdd954b819dff92e4630ac144f8aa9989 | yuuuhui/Basic-python-answers | /梁勇版_4.24rpy.py | 5,483 | 3.96875 | 4 | ace = "Ace"
eleven = "Jack"
twelve = "Queen"
thirteen = "King"
c1 = "spades"
c2 = "Heart"
c3 = "diamonds"
c4 = "clubs"
import random
num = random.randint(1,14)
color = random.randint(1,4)
gsize = random.randint(0,1)
if num == 14:
if gsize == 0:
print("The card you picked is red Kin... |
c9654b7176e0ca7f33a5329cd0b408a3d00bbf9c | yuuuhui/Basic-python-answers | /梁勇版_6.26.py | 804 | 4.09375 | 4 |
def isprime(z):
i = 2
divisor = 2
ispr = True
while divisor < z:
if z % divisor == 0:
ispr =False
else:
pass
divisor += 1
return ispr
def ismeiprime(x):
i = 2
isp = True
while 2 ** (i) - 1 <= x:
if (2 ** (i)... |
c0ae04bcc6d3692e57532987778cecfa4d639334 | yuuuhui/Basic-python-answers | /梁勇版_5.4.py | 107 | 3.78125 | 4 | print("miles \t km")
for i in range(1,11):
km = i * 1.609
print("{} \t {:.3f}".format(i,km))
|
a79fd086a474a2f36a04ad9484f34c0dedd2f8d1 | yuuuhui/Basic-python-answers | /梁勇版_6.24.py | 763 | 3.859375 | 4 |
def isprime():
count = 0
i = 0
n = 1000
while i < n:
divisor = 2
isprimenumber = True
while divisor < i :
if i % divisor == 0:
isprimenumber = False
break
else:
... |
10b9b8c4daf1ea5730092711245e9bc4e2836deb | yuuuhui/Basic-python-answers | /梁勇版_6.39.py | 432 | 3.65625 | 4 | import turtle
def turtlegoto(x,y):
turtle.penup()
turtle.goto(x,y)
turtle.pendown()
def drawline(x1,y1,x2,y2,color = "black",size = 1):
turtle.color(color)
turtle.pensize(size)
turtlegoto(x1,y1)
turtle.goto(x2,y2)
def drawstar():
drawline(0,100,50,-150)
... |
78c1b55c46f5aad5e9361ee75feb79f3409e0743 | yuuuhui/Basic-python-answers | /梁勇版_1.9.py | 196 | 3.65625 | 4 | width = 4.5
height = 7.9
area = width * height
perimeter = 2 * ( width + height)
print("""
宽度为{}而高为{}的矩形面积为{},周长为{}
""".format(width,height,area,perimeter))
|
cf32a83c651d59598fd9708bf99266cb9d800cff | yuuuhui/Basic-python-answers | /梁勇版_2.14.py | 379 | 3.984375 | 4 | x1,y1,x2,y2,x3,y3 = eval(input("Enter three points for a triangle:"))
side1 = ((y2 - y1) ** 2 + (x2 - x1) ** 2) ** 0.5
side2 = ((y3 - y2) ** 2 + (x3 - x2) ** 2) ** 0.5
side3 = ((x1 - x3) ** 2 + (y1 - y3) ** 2) ** 0.5
s = (side1 + side2 + side3) / 2
area = (s * (s - side1) * (s - side2) * (s - side3)) ** 0.5
print... |
e19e3398e3ad3667b4026be17f5a5c10eb26f1d8 | yuuuhui/Basic-python-answers | /梁勇版_4.7rpy.py | 620 | 3.78125 | 4 | amount = eval(input("Enter the amount:"))
remainingamount = int(amount * 100)
onedollar = remainingamount // 100
remainingamount = remainingamount % 100
quarters = remainingamount // 25
remainingamount = remainingamount % 25
dimes = remainingamount // 10
remainingamount = remainingamount % 10
nickles = ... |
eb1e5ab98046948e5430c8fe9da76d0497ef0be7 | yuuuhui/Basic-python-answers | /梁勇版_4.11rpy.py | 1,308 | 3.96875 | 4 | #闰年和非闰年
year = int(input("Enter the year:"))
month = str(input("Enter the month:"))
if year < 0:
print("wrong input!")
elif year % 4 == 0 and month =="二月":
print("{}年{}月有29天".format(year,month))
else:
if month == "一月":
print("{}年{}份有31天".format(year,month))
elif month == "二月":
... |
8057729bfad807fc5b23ed68b71e5746af7b26ee | yuuuhui/Basic-python-answers | /梁勇版_4.28rpy.py | 949 | 4.21875 | 4 | x1,y1,w1,h1 = eval(input("Enter r1's x-,y- coordinates,width,and height:"))
x2,y2,w2,h2 = eval(input("Enter r2's x-,y- coordinates,width,and height:"))
hd12 = abs(x2 - x1)
vd12 = abs(y2 - y1)
if 0 <= hd12 <= w1 /2 and 0 <= vd12 <= h1 / 2:
print("The coordinate of center of the 2nd rect is withi... |
98f0149fb41308f9e80baea2bb63055ebaf326f2 | yuuuhui/Basic-python-answers | /梁勇版_2.23py.py | 355 | 3.8125 | 4 | import turtle
r = int(input("Enter the radius:"))
turtle.showturtle()
turtle.circle(r)
turtle.penup()
turtle.goto(2 * r,0)
turtle.pendown()
turtle.circle(r)
turtle.penup()
turtle.goto(0,2 * r)
turtle.pendown()
turtle.circle(r)
turtle.penup()
turtle.goto(2 * r, 2 * r)
turtle.pendown()
turtle.circle(... |
f22ac6d916ab358fb770e891bc9daa9044fb3ca1 | yuuuhui/Basic-python-answers | /梁勇版_5.46py.py | 264 | 3.875 | 4 | from math import *
xsquare = 0
sum = 0
numlist = []
for i in range(1,11):
num = eval(input("Enter ten numbers"))
xsquare += (num ** 2)
sum += num
mean = sum /10
sd = sqrt( ( xsquare - ((sum ** 2)/10) ) / (10 - 1))
print(mean,sd)
|
dfa4ad361b159743f8ecd2f3888e6e6e1420ed3d | yuuuhui/Basic-python-answers | /梁勇版_5.24py.py | 640 | 4.125 | 4 | loan = eval(input("Loan Amount"))
year = int(input("Number of Years:"))
rate = eval(input("Annual Interest Rate:"))
monthly = (loan * rate / 12) / (1 - 1 / ((1 + rate / 12) ** (year * 12)))
total = monthly * 12 * year
print("Monthly Payment:{:.2f}".format(monthly))
print("Total Payment:{:.2f}".format(total))
p... |
432d2e8a614fda318ec9242ce760fd13284de2cd | yuuuhui/Basic-python-answers | /梁勇版_6.34.py | 254 | 4.03125 | 4 | from math import *
n = eval(input("Enter the number of sides:"))
s = eval(input("Enter the side:"))
def area(n,s):
area = (n * (s ** 2)) / (4 * tan(pi / n))
print("The area of the polygon is {:.2f}".format(area))
area(n,s)
|
3a72bb27f435bd2bd4c9ab1df26fa671e5eb2263 | MalachiBlackburn/cti110new | /P2T1_SalesPrediciton_MalachiBlackburn.py | 345 | 3.890625 | 4 | #This program will convert pounds to kilograms
#2/12/19
#CTI-110 P2T1 - Sales Prediction
#Malachi Blackburn
#Gets the projected total sales
total_sales = float(input("Enter the projected sales: "))
#Calculates the profit as 23 percent of total sales
profit = total_sales * .23
#Display the profit
print("The pro... |
7b156440fe82f681be466327acc244b6f980e637 | JamesMsuya/algorithms. | /maximum_cost_141044093.py | 1,690 | 3.5625 | 4 | """
This algorithm keeps tracks of two local defined list. For every i'th number in an list Y two assumtions are made
that is is itself or 1. The subsequent sums of when it is 1 or itself are kept in two list lis and li respectively.
The list lis[] and li[] are initialized to 0 assuming previous sum is 0.
lis[i]... |
c51001c9f85d970cba0d7e06757e021919ec132e | joseluisvzg/EnvioClickChallenge | /Python/Exercise2.py | 415 | 4.34375 | 4 | #!/usr/bin/env python
consec_vowel = {
'a': 'e',
'e': 'i',
'i': 'o',
'o': 'u',
'u': 'a'
}
def vowels_changer(text):
new_text = []
for char in text.lower():
if char in consec_vowel:
char = consec_vowel[char]
new_text.append(char)
new_text = ''.join(new_text)
return new_text
if __name__ == "__main__":
... |
90306e40508ccd4f94c0cc690c3df9b3be41f639 | ensardemirci/BTKAkademi | /20 - Pandas/20.13 - Uygulama Nba Veri analizi.py | 920 | 3.609375 | 4 | import pandas as pd
df = pd.read_csv('20 - Pandas/Datasets/nba.csv')
# 1
result = df.head(10)
# 2
result = len(df.index)
# 3
result = df['Salary'].mean()
# 4
result = df['Salary'].max()
# 5
result = df[['Name','Salary']].sort_values('Salary', ascending=False).head(1)
# 6
result = df.query('20 <= Age < 25 ')[['N... |
135001be71705edc93df8521017c2968145f29d1 | wdj729115299/python_study_test | /hello_word2.py | 508 | 3.90625 | 4 | shoplist = ['apple', 'orange', 'banana', 'carrot']
print 'I have ', len(shoplist), ' items to purchase.'
print 'these items are:'
for item in shoplist:
print item,
print 'I alse have to buy rice'
shoplist.append('rice')
print 'these items are:'
for item in shoplist:
print item,
print 'I will sort my list'
... |
91c7ac1b5cb702cb02409c47af289d7229f58261 | huiqi2100/searchingsorting | /bubblesort.py | 288 | 4.03125 | 4 | # bubblesort.py
def bubblesort(array):
swapped = True
while swapped:
swapped = False
for i in range(1, len(array)):
if array[i-1] > array[i]:
array[i-1], array[i] = array[i], array[i-1]
swapped = True
return array
|
689936f0132a848679cc145a305f6594427e038d | UccelloLibero/Python_code_challenges | /list_challenges.py | 4,996 | 4.28125 | 4 | # 1.
# Create a function named double_index that has two parameters named lst and index.
# The function should return a new list where all elements are the same as in lst except for the element at index, which should be double the value of the element at index of lst.
# If index is not a valid index, the function shoul... |
e542f971074e637d708f209bb1be1237e97e59fb | belogurow/BMSTU_IU9 | /Bioinformatics/Lab2/Util.py | 274 | 3.65625 | 4 | def print_sequences(seq_1: str, seq_2: str):
sequence_len = len(seq_1)
start = 0
step = 80
end = start + step
while start < sequence_len:
print(seq_1[start:end])
print("|" * len(seq_1[start:end]))
print(seq_2[start:end])
print()
start += step
end += step |
94544d5793f5356e6a195efd153f4ae268426c22 | Sarumathikitty/guvi | /codekata/Array/print_ele_less_des_order.py | 254 | 3.84375 | 4 | #print all elements lesser than n in descending order
def function(N,n):
a=[]
for i in range(len(n)):
if(n[i]<N):
a.append(n[i])
a.reverse()
return(a)
N=int(input())
n=list(map(int,input().split()))
c=function(N,n)
print(*c)
|
ebacaa22aa8623a063016865b8faa790bb4d359a | Sarumathikitty/guvi | /codekata/Strings/find_len_str.py | 91 | 3.890625 | 4 | #Given a string find its length
n=str(input())
count=0
for i in n:
count+=1
print(count)
|
c281900a2efc288a4eb5e00b3b8bf0cb35dc6fe0 | Sarumathikitty/guvi | /codekata/Array/print_suffix_sum.py | 229 | 3.734375 | 4 | #Given a number print suffix sum of the array
def function(N,s):
sum,a=0,[]
for i in range(N):
sum=s[i]+sum
a.append(sum)
a.reverse()
return(a)
N=int(input())
s=list(map(int,input().split()))
c=function(N,s)
print(*c)
|
a68591df5fbf05b2b660b51d5991e7a5987842af | Sarumathikitty/guvi | /codekata/Mathematics/print_mod_c.py | 81 | 3.53125 | 4 | #Given a number print a*b mod c
a,b,c=map(int,input().split())
d=a*b
print(d%c)
|
3728c371427f3c1619302da9945650f66a453c33 | Sarumathikitty/guvi | /codekata/Basics/scalene_triangle.py | 259 | 3.828125 | 4 | #Given 3 numbers form a scalene triangle
def checkvalid(a,b,c):
if((a!=b) and (b!=c) and (a!=c)):
return True
else:
return False
a,b,c=map(int,input().split())
if checkvalid(a,b,c):
print("yes")
else:
print("no")
|
1e1b9210ab2b9a6f177149adeb043ec0a9da3576 | Sarumathikitty/guvi | /codekata/Strings/remove_char.py | 105 | 3.875 | 4 | #Given a string remove characters which are present in another string
s=str(input())
print(s+" Answer")
|
246dd56dd9d9b2a217a93a26949d9bed5fa69020 | Sarumathikitty/guvi | /codekata/Mathematics/print_a_pow_b.py | 94 | 3.640625 | 4 | #Given numbers A,B find A power of B
A,B=map(int,input().split())
res=A**B
print(res)
|
e174013d66f9135fd27ed24b666eff412b3f49c3 | Sarumathikitty/guvi | /codekata/Absolute_Beginner/check_odd_even.py | 264 | 4.5 | 4 | #program to check number whether its odd or even.
number=float(input())
num=round(number)
#check number whether it is zero
if(num==0):
print("Zero")
#whether the number is not zero check its odd or even
elif(num%2==0):
print("Even")
else:
print("Odd")
|
ce7593b19ffef271972cf5d3c8f1ae164c462832 | yaxinn/codingground | /New Project/maxmin.py | 3,363 | 3.703125 | 4 | import collections
class maxQueue():
def __init__(self):
self.size = 0
self.q = collections.deque()
self.mq = collections.deque()
def push(self, num):
while self.mq and self.mq[-1] < num:
self.mq.pop()
self.mq.append(num)
self.q.append(num)
... |
400edf9a59ca355efe631e7ebbdaf8cd35ff6e3f | egillanton/samromur-asr | /preprocessing/ice-norm/text-cleaning/map_replacement.py | 2,575 | 3.515625 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Uses replacement mapping files to replace symbols and strings in input using the replacement strings.
"""
import re
mp_file_path = '../mapping_tables/'
acro_file = 'acros.txt'
abbr_file = 'abbr.txt'
symbol_file = 'symbol_mapping.txt'
class ReplacementMaps:
d... |
b4a16f1bdcbec1708a30ec89179ae36572a04a0a | enriqueaf/UniProyectos | /Colorear.py | 832 | 3.515625 | 4 | class MatrizIncidencia:
def __init__(self,lista):
self._lista = lista
self.vertices = len(lista)-1
def estan_unidos(self,a,b):
if self._lista[a][b]==1: return True
return False
def pintar(n,M):
pintura = coloreando(0,M,[])
if n in pintura: return False
return pintura... |
45118f6aca17577fd9966d3512d708df950cd5b5 | PACOPEPE20/PROGRAMAS_PYTHON | /aplicacioncoche.py | 577 | 3.859375 | 4 | class Coche:
"""Abtraccion de los objetos coche"""
def __init__(self, gasolina): #self es el objeto y no cuenta como argumento
self.gasolina = gasolina
print("Tenemos", gasolina, "litros")
def arrancar(self):
if self.gasolina > 0:
print("Arrancar")
... |
307469ae45627409999676e6007c53d2157b81ea | PACOPEPE20/PROGRAMAS_PYTHON | /pregunta.py | 254 | 3.96875 | 4 |
#¿Cuál es el color dominante de la bandera de España?
fav = (input("¿Cuál es el color dominante de la bandera de España?: "))
if fav == "rojo":
print("SÍ")
print("Aceretaste")
else:
print(" NO")
print(" Qué lastima")
|
8971147b9464d531ec12b4f55a1efe01d06bc243 | isoscl/betterlifepsi | /psi/app/utils/date_util.py | 2,448 | 3.90625 | 4 | from datetime import datetime
def years_ago(years, from_date=None):
if from_date is None:
from_date = datetime.now()
try:
return from_date.replace(year=from_date.year - years)
except ValueError:
# Must be 2/29!
assert from_date.month == 2 and from_date.day == 29
ret... |
a34a5cf032f82720848d4adaef67d135ad941e4c | pradyotpsahoo/P342_A1 | /A1_Q2.py | 500 | 4.46875 | 4 | # find the factorial of a number provided by the user.
# taking the input from the user.
num = int(input("Enter the number : "))
factorial = 1
# check if the number is negative, positive or zero
if num < 0:
print("Factorial does not exist for negative numbers. Enter the positive number.")
elif num == 0:
... |
38eaad2f4ca9dd200e293f5c20b537d8053934a0 | Tricerator/DataStructuresAndAlgorithms | /DataStructures/LinkedList/LinkedList.py | 1,922 | 4 | 4 | #!/usr/bin/env python3
class Node:
def __init__(self, value):
self.value = value
self.descendant = None
class LinkedList(object):
def __init__(self, value=None):
if value is None:
self.root = None
return
if type(value).__name__ == 'list':
... |
1fdad2f80ff24e67e2ebff80f725f53369af384a | BobAnkh/MaC | /hw2/program/mytorch/loss.py | 2,167 | 3.75 | 4 | # Do not import any additional 3rd party external libraries as they will not
# be available to AutoLab and are not needed (or allowed)
import numpy as np
import os
# The following Criterion class will be used again as the basis for a number
# of loss functions (which are in the form of classes so that they can be
# e... |
8af7987d86f068aeba4978fc10098d9a21d2c36d | dennisbader/pd_analysis | /distributionset/Gaussiandistribution.py | 3,990 | 4.21875 | 4 | import math
import numpy as np
from matplotlib import pyplot as plt
from .Generaldistribution import Distribution
class Gaussian(Distribution):
""" Gaussian distribution class for calculating and
visualizing a Gaussian distribution.
Attributes:
mean (float) representing the mean value of the distribution
st... |
b5fc65a10dddac2ee66bff21157c80734ab2fc8a | butlerk/5023-OOP-scenarios | /students/main.py | 970 | 4 | 4 | from grades import Student
students = []
student1 = Student('Michael', 80, 70, 70, True)
students.append(student1)
student2 = Student('Angela', 60, 65, 75, True)
students.append(student2)
student3 = Student('Natalie', 60, 65, 100, False)
students.append(student3)
# Print the names and marks for each of the students... |
aaaf7244971bdfe175e4c5b54e0589eaa0d05bec | Stuartlab-UCSC/stuartlab-scripts | /python/scipy-0.8.0/scipy/optimize/cobyla.py | 2,262 | 3.5 | 4 | """Interface to Constrained Optimization By Linear Approximation
Functions:
fmin_coblya(func, x0, cons, args=(), consargs=None, rhobeg=1.0, rhoend=1e-4,
iprint=1, maxfun=1000)
Minimize a function using the Constrained Optimization BY Linear
Approximation (COBYLA) method
"""
import _cobyla
from nu... |
aa9b82d2376bccc0c2ee86a4458901fd1bb42707 | SireeshaPandala/Python | /Python_Lesson5/Python_Lesson5/LinReg.py | 936 | 4.15625 | 4 | import numpy as np
import matplotlib.pyplot as plt #for plotting the given points
x=np.array([2.9,6.7,4.9,7.9,9.8,6.9,6.1,6.2,6,5.1,4.7,4.4,5.8]) #converts the given list into array
y=np.array([4,7.4,5,7.2,7.9,6.1,6,5.8,5.2,4.2,4,4.4,5.2])
meanx=np.mean(x) #the meanvalue of x will ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.