blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
a65a63dbf315a5418b1cf31d9fab66c8293d2e1a | huitianbao/Python_study | /exe3version3/18/test/4/test1.py | 299 | 3.5625 | 4 | # 4.已知 a = [1,2,3,6,8,9,10,14,17],请将该list转换为字符串,例如 '123689101417'.
a = [1,2,3,6,8,9,10,14,17]
str_a=[]
for k in a:
str_a.append(str(k))
print(str_a)
def list_to_string(x):
sum=''
for kk in x:
sum=sum+kk
return sum
print(list_to_string(str_a)) |
b97e1d84577a471b9296ee616563ec585b85cc4e | huitianbao/Python_study | /ex2/03_string/exe/exe1.py | 342 | 4.34375 | 4 | #coding:utf8
import re
# 1 字符串:
#
# a = 'abcd'
#
# 用2个方法取出字母d
a='abcd'
r=r'd'
print a[-1]
print a[len(a)-1]
print a[3]
print re.findall(r,a)
# 2:
#
# a = 'jay'
#
# b = 'python'
#
# 用字符串拼接的方法输出:
#
# my name is jay,i love python.
a='jay'
b='python'
print "my name is %s,i love %s." % (a,b)
|
5c58870de842923ec900807b867131c6c0b231e2 | huitianbao/Python_study | /ex2/09_list_exercises/05/list_01.py | 149 | 3.65625 | 4 | #coding:utf8
# 一: 已知:元组 a = (1,2,3) 利用list方法,输出下面的结果:
#
# (1,2,4)
a=(1,2,3)
b=list(a)
# print b
b[2]=4
print b
|
6a508839ec61229f14b4ea837b40acf71db79acf | huitianbao/Python_study | /ex2/09_list_exercises/02/list2.py | 154 | 3.515625 | 4 | #coding:utf8
# a = [1,2,3]
# b = [4,5,6]
#
# 用2个方法输出下面结果:
#
# [1,2,3,4,5,6]
a = [1,2,3]
b = [4,5,6]
print a+b
a.extend(b)
print a
|
824d6a3345594cda8bbe720710f78664531e9820 | huitianbao/Python_study | /exe3advanced/09_function_exercises/first.py | 329 | 3.859375 | 4 | #coding:utf8
'''
1.定义一个func(name),该函数效果如下。
assert func("lilei") = "Lilei"
assert func("hanmeimei") = "Hanmeimei"
assert func("Hanmeimei") = "Hanmeimei"
'''
def func(name):
return str.capitalize(name)
print(func('fffffff'))
assert func('lilei')=='Lilei'
assert func("hanmeimei") == "Hanmeimei"
|
54a0e6e7f854048c11de60e1523eb2e7f12cd652 | huitianbao/Python_study | /ex1/04_areaAndC/Rectangle.py | 158 | 4.09375 | 4 | length=float(raw_input("length is :"))
width=float(raw_input("width is :"))
print "the area is "
print length*width;
print "the c is "
print 2*length+2*width |
404b0f0d0bf689994f3bafe83bc62e4dc7a2d2ce | huitianbao/Python_study | /exe3advanced/04/fouth.py | 997 | 3.703125 | 4 | #coding:utf8
'''
4 定义一个方法get_funcname(func),func参数为任意一个函数对象,需要判断函数是否可以调用,如果可以调用则返回该函数名(
类型为str),否则返回 “fun is not function"。
'''
def test_fun():
print('hello')
return 1
def get_funcname1(funcc):
'''
func参数为任意一个函数对象,需要判断函数是否可以调用,如果可以调用则返回该函数名(
类型为str),否则返回 “fun is not function"
'''
if callabl... |
6a04a07671c993eed96f0bd431023521bf19b096 | TiagoHMSilva/Python | /Cifra Cesar/main.py | 639 | 4 | 4 | """
In cryptography, a Caesar Cipher, also known as an exchange cipher, Caesar code or Caesar exchange, is one of the
simplest and most encryption techniques. It is a type of substitution cipher in which each letter of the text is
replaced by another, which appears in the alphabet below it a fixed number of times.
"""
... |
1303da295dcc5933427501c7d10a017bd6cf945b | iamparul08/Data-Structures | /arrays2.py | 523 | 4.3125 | 4 | #python code to demonstrate pop() and remove()
#importing "array" for array
import array
arr = array.array('i', [1, 2, 3, 1, 5])
#printing original array
print("The new created array: ", end=" ")
for i in range(0, 5):
print(arr[i], end=" ")
print("\r")
#using pop() to remove element at 2nd position
pr... |
1c32833b9c6a8b9affc36e7e430b3ffb6cd84994 | YuzhongHuang/DataScience16CYOA | /utils.py | 8,058 | 4.0625 | 4 | # functions definition for length data operation
def createLowerWordList(line):
"""
Given a line of string, seperates
the string into lower case word and
get rid of punctuations and numbers
"""
# get a splited words list and an empty list
wordList1 = line.split()
wordList2 =[]
# lo... |
79603efffdff0a6dc7b1937205fc7545d92de6e3 | abelardopardo/ontask_b | /ontask/django_auth_lti/timer.py | 623 | 3.84375 | 4 |
import time
class Timer:
def __init__(self, verbose=False):
self.verbose = verbose
def __enter__(self):
self.start = time.time()
return self
def __exit__(self, *args):
self.end = time.time()
self.secs = self.end - self.start
self.msecs = self.secs * 1000 ... |
afb24641b495e81e5118b281d73419e80c83b222 | fortee/halite_iii | /dijkstra.py | 5,028 | 3.671875 | 4 | import heapq
import logging
import time
from hlt.game_map import Position
from simple_graph import Graph
from typing import List
def dijkstra(graph, src, dest):
"""
Originally I started following Skiena's implementation of Dijkstra's algorithm, but it wasn't quite what I wanted.
I'm not sure if this tec... |
bc43dad893eecfa6e6aa635197e40bfe164d63e8 | Nkzono99/emses_inp_generator | /src/utils/units.py | 4,662 | 3.5 | 4 | class UnitTranslator:
def __init__(self, from_unit, to_unit, name="None"):
self.from_unit = from_unit
self.to_unit = to_unit
self.ratio = to_unit / from_unit
self.name = name
def set_name(self, name):
self.name = name
return self
def trans(self, value, rever... |
beda00a5904fb449481d3448c436b9ea7a8ff9bf | Justin-DNF/RockPaperScissors | /Rock Paper Scissors.py | 887 | 3.984375 | 4 | # Rock Paper Scissors
# Justin D
# 10/27/2020
# Filename: Rock Paper Scissors.py
from random import randint
print("Type: Rock, Paper, or Scissor")
player = input()
computer = randint(0,2)
if computer == 0:
computer = "Rock"
if computer == 1:
computer = "Paper"
if computer == 2:
computer = "Sci... |
d4503854d15b2d427390b7d6a418e87fb88ebd27 | christinamtong/poli178 | /stripData.py | 5,819 | 3.671875 | 4 | # ###############################
#
# Input: path to file in the csv format given by the world bank.
# In the .csv file, you must manually delete all the rows before
# the country data begins (including the row with dates).
#
# Output: csv file with rows for high income OECD, high income non-OECD,
# countries with sim... |
a16e408b4c80997b48b96423ae57bfd4d95c7b94 | rjsilvestre/python-sundry | /make-greeting-closure.py | 1,164 | 4.21875 | 4 | # Closures test file. Creates a simple function that creates returns
# another function. The purpose is to store a string to be used as a
# greeting by the returned function. Example based on the programiz
# website.
def make_greeting(greeting):
"""A function that creates greeting functions."""
def greet(nam... |
72a83ee644a794f1abb9bce9a9fc0bdc2c806a74 | rjsilvestre/python-sundry | /edx-mitx-6.00.2x/edx-mitx-6.00.2x-fex02_01-pset-two-bags.py | 2,210 | 4.09375 | 4 | # Write a generator that returns every arragement of items such that is in one
# or none of two different bags. Each comination should be given as a tuple of
# two lists, the first being the items of bag 1 and the second being of items of
# bag 2.
import random
# Classes and functions provided by the course.
class I... |
9fb523fea3a3c4e3e666f514ea5836a6a04b9f2b | rjsilvestre/python-sundry | /edx-mitx-6.00.2x/edx-mitx-6.00.2x-midterm-exam/midterm-max-contig-sum.py | 454 | 3.890625 | 4 | def max_contig_sum(L):
""" L, a list of integers, at least one positive
Returns the maximum sum of a contiguous subsequence in L """
best_sum = 0
for i in range(len(L)):
for j in range(i+1, len(L)+1):
if sum(L[i:j]) > best_sum:
best_sum = sum(L[i:j])
return best_... |
17c8aca8978f2ee1ec9cdab1373791027313ae19 | rjsilvestre/python-sundry | /edx-mitx-6.00.2x/edx-mitx-6.00.2x-fex08_04-non-replacement-balls.py | 953 | 3.90625 | 4 | import random
def noReplacementSimulation(numTrials):
'''
Runs numTrials trials of a Monte Carlo simulation
of drawing 3 balls out of a bucket containing
3 red and 3 green balls. Balls are not replaced once
drawn. Returns the a decimal - the fraction of times 3
balls of the same color were dra... |
1ff9b8f582dd0c944a5ad0f051fdb6a139026559 | rjsilvestre/python-sundry | /edx-mitx-6.00.1x/edx-mitx-6.00.1x-pset02_03-cc-pay-debt-year-bisection.py | 1,266 | 4.40625 | 4 | # Program that calculates the minimum fixed monthly payment
# needed in order pay off a credit card balance within 12 months.
# A fixed monthly payment is a single number which does not
# change each month, but instead is a constant amount that
# will be paid each month.
# This version uses bisection search to find... |
421e7b9867b6affbe7fc59030e9876bf57094032 | gabrielCaio/onlineJudgesAnswers | /Uri/Module 1/1010.py | 227 | 3.546875 | 4 | code1, num1, valuePiece1 = input().split()
code2, num2, valuePiece2 = input().split()
value1 = int(num1) * float(valuePiece1)
value2 = int(num2) * float(valuePiece2)
print("VALOR A PAGAR: R$ {:.2f}".format(value1 + value2))
|
8245b08dc035e3839598981e61f96648fe2e9ca5 | gabrielCaio/onlineJudgesAnswers | /Uri/Module 1/1013.py | 219 | 3.890625 | 4 | e1, e2, e3 = input().split()
a = int(e1)
b = int(e2)
c = int(e3)
def greater(a, b):
temp = (a + b + abs(a - b))
return temp / 2
m = greater(a, b)
maior = greater(m, c)
print("{} eh o maior".format(int(maior))) |
62200aae1e68584dbc048134be63cf2dbc2b0bba | gabrielCaio/onlineJudgesAnswers | /TheHuxley/Python/691.py | 203 | 4.0625 | 4 | def greater(num1, num2):
if num1 < num2:
print("{0} {1}".format(num1, num2))
else:
print("{0} {1}".format(num2, num1))
num1, num2 = input().split()
greater(int(num1), int(num2)) |
3856394719760dd9bf5515f936fd8b615df9e18f | html-3/practice | /ReverseString/testset.py | 427 | 3.609375 | 4 | from function import ReverseString
# hypothetical list to test the function
testset = [
"Hello World",
"Coderbyte",
"12345",
"above\nbelow"
]
# Correct Outputs
# dlroW olleH
# etybredoC
# 54321
# woleb
... |
8232ca1775345a4b5f525df18427cb594dba4cb3 | html-3/practice | /PalindromicSubstring/testset.py | 409 | 3.515625 | 4 | from function import PalindromicSubstring
# hypothetical list to test the function
testset = [
"abcdefgg",
"dogcatfish",
"1331",
"aracecar"
]
# Correct Outputs
# none
# none
# 1331
# racecar
... |
faa1ba71e81c88e17084e06c64e9323521383d05 | Romanmc72/kill_spikey_guy | /spikey_functions.py | 5,960 | 3.578125 | 4 | #!/usr/bin/env python3
"""
Storing some reusable functions here.
"""
import pygame as pg
import math as m
def get_offset(original, changed):
"""
:param original:
The original must be a pygame surface,
and it will be the object whose center
is the reference point for the offset
:par... |
a8d1ffe3109057da682a4ba466b163af5e015d99 | Bernie1990/CodilityLessons | /Lesson6-sorting/Distinct/mySol.py | 283 | 3.515625 | 4 | # you can write to stdout for debugging purposes, e.g.
# print("this is a debug message")
def solution(A):
# write your code in Python 3.6
D = {}
ret = 0
for i in range(len(A)):
if A[i] not in D:
D[A[i]] = 1
ret += 1
return ret
|
d15e07b50dda79550a1aa02db8ace2bb9419db36 | MusikPolice/Fretboard | /app.py | 2,463 | 4.3125 | 4 | # Dictionary of musical notes. The key is name of the note, the value is a zero-based numerical index
notes = {'C':0, 'C#':1, 'D':2, 'D#':3, 'E':4, 'F':5, 'F#':6, 'G':7, 'G#':8, 'A':9, 'A#':10, 'B':11}
# The reverse of notes, such that integer index is key and note name is value
indices = dict((v, k) for k, v in notes... |
8401b42eb41b8fe22b974df8b614285b904dc39a | p-tai/udacity-fullstack | /project2-tournament_results/vagrant/tournament/tournament.py | 6,854 | 3.90625 | 4 | #!/usr/bin/env python
"""
tournament.py -- implementation of a Swiss-system tournament.
This python program \will connect to PostgreSQL database
named tournament to perform any database updates.
"""
import psycopg2
from random import randrange
def connect():
"""Connect to the PostgreSQL database named 'tourname... |
aec8548892dfbc5542915b4e808048f46225d88d | marvinxu99/pyqt5-learn | /center_screen.py | 1,473 | 4.0625 | 4 | #!/usr/bin/python3
# -*- coding: utf-8 -*-
"""
ZetCode PyQt5 tutorial
This program centers a window on the screen.
Author: Jan Bodnar
Website: zetcode.com
Last edited: August 2017
"""
import sys
from PyQt5.QtWidgets import QWidget, QDesktopWidget, QApplication
class Example(QWidget):
def __init__(self... |
19e444c5a65775b6214ac1e8426328eaf18db6b0 | alei-num1/Git-hub | /Practice-program/Program 11.py | 399 | 3.703125 | 4 | # 判断101-200之间有多少个素数,并输出所有素数。
# 想法一
count = 0
leap = 1
from math import sqrt
for m in range(101, 201):
k = int(sqrt(m))
for i in range(2, k + 1):
if m % i == 0:
leap = 0
break
if leap == 1:
count += 1
print("%d" % m)
leap = 1
print("There are %d numbers t... |
ac21f27cc3241440b53560ff947a727079a7e2b2 | alei-num1/Git-hub | /Git-hub/the 4th.py | 303 | 3.90625 | 4 | # 一.已经字符串 s = "i,am,li_lei",请用两种办法取出之间的“am”字符。
# plan 1
# s = "i,am,li_lei"
# print(s[2:4])
# tem = list(s)
# print(tem)
# plan 2
s = "i,am,li_lei"
list1 = s.split(',')
# print(type(list1))
print(list1[1])
# 二.在python中,如何修改字符串?
|
878dd760455066fc384e038e9fff9934d4b5e1fb | alei-num1/Git-hub | /beans/fish.py | 806 | 3.828125 | 4 | class Fish:
def __init__(self, name, color, age, weight):
self.name = name
self.color = color
self.age = age
self.weight = weight
def swim(self):
print("The fish %s is swimming." % self.name)
def introduce(self):
print("I'm %s, my body is %s, and I'm %d year... |
be2aef92312f4b84fc78a51d57ea66a29258bf01 | prashant60/Data-Structures | /Reverse_Linked_List.py | 1,398 | 3.984375 | 4 | class Node:
def __init__(self,data,next):
self.data=data
self.next=next
class linked:
def __init__(self):
self.head=None
self.head2=None
def create(self,lst):
if self.head is None:
self.head=Node(lst[0],None)
for i in range(1,len(lst)):
... |
0cd61714dde7ec5ea7bf8d4d01d59ec771aa0856 | CarterWS/Summer2020 | /LabVIEWCode/Servers/Prime_Docs/spike Examples/color_get_color.py | 420 | 3.84375 | 4 | from spike import ColorSensor
# Initialize the Color Sensor.
paper_scanner = ColorSensor('E')
# Measure the color.
color = paper_scanner.get_color()
# Print the color name to the console
print('Detected:', color)
# Check if it is a specific color
# Values: 'black','violet','blue','cyan','green','yellow','red','whit... |
ad502d2b0dcca053dc4a8f524ec6fc63ea7d0e58 | CarterWS/Summer2020 | /PythonCode/Huzzah/Examples/Dipesh/02LightUpLED.py | 620 | 4.15625 | 4 | #LED on and off
#Connect the negative terminal of LED to ground and the positive terminal to Pin 12
#Use a Resistor
import machine, time #import library
ledRed = machine.Pin(12, machine.Pin.OUT) #connect an LED on Pin 12, declare the pin as output
#ledRed.off() #will turn off the LED
ledRed.on() #will turn on L... |
d264decbe2af49038a2ed24eb89c833aac3b695f | amitahire/3dml | /E1/e1/implicit_function.py | 2,769 | 3.765625 | 4 | """Definitions for Signed Distance Fields"""
import numpy as np
def signed_distance_sphere(x, y, z, r, x_0, y_0, z_0):
"""
Returns the signed distance value of a given point (x, y, z) from the surface of a sphere of radius r, centered at (x_0, y_0, z_0)
:param x: x coordinate(s) of point(s) at which the S... |
fdecdae7fae1972e466c410c5bff1e2822ccdfc3 | mustafaalby/OpenCVTrainings | /DrawingWritingOnImage.py | 692 | 3.53125 | 4 | import cv2
import numpy as np
def main():
img = cv2.imread('testImage.jpg', cv2.IMREAD_COLOR)
img[60:100, 300:550] = [255, 255, 255]
cv2.line(img, (0, 0), (120, 90), (255, 255, 0), 20)
# draw a line(image, starting point, finish point, rgb color, line thickness)
cv2.rectangle(img, (5, 20), (200, 2... |
a77aa27e1c3ebc7cb08c6a9f7346873d5807f03d | CFBerryhill/Konane | /gameboard.py | 7,299 | 3.78125 | 4 | from copy import copy
class Directions:
NORTH = 'North'
SOUTH = 'South'
EAST = 'East'
WEST = 'West'
class Move:
"Handles movement of pieces on the game board"
def __init__(self, tile, dir, jumps):
self.tile = tile
self.dir = dir
self.jumps = jumps
directions = {D... |
c7f12b13af93ec2b449f0fd6b659003c2329a41f | MasMat2/Drmario | /deocrator.py | 2,234 | 3.5 | 4 | # # def html_tag(tag):
# # def wrap(content):
# # print(f'<{tag}>{content}</{tag}>')
# # return wrap
# #
# # h1_tag = html_tag('h1')
# # h1_tag("Blog header")
# # h1_tag("Blog subheader")
# #
# # p_tag = html_tag('p')
# # p_tag("A brief history of yo salad ass")
#
#
# def full_decorator(prefix):
# d... |
d681b78e44de1067a47666fb4d75ea6cf7f1aff7 | ColoZhu/pythonCharm | /iterator.py | 3,261 | 4.25 | 4 | # Python3 迭代器与生成器
import sys
'''
迭代是Python最强大的功能之一,是访问集合元素的一种方式。
迭代器是一个可以记住遍历的位置的对象。
迭代器对象从集合的第一个元素开始访问,直到所有的元素被访问完结束。(迭代器只能往前不会后退)。
迭代器有两个基本的方法:iter() 和 next()。
字符串,列表或元组对象都可用于创建迭代器:
'''
list = [1, 2, 3, 4]
it = iter(list) # 创建迭代器对象
print(next(it))
list2 = [1, 2, 3, 4]
it2 = iter(list2)
for x in it2:
print(x,... |
292f19899cf1c6d9ae6f80dbf30b6bbb30f688ba | ColoZhu/pythonCharm | /condition.py | 1,046 | 4.0625 | 4 | # 条件语句
num = 5
if num < 10:
print("num<10")
elif num == 10:
print("num==10")
else:
print("num>10")
# 多条件判断
'''
由于 python 并不支持 switch 语句,所以多个条件判断,只能用 elif 来实现,
如果判断需要多个条件需同时判断时,可以使用 or (或),表示两个条件有一个成立时判断条件成功;
使用 and (与)时,表示只有两个条件同时成立的情况下,判断条件才成功。
'''
num1 = 9
if num1 >= 0 and num1 <= 10: # 判断值是... |
03a973c2fd9911d5814a1957774ce5087db32fbe | ColoZhu/pythonCharm | /base.py | 504 | 4.0625 | 4 | # 编程基础
# Fibonacci series: 斐波纳契数列
# 两个元素的总和确定了下一个数
a, b = 0, 1
while b < 10:
print(b)
a, b = b, a + b # a, b = b, a+b 的计算方式为先计算右边表达式,然后同时赋值给左边, b=a + b,然后a=b ,右边表达式的执行顺序是从左往右的。
'''
等价于
b_temp = b
sum = a + b
a = b_temp
b = sum
'''
# 1. end 关键字
a1, b1 = 0, 1
while b1 < 1000:
print(b1... |
ecb0544a95b3f1326da6e0e83d12126bff45da9f | ColoZhu/pythonCharm | /for_while.py | 2,548 | 3.953125 | 4 | # while 循环
# for 循环
for letter in 'Python':
print('当前字母 :', letter)
# 序列索引迭代 range(length),包左不包右
fruits = ['banana', 'apple', 'mango']
for index in range(len(fruits)): # 函数 len() 返回列表的长度
print('当前水果 :', fruits[index])
# 嵌套循环 while循环体中嵌套for循环
'''
以下实例使用了嵌套循环输出2~100之间的素数
'''
i = 2
while (i < 100):
j... |
4661e3f54423f5b0d65808b43453c3f68c6726b9 | ColoZhu/pythonCharm | /helloworld.py | 703 | 3.921875 | 4 | # -*- coding: UTF-8 -*-
print("你好,世界")
print('你好,世界' * 3)
for i in range(12):
print(i)
if True:
print("Answer")
print("True")
else:
print("Answer")
print("False")
item_one = "1"
item_two = "2"
item_three = "3"
total = item_one + \
item_two + \
item_three
print("total:" + total... |
7518256149feca0761a64f71fd8d46a3988c9380 | abhinaymandepudi/interview-questions | /python/combinations/subsets.py | 712 | 3.84375 | 4 | # encoding: utf-8
"""
Returns all the subsets of a given set.
@author: Ofir Picazo - ofirpicazo@gmail.com
@date: March 2012
"""
def get_subsets(input_set):
def _convert_combination_to_set(combination):
subset = set()
for i, value in enumerate(combination):
if value == '1':
... |
a1f20ada8165743d3aff3a37d17444fee600711c | warriorforGod/python | /PCC/ch5/alien_colors.py | 1,228 | 3.65625 | 4 | alien_color = 'green'
print("You shot a " + alien_color + " alien")
if alien_color == 'green':
print("5 points earned!")
alien_color = 'red'
print("\nYou shot a " + alien_color + " alien")
if alien_color == 'green':
print("5 points earned!")
alien_color = 'yellow'
print("\nYou shot a " + alien_color + " alien"... |
be7f4059c19e965d12fdc2070744c8ebeb8457ae | BrettMeirhofer/CIS2348 | /Homework3/10.11.py | 1,209 | 3.78125 | 4 | #Brett Meirhofer 2036955
class FoodItem:
def __init__(self,name="None", fat=0.0, carbs=0.0, protein=0.0):
self.name = name
self.fat = fat
self.carbs = carbs
self.protein = protein
def get_calories(self, num_servings):
# Calorie formula
calories = ((... |
079e6f19c940c76b47b293551d015ee93b76f59c | sillfsxa/datafrog_git_test | /hello.py | 286 | 3.703125 | 4 |
def greet(people):
printout = []
for p in people:
to_print = 'hello {}'.format(p)
printout.append(to_print)
print(to_print)
return printout
if __name__ == '__main__':
everybody = [
'colin',
'pierre'
]
greet(everybody)
|
39f6d774a43cf4f632710c9712ae7d7d264dbbe9 | hdjewel/calculator | /ex3_arithmetic.py | 1,722 | 4.0625 | 4 | import arithmetic
def main():
print "This is a program to do math equations."
print " "
print "Input pattern as follows"
print " addition - add, int, int"
print " sub - sub, int, int"
print " multi - ...."
print " squ - squ, int"
print "cube- cube, int"
print "etc..."
print "I... |
0b0442ddfd6199b4e6d862173ce1fb5c2ced4211 | LBerthot/ZCasino | /Fonctions.py | 4,209 | 3.96875 | 4 | # -*-coding:Latin-1 -*
# Liste des modules
from random import randrange
from math import ceil
def solde_depart():
"""Dtermine la solde de dpart.
La fonction continue tant que la somme entre est invalide"""
solde = -1
while solde <= 0: # La solde est demand tant que celle-ci est invalide
sol... |
509833a2c35765592c42960f58c795a23b45599c | edithbeen/CareerCup | /Q4_Target_Sum_Find_Subsets.py | 2,699 | 4.03125 | 4 | # given a target sum, find all the possible subsets of positive integers that sums up to the target sum
# eg given a target sum 15, a possible subset is [4, 5, 6]
# question 1: 0 included?
# Let's first consider the case when 0 is not included
# question 2: limit of sum? if the limit is low, then we just generate all ... |
0b115ef691c01b1ecd12f37e5db243457f9a3775 | edithbeen/CareerCup | /Q18_Count_Words_in_Sequence.py | 2,334 | 3.8125 | 4 | # Cound # of distinct words in a sequence
# question: how long is the sequence? Is it a stack, queue, or a stream?
# all elements in the sequence is a word? how do you define a word?
def count_distinct_words(l, dictionary):
s = []
for w in l:
if w not in s and w in dictionary:
s.append(s)
... |
9be0f47f8bccdfc358e2482de28eb6b63f6e62c2 | edithbeen/CareerCup | /Q23_Reverse_Integer.py | 467 | 4.0625 | 4 | # Reverse digits of an integer.
# Example1: x = 123, return 321
# Example2: x = -123, return -321
#
# The input is assumed to be a 32-bit signed integer. Your function should return 0 when the reversed integer overflows.
def reverseInt(n):
sign = 1
if n < 0:
sign = -1
n = - n
rev = 0
wh... |
17a2d3f7ba06f04c5e422b867f33fa68c7be855e | soulsparkk/labs | /lab1.7.py | 239 | 4.0625 | 4 | from math import sqrt
a = int(input("Введите длину первого катета: "))
b = int(input("Введите длину второго катета: "))
c = sqrt(a**2 + b**2)
print("Длина гипотенузы: ", c) |
f5b7209473ab69d43903bfd44ff9c2a0d1d91109 | zaky9/zaky | /9.4.2019/increment.py | 158 | 3.734375 | 4 | # Increment
x = 12
x += 1 # x = x + 1
print(x)
x -=1 # x = x - 1
print(x)
x *= 2 # x = x * 2
print(x)
x /= 2 # x = x / 2
print(int(x))
|
a8c0bef5cf032fb52926196227f37e040867cd9f | zaky9/zaky | /10.4.2019/basicCal.py | 450 | 4.1875 | 4 | # Basic calculator
no1 = int(input('Masukan angka pertama: '))
operator = input(' Masukan symbol operator (+,-,/,*): ')
no2 = int(input('Masukan angka kedua: '))
if operator == '+':
print(no1,"+",no2,"=",no1 + no2)
elif operator == '-':
print(no1,"-",no2,"=",no1 - no2)
elif operator == '*':
print(no1,"*",n... |
f3aaaad1c6bef2fe2822350391b2f377aeb6bde5 | zaky9/zaky | /9.4.2019/ratioumur.py | 204 | 3.859375 | 4 | total= int(input('umur total dua orang adalah: '))
ratio= float(input('ratio umur: '))
org1 = int(total / (1+ ratio))
org2 = int(total - org1)
print('Usia org1 =', org1, 'th & usia org2 = ', org2, 'th') |
71b3fa390416f3486c21af59b0466d9f12913878 | zaky9/zaky | /11.4.2019/format.py | 354 | 3.9375 | 4 | # format function
x= 200
print(x)
print('{:,}'.format(x))
print('{:,}'.format(x).replace(',','.'))
print('Halo {}, umurmu {}'.format('Andi', 27))
print('Halo {1}, umurmu {0}'.format('Andi', 27))
print('Asalmu dari {kota}'.format(kota = 'Depok'))
print('Suhu udara = {0:f}'.format(25)) # string formating methode {strin... |
2965b208d6dc1d2bcf39dad2ed7d92ff94ce4cc7 | zaky9/zaky | /11.4.2019/password.py | 361 | 3.953125 | 4 | # password
x=1
while x <= 3:
password = input("Enter password: ")
correctPassword ='123456'
if password == correctPassword:
print('welcome')
break
else:
x += 1
if x <=3:
print('input: ',x,". Invalid please try again", )
else:
print('You... |
2829f18e554097e649b35736ba20e94ff7ecb7be | zaky9/zaky | /9.4.2019/userinput.py | 331 | 3.90625 | 4 | # interactive that require user input
'''
nama = input('Halo, namamu siapa? : ')
usia = input('Halo '+ nama + '! Usiamu berapa? : ')
print(nama,',', usia)
x= float(usia)+20
print('20 tahun lagi usia '+ nama + ' adalah : ', x)
# user input hitung luas persegi
sisi = int(input('ketik panjiang sisi: '))
print('luas =', ... |
0697e0e3491d32a76649cda6d7700b62d2662e11 | lynda-trad/runtrack-python | /jour02/job20_085/main.py | 1,435 | 3.828125 | 4 | class Board:
def __init__(self, i, j):
self.grille = [['O' for h in range(i)] for w in range(j)]
self.height = i
self.width = j
def play(self, color, column):
if color == "Rouge":
c = 'R'
print("You played R")
elif color == "Jaune":
c ... |
cd3bd5b13e350334dd4352967d2df4b202f16a70 | lynda-trad/runtrack-python | /jour01/job29/main.py | 606 | 4.1875 | 4 | def draw_triangle(height):
triangle = ""
width = height * 2
i = 0
j = i + 1
while i < height:
for it in range(0, width):
if it == width / 2 - j:
triangle += "/"
elif it == width / 2 + i:
triangle += "\\"
if i == height - 1 a... |
ee93faa4dd843be255e43258605790ab7f88c11e | lynda-trad/runtrack-python | /jour03/job03/main.py | 387 | 3.65625 | 4 | from os.path import exists
import re
number = int(input("Entrez le taille de mots que vous recherchez\n"))
count = 0
filename = 'data.txt'
if exists(filename):
file = open(filename)
text = file.read()
file.close()
words = text.split()
for word in words:
if len(word) == number:
... |
895529df24c918eb19d92e6584fc3e482b19f09b | Gustovus/PFB_problemsets | /Python_Problemsets/problemset6_1read.py | 248 | 3.65625 | 4 | #!/usr/bin/env python3
file_tom = open("Python_06.txt", "r")
file_tomw = open("Python_06_uc.txt", "w")
for line in file_tom:
line = line.rstrip()
print(line.upper())
file_tomw.write(str(line.upper()) + '\n')
file_tom.close()
file_tomw.close()
|
51eefec5108d471b6e40d2fe8292402d0d6e46da | Gustovus/PFB_problemsets | /Python_Problemsets/problemset2_2.py | 152 | 3.78125 | 4 | #!/usr/bin/env python3
import sys
checknumber = sys.argv[1]
if int(checknumber) > 0:
print("Positive number")
else:
print("Not a positive number")
|
0c004a1f197a2252401c08c3b5287a65452897f1 | wkarney/code-snippets | /riddler/riddler_league_baseball/rlb_definitions.py | 5,476 | 3.90625 | 4 | '''
Riddler League Baseball, also known as the RLB, consists of three teams: the Mississippi Moonwalkers, the Delaware Doubloons and the Tennessee Taters.
Each time a batter for the Moonwalkers comes to the plate, they have a 40 percent chance of getting a walk and a 60 percent chance of striking out. Each batter for ... |
cbbac779d4ee2439264390a541908118dc1e5772 | AshMouch11/FinalProject17 | /Directions.py | 1,302 | 4.03125 | 4 | a = input("Welcome to Ash's super amazing junior year final programming project! Before I explain to you the rules of the game, would you prefer to be asked questions about : Supernatural (the TV show), Math, or Sherlock (the TV show)? ")
print(f"{a}? Awesome. Get ready for some great questions about {a}.")
directions ... |
b196fcfd1d150ad1509bb9171203c1d966fa268f | jeewonb/pythonStudy | /PycharmProjects/programmers/test.py | 779 | 3.609375 | 4 | def solution(s):
answer = 0
testList = []
for a in s:
testList.append(a)
print('list', testList)
while True:
try:
deleteFn(testList)
if len(testList) == 0:
print("answer: 1")
break
else:
... |
293a146505b37a0aa571c8d516a7d24edcf80c8e | mauza/kata | /2019/June/ep43.py | 1,105 | 3.515625 | 4 | from itertools import permutations
def gen_pandigitals(num_digits):
if num_digits > 10 or num_digits < 1:
raise Exception("You entered a bad digit")
digits = list(range(0,num_digits))
for perm in permutations(digits):
yield list(map(str, perm))
def check_pan_num(digits):
if len(digits)... |
27bb0ab074db4c386739322c8d32d74c6c83cfc4 | drwhoigloo/Play_with_Python | /learning.py | 5,746 | 4.3125 | 4 |
lesson = 'lists'
if lesson == 'exercise':
# Exercise to list all numbers in the given range that:
# - not evenly divisible by 7
# ex. 7%7 = 0 i.e. any number divisible by 7 will not get listed
# AND
# - not evenly divisible by 5
# ex. 5%5 = 0 i.e. any number d... |
859d327f3e3176afe43db11bfc88946a9e24a1a4 | INKWWW/Sword | /jz_offer/min_num_in_rotateArray.py | 436 | 3.734375 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
class Solution:
def minNumberInRotateArray(self, rotateArray):
# write code here
if len(rotateArray) == 0:
return 0
elif len(rotateArray) == 1:
return rotateArray[0]
else:
val = rotateArray[0]
... |
30b1ee730f1a65b6de5abbdf41bddf6367ff784b | codewithgsp/text-based-browser | /Problems/Merging several sorted lists/task.py | 188 | 3.546875 | 4 | n = int(input())
list_4 = []
for _ in range(n):
list_4.append(input().split())
list_5 = []
for e in list_4:
for i in e:
list_5.append(i)
print(" ".join(sorted(list_5)))
|
7715fbb92af9a4902b0d836abfcd6af160b93c6e | franciscoklf/base-de-datos | /db2.py | 1,067 | 3.515625 | 4 | import sqlite3
base = sqlite3.connect('d:\pi.db')
c = base.cursor()
print("1 - Ver lista de fabricantes")
print("2 - Ver lista de articulos")
print("3 - Ingresar fabricante")
print("4 - Ver lista articulos+fabricantes")
opc = {1:"FABRICANTES",
2:"ARTICULOS"}
opcion = int(input())
if opcion == 4:
c.execute(... |
e7dd32fc109808608cc3f92cf13d9463cdd915e7 | pedrokarneiro/Python_MongoDB_Study | /0702_Python_MongoDB_Sort_DESCending.py | 882 | 4.25 | 4 | # Python MongoDB Sort
# 0702_Python_MongoDB_Sort_DESCending.py
#
# Sort the Result
# ===============
# Use the sort() method to sort the result in ascending or descending order.
# The sort() method takes one parameter for "fieldname" and one parameter for "direction" (ascending is the default direction).
#
# Sort Desc... |
db6e67f1a0b3e02da66ccca216738ed98b91f9ab | pedrokarneiro/Python_MongoDB_Study | /07_Python_MongoDB_Sort.py | 1,092 | 4.21875 | 4 | # Python MongoDB Sort
# 07_Python_MongoDB_Sort.py
#
# Sort the Result
# ===============
# Use the sort() method to sort the result in ascending or descending order.
# The sort() method takes one parameter for "fieldname" and one parameter for "direction" (ascending is the default direction).
#
# Example: Sort the resu... |
9eb8f3d56dcfda3d4a47791da4f027f30eb6a36c | Llamato/LengthTools | /disassembler.py | 692 | 3.53125 | 4 | __version__ = "1.0"
__author__ = "Llamato"
from instructions import Instructions
def disassemble_code(block):
if "\n" in block:
blocks = block.splitlines()
for index, current_block in enumerate(blocks):
blocks[index] = disassemble_code(current_block)
return blocks
return l... |
f3e7be4b34cdf8a65e708b65559c88eb762b0a1b | charles-ah/work2--graphics | /draw.py | 2,221 | 3.796875 | 4 | from display import *
def draw_line( screen, x0, y0, x1, y1, color ):
dx = x1 - x0
dy = y1 - y0
if dx>=0 and dy>=0:
if dx >= dy:
octant1( screen, x0, y0, x1, y1, color )
else:
octant2( screen, x0, y0, x1, y1, color )
if dx>=0 and dy<=0:
if dx >= -1*dy:... |
084f53fd93b0370bafd118a4dc53cc2baa08aadd | pacifastacus/Programming1 | /ex02/masodik.py | 626 | 4.34375 | 4 | # Write a Python program to read an entire text file line by line and it writes them to the consol.
# It can handle the FileNotFoundError.
try:
fname = input("Adja meg a beolvasandó fájl elérési útját:")
file = open(fname, "r")
for i, line in enumerate(file):
print(i + 1, ". ", line, sep="",
... |
bc4b9e2956293e7f9e25a48d4a08316b916dcdbe | pacifastacus/Programming1 | /ex03/masodik.py | 715 | 3.9375 | 4 | # Write a python program which gets the n number and the name of the output file from
# the commandline argument and write a method to sum of the first n positive integers and
# write the whole equation into the file.
# 1+2+3+4+5=15
import sys
def sum_first_n_ints(n, outfile):
sum = 0
s = ''
for num in r... |
4f08a245dbaca244f05141d531f3e88e484280a9 | pacifastacus/Programming1 | /ex01/hatodik.py | 189 | 3.796875 | 4 | def first_n(string: str, n: int) -> str:
if len(string) < 3:
return string
else:
return string[:n]
s = input("sztring >")
n = int(input("n >"))
print(first_n(s,n)) |
8a41de4268f2ebf5ddd9f5dfca740b53eda65b16 | vmarinas/ECE480Python | /plotter.py | 1,013 | 3.515625 | 4 | from matplotlib import pyplot as plt
from matplotlib import style
import numpy as np
from matplotlib.animation import FuncAnimation
import pandas as pd
style.use('ggplot')
fig, ax = plt.subplots()
ax.set_xlim(0, 18)
ax.set_ylim(0, 285)
plt.title('Displacement vs. Time')
plt.ylabel('Displacement in microns')
plt.xlabel... |
801c57d8699bbd162514a76db781b11379f3b2b8 | ConorSheehan1/advent_of_code_2016 | /day1/Day1.py | 1,544 | 3.890625 | 4 | user = input().split(", ")
# north, south, east, west
distance = {"north": 0, "south": 0, "east": 0, "west": 0}
# orientation (circular list)
orient = ["north", "east", "south", "west"]
# start facing north (oriented north)
current = 0
# for every direction command
for val in user:
# find orientation
if val... |
e9fc4dce04b8132ed23d73fcb2413c6fd365e87f | MorvanZhou/Evolutionary-Algorithm | /tutorial-contents/Genetic Algorithm/Microbial Genetic Algorithm.py | 3,524 | 4.0625 | 4 | """
Visualize Microbial Genetic Algorithm to find the maximum point in a graph.
Visit my tutorial website for more: https://mofanpy.com/tutorials/
"""
import numpy as np
import matplotlib.pyplot as plt
DNA_SIZE = 10 # DNA length
POP_SIZE = 20 # population size
CROSS_RATE = 0.6 # mating p... |
ca3d7093f774d310d9840b76a63309517244662c | ReimKuos/ot-harjoitustyo | /src/shootables/sharp_bullet.py | 1,024 | 3.84375 | 4 | """this contains the bullet class used by the enemy sharp"""
import pygame
class SharpBullet(pygame.sprite.Sprite):
"""
A bullet that kills the player if it collides with it,
has standart speed and can move in all directions
"""
def __init__(self, x_pos: int, y_pos: int, x_speed: int, y_speed: in... |
7b7f3a539107dca1dd92650dff62d04819dcb81e | ReimKuos/ot-harjoitustyo | /src/entities/sharp.py | 3,030 | 3.546875 | 4 | """module that has enemy classes"""
from random import randint
from math import sqrt
from entities.enemy import Enemy
from shootables.sharp_bullet import SharpBullet
class Sharp(Enemy):
"""
basic enemy class, bounces around the screen kills the player if touched,
also shoot dangerous projectiles
"""
... |
3cf6eceeb10ed89d8eee466a49d53fe259398218 | katiaff/University | /CN/Game Of Life/GOL.py | 3,227 | 3.546875 | 4 | # -*- coding: utf-8 -*-
"""
Game Of Life implementation
@author Carla Fernández
"""
from __future__ import division
import numpy as np
import matplotlib.pyplot as plt
import timeit
rows = 30
cols = 40
def create_matrix():
np.random.seed(0)
X = np.zeros((rows, cols), dtype=bool)
r = np.random.random((10,... |
15f162459b53b46c2f9dc1e92129fc4629867a54 | born2vineet/HackerRank | /Lists.py | 314 | 3.78125 | 4 | # Enter your code here. Read input from STDIN. Print output to STDOUT
L = []
N = int(raw_input())
for i in range(1, N+1):
lst = raw_input().split()
command = lst[0]
args = lst[1:]
if command != "print":
command += "("+",".join(args) +")"
eval("L."+command)
else:
print L |
8640bcde3f525ebf09accabb2c5b248e52b0a18a | codetricity/projects | /restaurant.py | 1,507 | 3.703125 | 4 | import random
breakfastlist = [
"Avenue Cafe",
"The Sand Bar",
"Zelda's",
"Cook House",
"Sunrise Cafe"
]
lunchlist = [
"Sushi Garden",
"Erik's Deli Cafe",
"Betty's Burger",
"Chipotle",
"Togos",
"Dharma's",
"Thai Basil"
]
snacklist = [
"iCrave",
"Yogurtland",
... |
42c376a6e6317dcceae459282f7d35395a9fe635 | jezabrandt/mkdev | /one_or_two.py | 438 | 3.796875 | 4 | def one_or_two_dict(a):
return {1: 2, 2: 1}[a]
print(one_or_two_dict(1))
def one_or_two_list(a):
list_num = [1, 2]
list_num.remove(a)
return list_num[0]
print(one_or_two_list(2))
def one_or_two_set(a):
set_of_num = {1, 2}
set_a = set()
set_a.add(a)
res = (set_of_num ^ set_a)
... |
001e3d49615b8e23a095fd53d7fc0de7c0c46295 | jiangyoudang/python3 | /algorithm/euler/numAl.py | 1,366 | 4.125 | 4 | __author__ = 'congliu'
# -*- coding utf-8 -*-
import math
def fibonacci(num):
result_list = []
a = 1
b = 1
while (b <= num):
a, b = b, a + b
result_list.append(a)
return result_list
def fibonacci_gen(num):
a, b = 1, 1
while a < num:
yield a
a , b = b, a+b... |
bd846a5de7b31b5c565ddd506e473c3d1678729a | jiangyoudang/python3 | /algorithm/leetcode/flatten.py | 662 | 3.921875 | 4 | # Definition for a binary tree node
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
# @param root, a tree node
# @return nothing, do it in place
def flatten(self, root):
if not root:
return Non... |
410249bd8402418dc75f8e7925854fb632a9dca1 | jiangyoudang/python3 | /algorithm/leetcode/insert interval.py | 1,347 | 3.78125 | 4 | # Definition for an interval.
class Interval:
def __init__(self, s=0, e=0):
self.start = s
self.end = e
class Solution:
# @param intervals, a list of Intervals
# @param newInterval, a Interval
# @return a list of Interval
def insert(self, intervals, newInterval):
# if not in... |
10455fce5960f0a8fab2a82b134fb5f165bc4439 | jiangyoudang/python3 | /algorithm/other/combination problems.py | 1,135 | 3.765625 | 4 | '''
N个鸡蛋放到M个篮子中,篮子不能为空,要满足:对任意不大于N的数量,能用若干个篮子中鸡蛋的和表示。
写出函数,对输入整数N和M,输出所有可能的鸡蛋的放法。
M = 2
N = 3
1 2
2 1
'''
def helper(egg_n, hamper_n, temp, res):
if hamper_n == 1 and egg_n > 0:
res.append(temp[:]+[egg_n])
return
if egg_n < 1:
return
for i in range(1, egg_n):
temp.append... |
fdd14f9bc5f67a70b20276a91e95f3fcf8fbc467 | jiangyoudang/python3 | /algorithm/leetcode/shortestToBuildings.py | 1,540 | 3.546875 | 4 | class Solution(object):
def shortestDistance(self, grid):
"""
:type grid: List[List[int]]
:rtype: int
"""
m = len(grid)
n = len(grid[0])
shortest = float('inf')
buildings = sum([1 for row in grid for land_val in row if land_val == 1])
for i in range(m):
for j in range(n):
... |
63e2ae68ec167d9d53b124ab88af74cc4789a40e | ayingxp/LeetCode | /recursion/246.StrobogrammaticNumber.py | 982 | 3.734375 | 4 | # -*- coding: utf-8 -*-
"""
中心对称数:
中心对称数是指一个数字在旋转了180度之后看起来依旧相同的数字(或者上下颠倒地看)
示例:
输入: 69
输出: True
"""
class Solution:
def isStrobogrammic(self, num):
"""
:param num: str
:return: bool
"""
# 0, 1, 6, 8, 9 旋转180度以后得到新的数字,0,1,9,8,6
if not num:
return T... |
43f5ef65f384d6ec2748444f1d6853c7a5436044 | ayingxp/LeetCode | /recursion/687.longestUnivaluePath.py | 1,040 | 3.6875 | 4 | # -*- coding: utf-8 -*-
"""
给定一棵二叉树,找到最长的路径,这个路径中的每个节点具有相同值。
这条路径可以经过也可以不经过根节点。
注:两个节点之间的路径长度由它们之间的边数表示。
"""
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution(object):
def dfs(self, root, val):
if not root:
... |
127d60569503fe31e66e164e638f94b6eb42953e | ayingxp/LeetCode | /backtracking/permutaions2.py | 980 | 4.09375 | 4 | # 全排列问题
data = list("ABCDEF")
res = list()
def permutate(data):
if not data:
# res.append(None)
return None
if len(data) == 1:
# res.append(data)
return data[0]
else:
for i in range(len(data)):
# res.append([data[i]] + data[0:i] + data[i+1:])
... |
4ff12371e44e2b0f21a6875d449556595489c6e7 | kah-g/Estudos | /Python/comma_code.py | 954 | 4.21875 | 4 | #Projeto comma code proposto no livro 'Automate the boring stuff with python'
def insert_comma (lista):
lista_str = ''
for i in range ((len(lista))-1):
lista_str = lista_str + str(lista[i] + ', ')
lista_str = lista_str + 'and ' + str(lista[i])
return lista_str
def create_lista ():
... |
b00204a3f218ef4f0d9c579f6cb766325d0c6eb8 | navitajain/navitajain.github.io | /codes/CodingProblems/BT_MaxDepth_BFS-DFS-Recurse.py | 1,679 | 3.84375 | 4 | # Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
# DFS iterative
def maxDepth(self, root: TreeNode) -> int:
if not root: # root None
return 0
depth = [(r... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.