blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
877d9bf193fb488b296ba3666df992ea33bc3dff | as030pc/MisionTIC | /Fundamentos de Programacion - Python/Semana 3_Subprogramas, vectores, POO/metodos.py | 3,240 | 3.59375 | 4 | def esVacio(vec):
return vec.V[0] == 0
def esLleno(vec):
return vec.V[0] == vec.n
def tamagno(vec):
return vec.n
#agregar un dato(d) al final del Vector. Si esta lleno no agrega el dato
def agregarDato(vec, d):
if esLleno(vec):
return
vec.V[0] = vec.V[0] + 1
vec.V[vec.V[0]] = d
... |
fe92f37793f6407b778248e8db66a1d5c17ccaf9 | RAMMVIER/Data-Structures-and-Algorithms-in-Python | /Algorithm/2.Binary_search.py | 746 | 3.75 | 4 | # 二分查找:从有序列表的初始候选区list[0:n-1]开始,通过对待查找的值与候选区中间值的比较,使候选区减小一半
# 时间复杂度:O(logn)
def binary_search(li, val):
left = 0
right = len(li) - 1
while left <= right: # 候选区有值
mid = (left + right) // 2 # 整除用于取整数部分作为下标
if li[mid] == val:
return mid
elif li[mid] > ... |
a611c802f71433b930f372d61e7ef5a13bbe1b77 | J-Chaudhary/dataStructureAndAlgo | /linklist.py | 1,305 | 3.953125 | 4 | # Student : Jignesh Chaudhary, Student id : 197320
# Assignment - 1 (d)
import Queue
import Stack
def main():
linklist = Queue.Queue()
def add():
data = input("enter data in to queue: ")
linklist.EnQueue(data)
def remore():
linklist.DeQueue()
def display():
... |
519f15f55c8272cf53a7b46d67ff5ab661599f82 | gabriellaec/desoft-analise-exercicios | /backup/user_305/ch21_2019_03_15_16_02_56_907198.py | 101 | 3.6875 | 4 | a = int(input('Valor da conta:'))
a = a * 1.10
print ('Valor da conta com 10%: R$ {0:.2f}'.format(a)) |
3ff2382ff7f3e14d8f61cac3961734613b6ceb9b | edureimberg/learning_python | /exercicios/ex6.py | 257 | 3.859375 | 4 | print("Programa para calcular o tempo de viagem")
distancia = int(input("Digite a distancia a ser percorrida (KM):"))
velocidade = int(input("Digite a velocidade do veículo (KM/H):"))
print("O tempo da viagem é:", (distancia * 1) / velocidade, "horas")
|
0ff92bbd8fe1ffb415694ed2ec478b8a0e6a9a79 | shoyer/xarray | /xarray/plot/facetgrid.py | 21,632 | 3.765625 | 4 | import functools
import itertools
import warnings
import numpy as np
from ..core.formatting import format_item
from .utils import (
_infer_xy_labels,
_process_cmap_cbar_kwargs,
import_matplotlib_pyplot,
label_from_attrs,
)
# Overrides axes.labelsize, xtick.major.size, ytick.major.size
# from mpl.rcPa... |
9b7762f5ddc1112ac2ef653904d73be0875062e9 | hason123/ironman | /Session 7/Part 2/dash.py | 247 | 3.765625 | 4 | colors = ["blue" , "green","red","yellow"]
from turtle import *
shape("turtle")
speed(1)
color(colors[0])
forward(100)
color(colors[1])
forward(100)
color(colors[2])
forward(100)
color(colors[3])
forward(100)
mainloop() |
20acfe1723b3ac2f1ad04c8f5f1f19a7a32e3332 | ZacByrnes/CP1404_Practical | /prac_02/files.py | 609 | 3.96875 | 4 | """
Ask User for Name
"""
#Start
Name = input("What is your name? ")
OUTPUT_FILE = Name
out_file = open("name.txt", "w")
print("Your name is ", file=out_file)
out_file.close()
#Second Part
in_file = open('name.txt', "r")
name = in_file.read()
print("Your name is", name)
in_file.close()
#Getting Numbers from a documen... |
ef02d189b3c726c0014f476c8fd95aa38d7b9ea5 | zxcvbnm123xy/leon_python | /python1808real/day21/day21-2-thread.py | 4,237 | 3.625 | 4 | # 二、线程
# 线程的概念:进程中的基本执行单元。
# 已学过创建线程的方式:
#(1) 使用init方法创建线程对象,指定target和args
#(2)继承Thread,重写run方法
from threading import Thread
#使用Thread完成案例
# IO密集型 10.5s
# 计算密集型 1.7s
import time
def sum(a,b):
s=0
for i in range(a,b):
s+=i
time.sleep(0.5)
return s
# def sum_1(b1,b2):
# t1=Thread(target=s... |
b13eca10427613fd50504e438f6ab566466f0600 | MaLei666/practice | /剑指Offer/数组_哈希/04-二维数组中的查找.py | 1,322 | 3.515625 | 4 | # -*- coding:utf-8 -*-
# @author : MaLei
# @datetime : 2021/2/18 9:38 下午
# @file : 04-二维数组中的查找.py
# @software : PyCharm
'''
在一个 n * m 的二维数组中,每一行都按照从左到右递增的顺序排序,每一列都按照从上到下递增的顺序排序。
请完成一个高效的函数,输入这样的一个二维数组和一个整数,判断数组中是否含有该整数。
示例:
现有矩阵 matrix 如下:
[
[1, 4, 7, 11, 15],
[2, 5, 8, 12, 19],
[3, 6, 9, 16, 22],
... |
e32b14f8f3e60e7c9d88d5f669bb31099a45d3c9 | MinnuMariyaJoy/luminarpythoncode | /Advanced/Test/Test 1/q1.py | 459 | 3.671875 | 4 | class Vehicle:
def m1(self,registration,cost,mileage):
self.registration=registration
self.cost=cost
self.mileage=mileage
def m2(self):
print("Registration: ",self.registration)
print("Cost: ",self.cost)
print("mileage: ",self.mileage)
class Bus(Vehicle):
bna... |
3ec4c9c3c906bf24cc2538f421bfa6d8af6744ab | amughal2/Portfolio | /python_work/cities.py | 691 | 4.28125 | 4 | the_cities = {
'greensboro': {
'location' : 'nc',
'population' : 300000,
'fact' : 'it is green'
},
'new york' : {
'location' : 'ny',
'population' : 1000000,
'fact' : 'it is the biggest city in america',
},
'chicago' :{
'location' : 'il',
'population' : 1000000,
'fact' : 'it is the windy city of... |
67ee4ef52f22b3fe0b64d3076cedd11f302209d7 | Javiergm18/PREINFORME-DE-LABORATORIO-9 | /PREINFORME-DE-LABORATORIO-9/2.py | 168 | 3.8125 | 4 | numero = int( input("ingrese un numero: "))
i = 0
while numero > 0 :
i = i+1
resto = numero % 10
numero = int(numero/10)
print("%d"%(resto),end ="") |
62029f6f9823ca2412225f0184d730dc74f5a776 | blehrhof/brian | /better looping and code.py | 6,095 | 3.546875 | 4 | for i in [0,1,2,3,4,5]:
print i**2
for i in range(6):
print i**2
for i in xrange(6):
print i**2
colors = ['a','b','c','d']
for i in range(len(colors)):
print(colors[i])
for color in colors:
print color
for i in range(len(colors)-1,-1,-1):
print colors[i]
for color in... |
2eb13cfac1666d3b86a4b525512133054e98f3f2 | mzaldiadithya/Python | /Tugas Pertemuan 3/tugas 1/operator-bitwise.py | 1,177 | 4.09375 | 4 | # ============================= Operator Bitwise ===========================
title = "Operator Bitwise"
print("\n" + title.upper().center(100))
print("================================\n".center(100))
a = 14
b = 3
# Bitwise AND operation
print("a & b =", a & b)
print("\n============== Bitwise AND Explanati... |
33715334d1f8f680daeac7f452fc90ecbb8b7553 | Gyllm/UNIABCDE | /professor.py | 1,100 | 3.5625 | 4 | from empregado import Employee
class Teacher(Employee):
def __init__(self,name,phone,email,salary,start_date,course):
super().__init__(name,phone,email,salary,start_date)
self.course = course
def additional_health_hazard(self):
if self.course == 'Engenharia':
return {
... |
68c37568dab6c0e95cb00e2ed289b7af638d66eb | nathanrw/aoc2020 | /aoc2020.py | 12,573 | 3.546875 | 4 | import argparse
import re
import functools
import operator
def task_1_part_1():
with open('input1.txt') as f:
lines = f.readlines()
numbers = [ int(line) for line in lines ]
def get_number(numbers):
for x in numbers:
for y in numbers:
if x + y == 2020:
... |
d0e8d7ac03d1c927d90e4ec526f3b759248fb255 | mikgross/cognitive-developer-training | /hands-on/task-3 - KMeans/plot_cluster_iris.py | 3,468 | 3.84375 | 4 | #!/usr/bin/python
# -*- coding: utf-8 -*-
"""
=========================================================
K-means Clustering
=========================================================
The plots display firstly what a K-means algorithm would yield
using three clusters. It is then shown what the effect of a bad
initializa... |
15ba84c0279bfe0ffa38412da28b4786873eebc9 | hareem-a/Python | /Population.py | 862 | 3.828125 | 4 | """
This program compares the populations of the US and Mexico.
Author: Hareem
"""
US_pop = 328200000
mexico_pop = 127600000
US_rate = 0.53
mexico_rate = 1.06
US_dec = .9947
mexico_inc = 1.0106
years = 0
print("The current population of the US is %d and decreases by %f each year." % (US_pop, US_rate), sep = " ")
pri... |
55fcd2137a5fb7536358a687e68539010f424b60 | ruslanolkhovsky/utilitypy | /file_str_replace.py | 2,332 | 4.53125 | 5 | """A simple utility program in python 3 to replace a string all over a file with a new string, and save the result to a new file.
Example:
``
$ python3 file_str_replace.py -s 'file.txt' -f 'A' -r 'B' -t 'new_file.txt'
``
Arguments:
--sourcefile, -s Name of the source file (required)
--find, -f String to... |
87b2b5f91bac4b369886a7ef2773c673058687b1 | arkuzya/infa_2019_arkuzya | /lab2/12.py | 296 | 4 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Sep 12 16:07:29 2019
@author: student
"""
import turtle
t = turtle
for r in range(7):
for i in range(50):
t.forward(1)
t.right(3.6)
for i in range(50):
t.forward(0.3)
t.right(3.6)
|
f71baced225563cf55ca03248cd9a86149431ec5 | muzuco/pythonstudy2015 | /01_wiki.python.org/15_itertools.py | 359 | 3.5 | 4 | from itertools import groupby
lines = '''
this is the
first paragraph.
this is the second.
'''.splitlines()
print len(lines)
print '-------------'
for i, tmp in enumerate(lines):
print 'line {num} : {str}'.format(num=i, str=tmp)
print '-------------'
for has_chars, frags in groupby(lines, bool):
if ha... |
f0e453cb807e7259cc5e5d8cd2846c36efa29d17 | hooong/baekjoon | /Python/10830.py | 817 | 3.640625 | 4 | # 10830번 행렬 제곱
# 행렬 곱셈
def mul(n,matrix1,matrix2):
result = [[0 for _ in range(n)] for _ in range(n)]
for i in range(n):
for j in range(n):
for k in range(n):
result[i][j] += matrix1[i][k] * matrix2[k][j]
result[i][j] %= 1000
return result
# 2분할
def devide... |
d3bb165b0bccc11c90e19a91d5b168080a84efe4 | sapnajayavel/FakeReview-Detector | /annotation/shingling.py | 1,283 | 3.5 | 4 | #!/usr/bin/env python2.7
#encoding=utf-8
"""
"""
def ngram_sequence(n,string):
string = list(string)
sequence = []
for i in range(len(string)-4):
s = string[i]+string[i+1]+string[i+2]+string[i+3]
sequence.append(s)
return list(set(sequence))
def jaccard_str(s1,s2):
seq1 = ngram_se... |
d46b9f7e91c7d07d152434fd4e9ba8bc54ea666d | OmarGP/Python1 | /Secuencia_de_Ejercicio01/Ejercicio H.py | 997 | 4.1875 | 4 | import math
#H1. Muestra las siguientes secuencias de número utilizando un WHILE:
#H1.1 Secuencia del 1 al 100
a = 1
print(f" >>>> Secuencia del 1 al 100 <<<<")
while (a <= 10):
print (f"# {a}")
a += 1
print("=============================")
#H1.2 Los números impares del 51 al 91.
print(f" >>>> Secuencia d... |
b6dc649684a4bba7e05b1b4e6641da66a7a5e196 | hideraldus13/mini_jogos_python | /adivinhe_o_numero.py | 1,233 | 3.875 | 4 | import random
def jogador(x):
numero_randomico = random.randint(1, x)
palpite = 0
print(f'Vamos lá! Adivinhe o número que escolhi. Uma dica: é um número entre 1 e {x}.')
while palpite != numero_randomico:
palpite = int(input(f'Adivinhe um número entre 1 e {x}: '))
if palpite < numero_... |
0d38003408c5c7684635040270f3650d6e1f4989 | arunpatala/scala-learn | /SPOJ/py/MIRRORED.py | 180 | 3.6875 | 4 | print "Ready"
while(True):
s = raw_input()
if(s==" "):
break
else:
if(s=="pq" or s=="qp" or s=="db" or s=="bd"):
print "Mirrored pair"
else:
print "Ordinary pair"
|
6f8f3f9a5432a1e21c8908f06f78979ce645cb53 | kmanwar89/ISAT252 | /Exercises/Textbook Examples Chapter 10/flip.py | 847 | 4 | 4 | __author__ = 'kadar'
# Example of a class and a main function in the same file. Fine for smaller
# programs but not good for future expansion/large & complex programs.
import random
class Coin:
def __init__(self):
# self.sideup = 'Heads' -- this is not private, the attribute can be directly accessed
... |
31432e268fe4802aa80cafffb1ef7ca81a5609b2 | Novandev/pythonprac | /interview/minimum_swaps.py | 981 | 3.625 | 4 | '''
Given an array of increasing numbers (range function in python)
find out how many bribes everone had to take to get to thier positions, note that a single person cannot bribe fore than 2 people in from of them
the input n is the number of people in line in sorted order
'''
def minimum_swaps(n,new_order):
... |
08d7fd6bd582dc6e98217435f1e8fd56359128cc | sdzr/cookbook_study | /chapter3/scpt3-7.py | 165 | 3.59375 | 4 | # 无穷大和NaN
a = float('-inf')
b = float('inf')
c = float('NaN')
print(a, b, c)
print(a+10)
print(c+10)
import math
print(math.isinf(b))
print(math.isinf(c)) |
b6db70701f6320a230d6b7bbd7e7c01d797fa898 | j717273419/python3_test | /List/List1.py | 365 | 4.34375 | 4 | list = ["a","b",3]
for item in list:
print(item,end=" ")
# print 函数的 end 关键参数来表示以空格结束输出,而不是通常的换行。
# python直接获取集合中的指定信息,组合成一个新的List
list2 = [item for item in list]
print(list2)
list2.append(3)
print(list2)
list3 = [item for item in list2 if item != 3]
print(list3) |
af8abe1e92094c667010b9e8f70284c317441b1d | sakshisangwan/Python-101 | /Basic Practice Code/EvenSum.py | 307 | 4.34375 | 4 | # This program will calculate the sum of all the even numbers upto the given number
a = int(input ("Enter a number "))
result = 0
count = 0
while count <= a:
if count % 2 == 0:
result = result + count
count = count + 1
else:
count = count + 1
print ("Sum of even numbers upto %d is %d" %(a,result)) |
dbc97852fde35eb237baf19cea8b59ac6021d087 | NichHarris/leet-code | /fizzBuzz.py | 954 | 3.671875 | 4 | class Solution(object):
def fizzBuzz(self, n):
"""
:type n: int
:rtype: List[str]
"""
ans = []
for i in range(1,n+1):
if i%5 == 0 and i%3 == 0:
ans.append("FizzBuzz")
elif i%5 == 0:
ans.append("Buzz")
... |
f855f73922f27c7478cc6d79a8dfad5061113021 | emmadeeks/CMEECourseWork | /Week2/Code/dictionary.py | 1,434 | 3.75 | 4 |
#!/usr/bin/env python3
#Author: Emma Deeks ead19@imperial.ac.uk
#Script: dictionary.py
#Desc: Populates a dictionary to map order names to sets of taxa
#Arguments: No input
#Outputs: Completed dictionary
#Date: Oct 2019
""" Populates a dictionary to map order names to sets of taxa """
# Creates a dictionary of ta... |
e17b4a1460d8e5c1c34b35dfcef3ea777dea18bc | XiaoMaoBee/PROJECT2_Bulls-Cows | /PROJECT2_Bulls-Cows.py | 2,217 | 3.734375 | 4 | # muj druhy projekt "Bulls and cows" game
import random
import time
ODDELOVAC = '=' * 56
first_rand = ['1', '2', '3', '4',
'5', '6', '7', '8', '9']
rest_rand = ['0', '1', '2', '3', '4',
'5', '6', '7', '8', '9']
genum = []
a = True
while a:
first = random.sample(first_rand, 1)
rest ... |
28832e1640e11dd68a9837a39f0460caf364adc0 | af94080/dailybyte | /spot_diff.py | 648 | 4.21875 | 4 | '''You are given two strings, s and t which only consist of lowercase letters. t is generated by shuffling the letters in s as well as potentially adding an additional random character. Return the letter that was randomly added to t if it exists, otherwise, return ’ ‘.
Note: You may assume that at most one additional c... |
dc593ab701a573a786ea047dcead804846b1d17e | Yycxj/Python3 | /ex43_classes.py | 1,249 | 3.71875 | 4 |
class Scene(object):
def enter(self):
pass
class Engine(object):
def __init__(self,scene_map):
print (f"really playing {scene_map.start_scene}")
def play(self):
print ("Let's go ~")
def yes_no (self):
while True:
put = input("yes or no >> ")
i... |
00f76fd7697464a7667e86e20d524523ca8ad047 | buxizhizhoum/leetcode | /construct_binary_tree_from_preorder_and_inorder_traversal.py | 1,229 | 4.15625 | 4 | #!/usr/bin/python
# -*- coding: utf-8 -*-
"""
Given preorder and inorder traversal of a tree, construct the binary tree.
Note:
You may assume that duplicates do not exist in the tree.
For example, given
preorder = [3,9,20,15,7]
inorder = [9,3,15,20,7]
Return the following binary tree:
3
/ \
9 20
/ \
... |
79b297a80a219b9715ef818a541ab950cc793c1d | Shrikaran-Kanagaraj/PythonIsEasy | /InstaDataRetriver.py | 683 | 3.65625 | 4 | from instagramy import InstagramUser
name = input("Enter user name:")
user = InstagramUser(name)
followers = user.number_of_followers
print('Total followers:', followers)
following = user.number_of_followings
print('Total followings:', following)
posts = user.number_of_posts
print('Total posts:', posts)
bio = use... |
eb0deedef4a63f7d459e6ae5a9cd7358134018f5 | JBello85/Python-For-Beginners | /main.py | 1,962 | 4.3125 | 4 | # Fundamentals: They are four required fundamentals in any language. Those are called key points. 1. Terms, 2. Actions, 3. Data Types and 4. Best Practices.
# #Data Types
# 1. int (interger. use it for all numbers)
# 2. FloatingPointError
# 3. bool
# 4. Str (String. For all letters)
# 5. list
# 6. tuple
# 7. set
# 8.... |
9bba47e7ddb7756cbc72ece7a3c3f7b885cd66e3 | Pablo784/lab-09-functions | /factorial.py | 135 | 3.828125 | 4 | def factorial(n):
return n * 4 * 2 * 1
userstring = input("Number Please:")
usernum = int(userstring)
print(factorial(usernum))
|
28a8d245a41964266f110f651947959a029625a8 | pradeepmaddipatla16/my_problem_solving_approach_leetcode_medium_hard_problems | /strings/robot_return_to_origin.py | 259 | 3.65625 | 4 | def function1(moves):
x=y=0
for move in moves:
if move=='U':y+=1
elif move == 'D':y-=1
elif move=='R':x+=1
elif move=='L':x-=1
if x==0 and y==0:return True
else:return False
print(function1(['R','L','D','U'])) |
5952e6edacf6ba5745712f235ababd53d460053e | Lazcanof/Py4e | /02_Data_Structures/week_06/Assignment_10_2.py | 1,142 | 4.03125 | 4 | # 10.2 Write a program to read through the mbox-short.txt
# and figure out the distribution by hour of the day for each of the messages.
# You can pull the hour out from the 'From ' line by finding the time and then splitting the string
# a second time using a colon.
# From stephen.marquard@uct.ac.za Sat Jan ... |
5ace5228abb4cf0fec28db9bc78007c5f9641380 | GeneLiuXe/University-Subject-Library | /Numerical-Analysis/Experiment/Ch1/problem1.py | 654 | 3.625 | 4 | import math
def Solution(a, b, c):
x1 = x2 = 0
tmp = b * b - 4 * a * c
if a == 0:
x1 = x2 = -c / b
elif tmp < 0:
print("No solution.\n")
return
else:
tmp = math.sqrt(tmp)
if c == 0:
x1 = (-b + tmp) / (2 * a)
x2 = (-b - tmp) / (2 * a)
... |
f2593a8ea609c4bc0677917e088d919382e8796a | rafaelbarretorb/Robotics-Notebook | /PathPlanning/geometry.py | 1,040 | 3.828125 | 4 | """
geometry elements
"""
import math
class Point(object):
def __init__(self, x, y):
self.x = x
self.y = y
def __eq__(self, other):
return self.x == other.x and self.y == other.y
def __add__(self, other):
return Point(self.x + other.x, self.y + other.y)
def dist(self,... |
63a42499a256db8806784794b402163fd7d5cb36 | yougooo/epam_training | /Python/day_1/test6.py | 247 | 3.59375 | 4 | #!/usr/bin/python
import sys
def polindrom_check(word):
word = word.lower()
word = word.replace(' ','')
return 'YES' if word == word[::-1] else 'NO'
if __name__=='__main__':
word = sys.argv[1]
print(polindrom_check(word))
|
65f01906386543f708d01d2a03e48ee477f1d0c0 | sabzi1984/Intro-to-Algorithms | /dijkstra with linear shortest distance.py | 1,608 | 3.890625 | 4 | # look for shortest distance from the "dist_so_far" dictionary
#and return the closest node
def shortest_dist_node(dist):
best_node = None
best_value = 1000000
for v in dist:
if dist[v] < best_value:
(best_node, best_value) = (v, dist[v])
return best_node
#add all the neighbour nodes... |
31e2183e6a0ad263fff0ce7bb741d41965fc11c8 | bradyz/sandbox | /hackerrank/arraysort/insertionsort.py | 994 | 4 | 4 | import sys
def print_arr(arr):
tmp = ""
for x in arr:
tmp += str(x) + " "
print(tmp)
return
def insertion_sort(a, s):
count = 0
if a == 1:
# print_arr(a)
return count
for x in range(1, s):
while x > 0 and a[x] < a[x - 1]:
tmp = a[x]
... |
f8f11191f4d8e35f01b6feb43c01cb6853e929bb | choroba/perlweeklychallenge-club | /challenge-207/spadacciniweb/python/ch-1.py | 794 | 4.21875 | 4 | # Task 1: Keyboard Word
# Submitted by: Mohammad S Anwar
#
# You are given an array of words.
# Write a script to print all the words in the given array that can be types using alphabet on only one row of the keyboard.
#
# Let us assume the keys are arranged as below:
# Row 1: qwertyuiop
# Row 2: asdfghjkl
# Row 3: z... |
8dccc3a15a95e5d498539b89454a74028324360b | matheuszei/Python_DesafiosCursoemvideo | /0022_desafio.py | 523 | 4.125 | 4 | #Crie um programa que leia o nome completo de uma pessoa e mostre:
#O nome com todas as letras maiúsculas e minúsculas.
#Quantas letras ao todo sem considerar espaços.
#Quantas letras tem o primeiro nome
nome = input('Digite o seu nome completo: ')
print('Maiusculo: {}'.format(nome.upper()))
print('Minusculo: {... |
a7a64beb6f8bf82403924f1222a42524c121d861 | longlizl/python | /guess_number.py | 951 | 3.765625 | 4 | real_num = 25
count = 0
for i in range(10):
if count < 3:
guess_num = input("请输入你猜的数字:").strip() #过滤空格和enter字符
if len(guess_num) == 0:
continue
if guess_num.isdigit(): #判断是否为数字
guess_num = int(guess_num)
else:
print("你需要输入一个真正的数字--")
c... |
e0ce2e01aa22cab32ca4af6fda8ce775a8a94cd1 | microease/Python-Tip-Note | /026ok.py | 342 | 3.84375 | 4 | # 给你一个整数组成的列表L,按照下列条件输出:
# 若L是升序排列的,则输出"UP";
# 若L是降序排列的,则输出"DOWN";
# 若L无序,则输出"WRONG"。
L = [1, 2, 32, 421, 242, 1424, 55353, 312421]
if L == sorted(L):
print("UP")
elif L == sorted(L, reverse=True):
print("DOWN")
else:
print("WRONG") |
6e0b997e88f53d2782c87003d9ae73b917aa99ea | mohitraj/mohitcs | /Learntek_code/25_Sep_18/for4.py | 96 | 3.984375 | 4 | str1 = "What we think we become"
i = 0
for each in str1:
if each== 'e':
i = i +1
print (i) |
c0278c87f8913fd726a6bf9f76f1ac760d574370 | yachiwu/python-training | /backup/loop-basic.py | 183 | 3.953125 | 4 | #while迴圈
#1+2+3+..+10
# n = 1
# sum = 0 #紀錄累加的結果
# while n<=10:
# sum+=n
# n+=1
# print(sum)
#for迴圈
sum = 0
for x in range(11):
sum+=x
print(sum) |
42d6c6be72b0d34e6292238c5d3b9bd25ab69342 | Bmcentee148/PythonTheHardWay | /ex39.py | 1,832 | 4.0625 | 4 | # create a mapping of state to abbreviation
states = {
'Oregon' : 'OR',
'Florida' : 'FL',
'California' : 'CA',
'New York' : 'NY',
'Michigan' : 'MI'
}
cities = {
'CA' : 'San Francisco',
'MI' : 'Detroit',
'FL' : 'Jacksonville'
}
cities['NY'] = 'New York'
cities['OR'] = 'Portland'
#pint ... |
7240e8afe28ed81ca01c1d334f269adeaa89a839 | amlanprakash-403/pfa_amlanprakash | /Exercise 3.py | 1,602 | 4.5 | 4 | #!/usr/bin/env python
# coding: utf-8
# In[2]:
#Write a Python program to check whether the given number is even or not.
num = int(input('Enter the number you want to check for even or odd: '))
if num%2 == 0:
print('The number entered is even', num)
else:
print('The number entered is odd', num)
# In[5]:... |
d0aa610bcaa9be826bc5701d8dd287de9a8b3001 | woongchantonylee/Python-Projects | /Queens.py | 2,233 | 4.0625 | 4 |
# File: Queens.py
# Description: Simulates old queen puzzle and prints out number of possible solutions depending on size of board
# Student Name: Woongchan Lee
# Student UT EID: WL8863
# Partner Name: Dohyun Kim
# Partner UT EID: DK25659
# Course Name: CS 313E
# Unique Number: 85575
# Date Created: 07/12/... |
29b8b8301ad548ab22aa545554aafe7b3d7d5e12 | JamesAUre/First-year-of-python | /PythonSem1/firstproject/week2workshop.py | 442 | 4.15625 | 4 | import random
def coinflip():
heads = 0
tails = 0
unknown = 0
userinput = int(input("How times would you like to flip the coin? "))
for i in range(0,userinput):
x = random.randrange(0, 3)
if x == 0:
heads = heads + 1
elif x == 1: tails = tails + 1
elif... |
fea9c9a4deb9d09218eb3957ed0a74fe7b760609 | DenysZakharovGH/Python-works | /HomeWork4/The_Guessing_Game.py | 624 | 4.15625 | 4 | #The Guessing Game.
#Write a program that generates a random number between 1 and 10 and let’s
#the user guess what number was generated. The result should be sent back
#to the user via a print statement.
import random
RandomVaried = random.randint(0,10)
while True:
UserGuess = int(input("try to guess the nu... |
65c6f5d9baebde5d11a4533c1cb2812032842eea | Khalid-Sultan/Phase-2-Algorithms-Prep | /Leetcode/Stacks,_Queues/2_-_Medium/71._Simplify_Path.py | 867 | 3.703125 | 4 | from collections import deque
class Solution:
def simplifyPath(self, path: str) -> str:
res = ""
buffer = deque()
start = True
l = ""
for i in range(1, len(path)):
if path[i]=='/':
l+='/'
if l=="../":
if buffer: ... |
da543c6294648d4b472ea1560d9e4e135673700c | sanju5445/python_program.github.io | /class_abstrac&encap6.py | 1,148 | 3.796875 | 4 | class Employee:
company_name='TCS'
def __init__(self,name,role,salary):
self.name=name
self.role=role
self.salary=salary
def speak(self):
return f"hi i am {self.name} , i am {self.role}, and my salary is {self.salary}"
@staticmethod
def fn():
return "thanks fo... |
3e0d97320d3da96e13c880132a1b53c7aa587630 | tonberarray/datastructure-and-algrorithm | /线性表操作/链表/双向链表.py | 2,168 | 3.984375 | 4 | # dual_link_List 双向链表
class DualNode(object):
"""docstring for DualNode"""
def __init__(self, val=None):
self.val = val
self.prior = None
self.next = None
self.visited = False
class DualLinkList(object):
"""docstring for DualLinkList"""
def __init__(self):
self.head = None
def createList(self,num):... |
749a57cbdd0b86c771968c279fa9b6e2a7844feb | lockmachine/DeepLearningFromScratch | /ch05/buy_apple_orange.py | 1,307 | 3.5 | 4 | #!/usr/bin/env python
# coding: utf-8
from layer_native import *
apple = 100
apple_num = 2
orange = 150
orange_num = 3
tax = 1.1
mul_apple_layer = MulLayer()
mul_orange_layer = MulLayer()
add_apple_orange_layer = AddLayer()
mul_tax_layer = MulLayer()
apple_price = mul_apple_layer.forward(apple, apple_num)
orange_pr... |
f6ce5644a852f6583c217ad10015290c4a36d62d | DFTFFT/DoublePendulum | /double_pendulum.py | 3,149 | 3.625 | 4 | # solve the ODEs for double-pendulum problem
import numpy as np
from scipy import sin, cos
from scipy.integrate import odeint
import matplotlib.pyplot as pl
class DoublePendulum(object):
"""Define the double pendulum class"""
def __init__(self, m1, m2, l1, l2):
self.m1, self.m2, self.l1, self.l2 = m1,... |
65d366849476615b466110774c06a282f9eba1c9 | shinhermit/simple-regression-demo | /plot_3_lines_crossing_2d.py | 2,169 | 4.0625 | 4 | """
Plot side by side:
- 3 lines all crossing at 1 point
- 3 lines crossing no more at a single point
after a slight change in 1 parameter
Used to illustrate the section "Limits of an algebraical solution"
of the first article about linear regression.
"""
import numpy
from matplotlib import pyplot
from equations im... |
fb6634d75cca3515e5ceb08419ea3f37cbd58784 | MinjeongKim98/Team4 | /week2/20171592-김병관-assignment2.py | 472 | 3.875 | 4 | num = 0
test = 0
while True:
try:
fnum = float(input('input number:'))
if fnum % 1 != 0: continue
if fnum < 0:
if fnum == -1: break
else: continue
hi = 1
num = int(fnum)
... |
833cac5dcc2b3c26de3cde9b452a900700a84f25 | paulburnz314/Top_ten_python_tricks | /lab_data_qualifiers.py | 1,283 | 3.5625 | 4 | ''' When you get a lab report the results somestimes have qualifiers such
as '>' or '<' the method detection limit or practical quantitation limit.
If you need to use this number in a calculation you will need to strip any
non numeric characters. Most likely you will get data from an excel or csv
file.
'''
... |
92dcf694068b868170d43b5b328bd8d5e91e653e | feliksce/euler | /prob2.py | 862 | 4.09375 | 4 | # Even Fibonacci numbers
# Problem 2
#
# Each new term in the Fibonacci sequence is generated by adding the previous two terms. By starting with 1 and 2, the first 10 terms will be:
#
# 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...
#
# By considering the terms in the Fibonacci sequence whose values do not exceed four million,... |
7c7765949ca08d4c6ed082247883a19f1992fdb6 | andrefacundodemoura/exercicios-Python-brasil | /exercicios_python_brasil/lista02_estrutura_de_decisao/ex02verifica_num.py | 313 | 4.03125 | 4 | '''
02. Faça um Programa que peça um valor e mostre na tela se o valor é positivo ou negativo.
'''
num = float(input('Digie um valor qualquer: '))
if num < 0:
print(f'O numero digitado [{num}] é negativo.')
elif num == 0:
print('0 é nulo')
else:
print(f'O numero digitado [{num}] é positivo.')
|
a812bac1c1bc91d3b9b6a4968b2d6fa69a19dde2 | vivekjaiswal90/datascience | /game python/keyboardmove.py | 2,334 | 4.375 | 4 | # Sample Python/Pygame Programs
# Simpson College Computer Science
# http://programarcadegames.com/
# http://simpson.edu/computer-science/
import pygame
black = (0,0,0)
white = (255,255,255)
# This class represents the bar at the bottom that the player controls
class Player(pygame.sprite.Sprite):
# -- Attributes
# S... |
ee14cfc30a7d9f4c8bf99f7d90beeb688f912929 | betty29/code-1 | /recipes/Python/65126_Dictionary_of_MethodsFunctions/recipe-65126.py | 450 | 3.78125 | 4 | import string
def function1():
print "called function 1"
def function2():
print "called function 2"
def function3():
print "called function 3"
tokenDict = {"cat":function1, "dog":function2, "bear":function3}
# simulate, say, lines read from a file
lines = ["cat","bear","cat","dog"]
for line in lines:
... |
f07b36a7bfef734419ded09925cf3b4ae23c8bb5 | UWPCE-PythonCert-ClassRepos/Self_Paced-Online | /students/patchcarrier/Lesson04/mailroom2.py | 5,801 | 3.796875 | 4 | #!/usr/bin/env python3
donors = {"Conrad Anker":[550, 1200, 0.02],
"Tommy Caldwell":[600.50, 80],
"Margo Hayes":[200, 550.50],
"Alex Honnold":[0.01],
"Paige Claassen":[750, 800, 150.25]}
def prompt_user(prompt, acceptable_vals):
"""Prompt the user for an input until the... |
764c3d6a87619731b390b0360658e0e98bc8c704 | naderalexan/sexy-python | /single_truthy_value.py | 321 | 4.03125 | 4 | """
Using iterators to check for one and only one truthy in a list
"""
def single_truthy_val(arr):
my_iter = iter(arr)
return any(my_iter) and not any(my_iter)
if __name__ == "__main__":
arr = [0, 1, 0, 0]
assert single_truthy_val(arr)
arr = [0, 1, 0, 0, 1]
assert not single_truthy_val(arr)... |
a0bfb18e42b74794b86310438b45978df6f62fa5 | twothicc/Algorithms | /sorting_techniques.py | 24,350 | 3.796875 | 4 | import random
import time
import math
def test(ftn, xs) :
start = int(time.time() * 1000)
ftn(xs)
end = int(time.time() * 1000)
print("Time taken using {0} on list size {1} is {2}".format(ftn.__name__, len(xs), end - start))
def counting_sort_test(ftn, xs, xs_range) :
start = int(time.time() * 1000)... |
f5abaa4d8485ffa0a1d3593df6293dca6f712e8d | roveryi/LeetCode-Practice | /P39.py | 1,737 | 3.59375 | 4 | '''
39. Combination Sum
Given a set of candidate numbers (candidates) (without duplicates) and a target number (target), find all unique combinations in candidates where the candidate numbers sums to target.
The same repeated number may be chosen from candidates unlimited number of times.
Note:
All numbers (includi... |
be8f19a8e036c15f516b03e24dff1d1c368a8923 | TitanLi/openCV | /read.py | 718 | 3.65625 | 4 | # -*- coding: UTF-8 -*-
import numpy as np
import cv2
img = cv2.imread('apple.jpg')
# 圖片讀取
# 會儲存成一個 NumPy 的陣列
print type(img)
# NumPy 陣列的大小
#(RGB 彩色圖片的 channel 是 3,灰階圖片則為 1)
print img.shape
# 此為預設值,這種格式會讀取 RGB 三個 channels 的彩色圖片,而忽略透明度的 channel
imgColor = cv2.imread('apple.jpg',cv2.IMREAD_COLOR);
print imgColor.sha... |
1702d95e4f9fc22ffcc97c5fb9054811018c1406 | nymul-islam-moon/Massage-Encrypt | /main.py | 861 | 3.578125 | 4 | #phthon Massage encryption
import sys
while(True):
option = input("Enter Your Option : ")
if "encrypt" in option or "decrypt" in option:
massage = input("Enter The Massage : ")
key = int(input("Enter The Key : "))
file1 = "QAZWSXEDCRFVTGBYHNUJMIKOLPabcdefghijklmnopqrstuvwxyz\ 123456... |
c4935acf1351e07fd0393de2f75cb144dd6070d6 | jianengli/leetcode_practice | /jianzhi_offer/66.py | 2,350 | 3.546875 | 4 | # -*- coding:utf-8 -*-
import collections
class Solution:
def movingCount(self, threshold, rows, cols):
# write code here
self.row, self.col = rows,cols
self.dict=set()
self.search(threshold,0,0)
return len(self.dict) # 求满足题意要求(if not self.judge(threshold, i, j) or (i,j) in s... |
48db1f84c21cf83562bd874af7e13d23f4b2cdb9 | jshartshorn/genome | /python/lib/genome/quality.py | 759 | 4.0625 | 4 | #!/usr/bin/env python
def qual_str_to_codes(qual_str):
"""Converts a string of space-delimited quality values to an
ascii string representation, where the ascii value of each character
is the quality value"""
return "".join([chr(int(x)) for x in qual_str.split(" ")])
def qual_codes_to_str(qual_codes... |
4d4218064e9cd2320068cc8af78172ca5902cb2b | ugauniyal/sort_algorithms | /bubble_sort.py | 293 | 3.859375 | 4 | def bubble_sort(input):
size = len(input)
for i in range(len(input) - 1,0,-1):
for j in range(i):
if input[j] > input[j+1]:
input[j], input[j+1] = input[j+1], input[j]
else:
j = j+1
return input |
08be7dd05738523d67903d32f02ff34b3dc43ae9 | codingWithAndy/Thesis_Project | /Code/Project/views/svmgameboard.py | 5,074 | 3.515625 | 4 | import numpy as np
from random import randint
from sklearn import svm, datasets
from PyQt5.QtWidgets import *
import matplotlib
import matplotlib.pyplot as plt
from matplotlib.backends.backend_qt5agg import FigureCanvas, FigureCanvasQTAgg
from matplotlib.figure import Figure
matplo... |
5b40804765c6aeba313bfe30f5ea9e63f29e9ba2 | jkxruby/IntroductionToAlgorithms | /src/6.3-1.py | 2,312 | 3.515625 | 4 | # -*- coding:utf-8 -*-
__author__ = 'haoxiang'
def minHeapify(A,length,i):
smallest = i
left = 2*i
right = 2*i+1
if left<= i and A[left]<A[smallest]:
smallest = left
if right<=i and A[right]<A[smallest]:
smallest = right
if smallest!=i:
temp = A[i]
A[i] = A[small... |
b3bb37e56b85d415c84e6c96096f4541cbc0995f | gceylan/pro-lang | /piton/stringtools.py | 2,096 | 4.15625 | 4 | #!/usr/bin/env python
#-*- coding: utf-8 -*-
def reverse(s):
"""
>>> reverse('happy')
'yppah'
>>> reverse('Python')
'nohtyP'
>>> reverse("")
''
>>> reverse("P")
'P'
"""
return s[::-1]
def mirror(s):
"""
>>> mirror("good")
'gooddoog'
>... |
180c51f638ac92c8e136a2f0c2fd59e8c958a305 | yychuyu/LeetCode | /problems/0498_Diagonal_Traverse/Elon.py | 1,057 | 3.546875 | 4 | class Solution:
def findDiagonalOrder(self, matrix: List[List[int]]) -> List[int]:
'''find diagonal'''
if not matrix:
return []
m = len(matrix)
n = len(matrix[0])
signal = 1
if m > n:
matrix = list(zip(*matrix))
m, n = n, m
... |
996a9039dbbef12a7fa538849527ebf70e2a2051 | k0malSharma/Competitive-programming | /FLOW006.py | 137 | 3.671875 | 4 | for _ in range(int(input())):
a=int(input())
s=0
while(a>0):
s+=int(a%10)
a=int(a/10)
print(int(s))
|
686f6174afefd051a3fb13214c0c7362b3ab4080 | criptik/puzcorner | /gui/turtle/tubouncer.py | 17,981 | 3.65625 | 4 | # import TK
import sys
import time
import turtle
from random import *
import math
from abc import ABC, abstractmethod
global dbg
dbg = False
def dbgprint(*args):
global dbg
if dbg:
print(args)
def vectorEnd(x1, y1, ang, len):
angrad = math.radians(ang)
angcos = math.cos(angrad)
angsin ... |
dd4ee2e4035fb5a01ddd31f9e0f7f589c677df10 | Sedrak-Khachatryan/BasicITCenter | /Homework/Homework_04/Xndir_647.py | 71 | 3.578125 | 4 | n=input("")
if n==n[::-1]:
t=True
else:
t = False
print(t) |
7da38bba841992c65d71c78ca7e2722dbeff4091 | Avangarde2225/pyththonWithBeatifulSoup | /pythonDataAnalysis/classesAndObjects/student.py | 1,214 | 4 | 4 |
file_name = "data.txt"
# f = open(file_name)
# # f_content = f.readline() #reads only the firstline of the file
# # f_content = f.read() #reads all the lines
#
# for line in f:
# print(line.strip())
# f.close()
def prep_record(line):
line = line.split(":")
first_name, last_name = line[0].split(",")
... |
00c5706c656062e7f9118fbb7210c49b4ed6bfca | dulcetlife/Larsen_CSCI3202_Assignment1 | /Larsen_Assignment1.py | 4,446 | 4.21875 | 4 | #CSCI 3202 Assignment 1
#Henrik Larsen
#Github username: dulcetlife
#Github repo: https://github.com/dulcetlife/Larsen_CSCI3202_Assignment1
#Written in Python 3
import Queue
#Queue class
#Using a list to store all the integers
class Queue(object):
def __init__(self):
self.list = []
def enqueue(self, x):
sel... |
2b9ec29039f1d45c042900d6d9c201917f5078f9 | santiagoom/leetcode | /solution/python/120_Triangle_3.py | 694 | 3.6875 | 4 |
from typing import List
from utils import *
class Solution_120_Triangle_3:
def minimumTotal(self, triangle: List[List[int]]) -> int:
below_row = triangle[-1]
n = len(triangle)
for row in reversed(range(n - 1)):
curr_row = []
for col in ra... |
cc7d018e72ff82a8a7038d7bff5632701587df26 | adamsfrancis/Python | /BaseConversion/getInput.py | 501 | 3.796875 | 4 | class numToConvert():
def __init__(self, numberInput, numberBase, convertNumber):
self.ni = numberInput
self.nb = numberBase
self.cn = convertNumber
def main():
numberInput = int(input('Please enter an integer: '))
numberBase = int(input('Please input the starting base(10,8,6,2): ')... |
ec754747f0ac8e1b3167dd288c14c54c84f67fbe | gajo357/IntroToAlgorithms | /Week7/FeelTheLoveModule.py | 3,602 | 3.90625 | 4 | import unittest
import copy
from DijkstraHeapModule import dijkstra_shortest_path
#
# Take a weighted graph representing a social network where the weight
# between two nodes is the "love" between them. In this "feel the
# love of a path" problem, we want to find the best path from node `i`
# and node `j` where the s... |
0812e326660e46021982afc5b51da0add726de96 | dig017/ubiquitous-daniel | /functions.py | 4,341 | 4.09375 | 4 | import string
import random
def creditcard(number):
"""This function checks a True Credit Card by verifying that the input is an integer and subsequently checks if that
input's length is 16 characters.
Parameters:
-----------
number: list
list of strings, for it to run the first stri... |
18270df81a3a64222cb45e3161b2dd7043ab303e | okwesi/machine-learning | /traintestsplit/KNN.py | 1,144 | 3.515625 | 4 | import numpy
import numpy as np
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn import neighbors, metrics
from sklearn.preprocessing import LabelEncoder
import matplotlib.pyplot as plt
#READING THE DATA
data = pd.read_csv('car.data')
#print(data)
X = data[[
... |
c4d56459e8f0bf152f2c685b93026b63586178cf | nmyeomans/Nivelacion_Python | /21082019/000858.py | 957 | 4.25 | 4 | # En esta ocasion vamos a cambiar de lugar los parametros de una lista
# para eso vamos a generar variables seleccionando un parametro especifico de la lista
# la forma siguiente es mas larga de lo normal pero es utilil para cambiar de orden en una lista
goleador=["Hans", "Nicolas", "Matias"]
ordenar=goleador[0] ... |
3ddaa21b632d73c1b1872a89a72a66f1c35895ee | trevor-ofarrell/holbertonschool-higher_level_programming | /0x04-python-more_data_structures/9-multiply_by_2.py~ | 158 | 3.75 | 4 | #!/usr/bin/python3
def multiply_by_2(a_dictionary):
newd = {}
newd = a_dictionary.copy()
for key in newd:
newd[key] *= 2;
return newd
|
2f7a53bc82bec0b4a2556c471a3a93d6d8f004cb | beginOfAll/base_study | /leetcode/88_MergeSortedArray.py | 936 | 3.546875 | 4 | class Solution:
def merge(self, nums1, m, nums2, n):
"""
:type nums1: list[int]
:type m: int
:type nums2: list[int]
:type n: int
:rtype: void Do not return anything, modify nums1 in-place instead.
"""
temp = {}
count = 0
if m == 0:
... |
0c609d60dac2a42fd979999c15db1ebdeaedfb84 | YujiaY/leetCodePractice | /LeetcodePython3/q0143.py | 966 | 4 | 4 | #!/usr/bin/python3
from typing import List
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
class Solution:
def reorderList(self, head: ListNode) -> None:
"""
Do not return anything, modify head in-place instead.
"""
if hea... |
61400eb94c6b0302b2ec1644793a1e5aa8d44bf9 | PaLaMuNDeR/algorithms | /Coding Interview Bootcamp/08_array_chunk.py | 1,427 | 4.09375 | 4 | import timeit
import operator
""" Given an array and chunk size, divide the array into n amount of sub-arrays
Examples:
chunk([1,2,3,4],2) -> ([1,2],[3,4])
chunk([1,2,3,4,5],2) -> ([1,2],[3,4],[5])
chunk([1,2,3,4,5,6,7,8],3) -> ([1,2,3],[4,5,6],[7,8])
chunk([1,2,3,4,5],4) -> ([1,2,3,4],[5])
chunk([1,2,3,4,5],10... |
142b93ee4184e6eff8a84d217ad397ae1cbf674f | Robert0306/dailyprogrammer | /expandNumbers.py | 559 | 4.09375 | 4 | # script to find the expanded number form.
def expandedNumber(num):
answer = []
divide = 10
# using 10 to divide the int.
while divide < num:
# modulo helps us find the number we need to work with.
rest = num % divide
if rest != 0:
answer.insert(0, str(rest))
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.