blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
6841e329044ea5496bdc98e65861c9e80c512228 | CrossEntropy/Heima-Python-Practices | /开发一个简易的名片系统/card_main.py | 1,062 | 4 | 4 | #! /usr/bin/python3
# 程序的入口
# 每一次启动名片管理系统都通过main这个文件启动
import card_tool
while True: # 进行一个无限循环,由用户决定什么时候退出循环
# 显示功能菜单
card_tool.show_menu()
# 用户输入
action_str = input("请选择希望执行的操作: ")
print("您选择的操作是【%s】"%action_str)
# 1,2,3针对名片的操作
if action_str in ["1", "2", "3"]:
# 输入为1进行新增名片的操作... |
cca5703a1797e21fe6cdd3b1a765dc481ece160e | Prosper0/MITx6002 | /W01/L1P3_P4.py | 967 | 3.71875 | 4 | # Lecture 1, Problem 3 & 4
import pylab
import numpy as np
PATH_TO_TEMPS_FILE = r'F:\Dev\Python\MITx6002\W01\julyTemps.txt'
def loadTemps():
inFile = open(PATH_TO_TEMPS_FILE, 'r', 0)
high_temps = []
low_temps = []
for line in inFile:
fields = line.split(" ")
if len(field... |
66375bf088d189ac04a7b27bc40b45bd0d751576 | Tashkulovv/python_vol_4 | /chapter 1.1.py | 1,660 | 3.984375 | 4 | #1
'''num1 = int(input('enter anumber1: '))
num2 = int(input('enter anumber2: '))
print(num1-num2)
#2
print(36%5)
'''
#3
'''word = input('введите слово: ')
if word[::-1] == word:
print('слово является палиндромом')
else:
print('слово не является палиндромом')'''
#4
'''word = 'I love JAVA'
print(word.replace(... |
770f4f0d42230139d9cad19abfd5950c26589c4a | nurtai00/WebDevPython | /hackerrank/12.py | 196 | 3.859375 | 4 | def wrap(st, n):
for i in range(0, len(st), n):
res = st[i:i+n]
if len(res) == n:
print(res)
else:
return(res)
wrap("abadcadcadasd", 3) |
98b9b64df2c586a235c4a0a00c52b71c8adb79cf | TanTaiHcmus/LogicalKnowledge | /Câu 1/Source code/Utils.py | 2,252 | 3.921875 | 4 | #%%
def dissociate(op, args):
"""Tách mệnh đề args thành các literal hoặc mệnh đề nhỏ hơn, dựa vào toán tử op
Ex: dissociate('AND', [A AND B]) --> [A, B]
dissociate('AND', [A OR B]) --> [(A OR B)]
dissociate('OR', [A AND B]) --> [(A AND B)]
dissociate('OR', [A OR B]) --> [A, B]
"""
... |
5ad6d7f2c02c9c47f713a48e7b7bcdb664d37dbf | ozyohthree/cscc_python | /datastructures.py | 1,713 | 4.46875 | 4 | # The different Data structures and how to use them
#List = Array / mutable
myLanguageList = ['Java', 'Python', 'Go']
anIntegersList = [10, 20, 30]
#print(myLanguageList)
#looping through my list
#for language in myLanguageList:
# print(language)
list_1 = ['spam', 2.0, 5, [10, 20]]
#for item in list_1:
# print... |
cab66ae80e42c34705fe918367770ed81f643a23 | gabrieldtc/CursoEmVideoPython | /PyCharm/Desafios/Mundo1/desafio27.py | 329 | 3.9375 | 4 | # faça um progrma que leia um nome completo de uma pessoa, mostrando em seguida o primeiro e o ultimo nome separadamentr
nome = str(input('Qual o seu nome completo: ')).strip()
print('Muito prazer em te conhecer!')
l = nome.split()
print('Seu primeiro nome {}'.format(l[0]))
print('Seu ultimo nome é {}'.format(l[len(l... |
bef1144c78314545d59a9782d4d1d14371d52e2a | Sajirimendjoge/Python-Assignments | /Task_1/a6.py | 589 | 4.625 | 5 | # Q6. Write a program to check the data type of the entered values. HINT: Printed output should say - The input value data type is : int/float/string/etc
ans = input("Enter the value")
print("The input value data type is : {}".format(type(ans)))
'''
Have a doubt regarding this. As the input type of all inputs taken ... |
763d35554c43ecf68905cd221cd9862669f17596 | piyushkashyap07/recursion | /sumof digits.py | 490 | 4.125 | 4 | # Sum of digits (recursive)
# Send Feedback
# Write a recursive function that returns the sum of the digits of a given integer.
# Input format :
# Integer N
# Output format :
# Sum of digits of N
# Constraints :
# 0 <= N <= 10^9
# Sample Input 1 :
# 12345
# Sample Output 1 :
# 15
# Sample Input 2 :
# 9
#... |
55cc51d5ab0d45fc43b99f0419c0c99ab8553e3b | miahnaseem/Predicting-Coding-Problem-Difficulty | /problem12_hard.py | 668 | 4.21875 | 4 | # There exists a staircase with N steps, and you can climb up either 1 or 2 steps at a time.
# Given N, write a function that returns the number of unique ways you can climb the staircase. The order of the steps matters.
# e.g. Input: 4, Output: 5
# - 1,1,1,1
# - 2,1,1
# - 1,2,1
# - 1,1,2
# - 2,2
steps = [1,2]
def s... |
02705065a9913f0df76a3ab33d015ff4e2534dd0 | SunnyMarkLiu/LeetCode | /101-200/110. Balanced Binary Tree.py | 2,384 | 3.9375 | 4 | #!/home/sunnymarkliu/softwares/anaconda3/bin/python
# _*_ coding: utf-8 _*_
"""
@author: SunnyMarkLiu
@time : 18-3-8 下午5:29
"""
# Definition for a binary tree node.
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def isBalanced... |
90e0564a5a080ad02fdbef2cf6175d1b08476894 | henryCraig/codingChallengesCodeWars | /sumLowestPositiveInts.py | 252 | 3.828125 | 4 | #def sum_two_smallest_numbers(numbers):
# numbers.sort()
# return (numbers[0] + numbers[1])
def sum_two_smallest_numbers(numbers):
return sum(sorted(numbers)[:2])
#sorted(numbers)
print(sum_two_smallest_numbers([19, 5, 42, 2, 77]))
|
02483e6f8aafe8e892e6d433cf7b846fe7a99439 | corganfuzz/pythonclasses | /RectangleClass.py | 256 | 3.53125 | 4 | class Rectangle:
def __init__(self, width=1, height=2):
self.width = width
self.height = height
def getArea(self):
return self.height * self.width
def getPerimeter(self):
return 2 * (self.width + self.height)
|
8d0c9fb854197e4f1a2ce2f24e4f9647f6efe146 | AghalarYusublu/PragmatechFoundationProject | /Task/E-olymp/sert_operatoru(3).py | 124 | 3.6875 | 4 | x = int(input())
if x < -4:
print(x+5)
elif -4 <= x and x <= 7:
print(x**2 - 3*x)
elif x > 7:
print(x**3 + 2*x) |
be0895cc725db7a18deb5f5086df131f8da438ed | MrHamdulay/csc3-capstone | /examples/data/Assignment_2/ovdjon001/question1.py | 349 | 3.921875 | 4 | def main():
year = eval(input("Enter a year:"))
print()
if isLeapYear(year):
print(year, "is a leap year.")
else:
print(year,"is not a leap year.")
def isLeapYear(year):
if year%400 == 0:
return True
elif year% 4 ==0 and year%100!=0:
return True
else:
... |
ea63f84f5077cb0fdc2991259595df3f6eb7af44 | thameenas/advent-of-code-20 | /day20/part1.py | 1,356 | 3.59375 | 4 | def read_input(input_path="input.txt"):
f = open(input_path)
input_lines = f.read().split('\n\n')
tile_dict = {}
for tile in input_lines:
tile_lines = tile.split("\n")
tile_number = tile_lines[0].split()[1].replace(":", "")
tile_dict[tile_number] = find_borders(tile_lines[1:])
... |
c9a1e4f22e178cf9b2f4d43318525a12cccafeab | sarah-mcculley/python-programming | /Circle/Circle.py | 492 | 4.4375 | 4 | import math
def calc_circumference(radius):
circumference = 2 * math.pi * radius
return circumference
def calc_area(radius):
area = math.pi * radius * radius
return area
print("To quit enter a negative value.")
radius = float(input("Give me a radius of your circle:"))
while radius >=0:
x = calc_... |
e56adfbc1ebab75d2aed8871787108768f31ca66 | daniel-reich/turbo-robot | /kpPkYohYvGJWWEb6Q_4.py | 1,307 | 4.03125 | 4 | """
Write a function that gets a string number and a fret of a 6-string guitar in
'standard tuning' and return the corresponding note. For this challenge we use
a 24 fret model.
The notes are:
C, C#/Db, D, D#/Eb, E, F, F#/Gb, G, G#/Ab, A, A#/Bb, B
Try not to use a 2 dimensional list. Look at the image on the ... |
9c43dcc5dac6abae52c848de016340023b5d8529 | PdxCodeGuild/class_redmage | /code/scott/python/lab02_madlib.py | 355 | 4.125 | 4 | #lab2_madlib.py - creating a madlib
noun1 = input("Enter a noun: ")
noun2 = input("Enter another noun: ")
verb1 = input("Enter a present continuous verb : ")
verb2 = input("Enter another present continuous verb: ")
drink1 = input("Enter the name of a drink you like: ")
print(f"{verb1} down the {noun1}, smokin' {noun... |
f960b56a829f232d182662f26e7c4690aff8ea7d | asheemchhetri/pythonClass | /Section 1/walrus.py | 427 | 4.34375 | 4 | '''
Writing a simple example to use the new walrus operator, introduced in Python 3.8
It helps to perform assignment to a variable, while we are using a condition as part fo different function.
'''
### Wihout Walrus
num = input("Please enter a number: ")
while (num.isdigit()):
print(num)
num = input("Please en... |
25a9c75d3a2ba53a0727fa96037cdd7a86d4b536 | zhangxingxian/Python-One-Phase | /onephase/dict(字典).py | 743 | 4.28125 | 4 |
dict1 = {"tom":12,"lilei":13}
print(dict1["tom"])
print(dict1.get("tom"))
print(dict1.get("sucnk",))
print(dict1.get("sucnk","没有这个键"))
dict1["zhang"] = 20
print(dict1)
dict1.pop("tom") # 字典的删除要指定删除的键
print(dict1)
for key in dict1:
print(key, dict1[key])
for value in dict1.values():
print(value)
for k, v ... |
f89e8c0f033a012c50d59b89d603116426e4246c | Crypto4lice/4lice | /Project-4/Project-4.py | 1,241 | 3.65625 | 4 | # value for listmap
resource = []
# open file and set listmap's key
rsc = open("./resource.txt", "r")
readhead = rsc.readline()
readhead = readhead.split(' ')
# set listmap
for line in rsc:
splitine = line.split(',')
dict = {}
dict[readhead[0]] = splitine[0]
dict[readhead[1]] = splitine[1]
dict[rea... |
75b6540680f85f9051c9fffb29e1f4682fb4091f | saiftg/Python-Stuff | /tip_calc2.py | 832 | 4.03125 | 4 | print "Total Bill amount?: "
bill = float(raw_input(""))
print "How many peeps?: "
peeps = int(raw_input(""))
print "Was service good, fair or bad?"
feedback = raw_input("")
service = feedback.upper()
tip1 = bill * 0.20
tip2 = bill * 0.15
tip3 = bill * 0.10
split1 = (bill + tip1)/peeps
split2 = (bill + tip2)/peeps... |
bf4339beb31c63b888ba9442ad2ca9439151b3b7 | NataliaSuarezO/Cocina-Inteligente | /Proyecto.py | 20,042 | 4.1875 | 4 | """
Título de proyecto : Cocina Inteligente.
Autor : Natalia Suárez Olmos.
Matrícula : A01707445.
python_version : 3.7.7
"""
import time
"""Esta función hace que la consola imprima después de un cierto
tiempo dado. El número que se inserta en la función está dado en segundos,
puede ser en núm... |
3c1d7b3629609c1c933f1b78d8ca0cdf82e40e15 | rahulgolani/Algorithms-Dynamic-Programming | /maxSubarraySum.py | 501 | 3.546875 | 4 | def getMaxSumSubarraySize(arr):
max_ending_here=0
max_so_far=float('-infinity')
start=0
end=0
s=0
for i in range(len(arr)):
max_ending_here+=arr[i]
if max_so_far<max_ending_here:
max_so_far=max_ending_here
start=s
end=i
if max_ending_he... |
d3590bd3154db287ebcebb247b8cd9aae86aa368 | piscesleon/Py_HelloWorld | /totalBrought.py | 824 | 3.6875 | 4 | allGuests = {'Alice': {'apples': 5, 'pretzels': 12},
'Bob': {'ham sandwiches': 3, 'apples': 2},
'Carol': {'cups': 3, 'apple pies': 1}}
# 获取嵌套字典中,二级字典的键列表
def getAllItems(guests):
AllItemList=[]
for v in guests.values():
for k in v.keys():
if k not in AllItemList:
... |
7ea0c9066354822df6c1fc3caaead73736e90192 | limgeonho/Fast_Campus_Algo | /유형별풀이/기본정렬알고리즘/10814_나이순정렬.py | 380 | 3.515625 | 4 | # 나이순정렬
# 파이썬의 정렬의 기본 값 => 나이순으로 array.sort(key=lambda x:int(x[0])) 정렬하면 나머지는 그냥 원래 있던 순서대로 정렬된다(stable)
n = int(input())
array = []
for _ in range(n):
age, name = map(str, input().split())
array.append([age, name])
array.sort(key=lambda x:int(x[0]))
for arr in array:
print(*arr) |
3b5a68f737e7e1b77689c2820a580245e7c845ef | Sashok15/GeekHub_python | /HT_6/Figure.py | 1,907 | 4.09375 | 4 | """Напишіть програму, де клас «геометричні фігури» (figure) містить властивість color з початковим значенням white
і метод для зміни кольору фігури, а його підкласи «овал» (oval) і «квадрат» (square) містять методи __init__
для завдання початкових розмірів об'єктів при їх створенні.
Видозмініть програму так, щоб метод... |
aec0f1c6f139939efbb6b9c8949f0befeb2046d6 | 02Kaden-seeger/Final-Project | /Final_Project.py | 9,637 | 3.984375 | 4 | '''
# My text based game for my Final Project
# Kaden Seeger
3.14.19
'''
name = input('What is your name: ')
# This will be used later
def housekey():
print('do you go upstairs or downstairs')
print('upstairs(1) downstairs(2)')
try:
choice = int(input('Your Answer: '))
if choice < 1... |
5a29b945eee01c7627b5f42ce56d7506d50115e5 | nestark/learning | /randname.py | 1,737 | 3.78125 | 4 | import random
from tkinter import Frame, Label, Button, messagebox, Entry
class Application(Frame):
def __init__(self, master=None):
Frame.__init__(self, master)
self.grid()
self.createWidgets()
self.roll()
def createWidgets(self):
self.hellolabel = Label(self, text='E... |
6767f8248f7c21577ba4b7520fa9b90f19927b3c | mgourab/100daysofcode | /day2/tip_calculator.py | 432 | 4.28125 | 4 | print("Welcome to the tip calculator.")
total_bill = float(input("What was the total bill? $"))
tip_percent = int(input("What percentage tip would you like to give? 10, 12, or 15? "))
no_of_people = int(input("How many people to split the bill? "))
bill_with_tip = total_bill * (1 + tip_percent/100)
#print(bill_with_ti... |
15ebe42761bea8ab1fb3de226499d85ae102ddf6 | JulietaCaro/Programacion-I | /Trabajo Practico 4/Ejercicio 12.py | 853 | 4.0625 | 4 | # 12.Desarrollar una función para reemplazar todas las apariciones de una palabra por otra en una cadena de caracteres
# y devolver la cadena obtenida y un entero con la cantidad de reemplazos realizados.
# Escribir también un programa para verificar el comportamiento de la función.
# FUNCIONES
def reemplazarApar... |
8b33e848cbd21c8721cd861e1f5bc1426e7ad928 | deathzhong0/Lrean-PY | /面向对象高级编程/使用@property | 1,599 | 3.890625 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
class Student(object):
def get_score(self):
return self._score
def set_score(self, score):
if not isinstance(score, int):
raise ValueError("cuo")
if score > 100 or score < 0:
raise ValueError("cuo2")
self._sco... |
2d491b40235e9ce92d5f08fc20f3ce7af0105722 | Emelynegdu/hackinscience | /exercises/097/solution.py | 672 | 3.53125 | 4 | bob = ['II', 'IV', 'II', 'XIX', 'XV', 'IV', 'II']
alice = ['IV', 'III', 'II', 'XX', 'II', 'XX']
silvester = ['XVIII', 'XIX', 'III', 'I', 'III', 'XVIII']
def love_meet(bob, alice):
for i in set(bob):
for j in set(alice):
if i == j:
print(i)
love_meet(bob, alice)
banane = []
... |
9606818ea37fcba397cf876088b78109e5e583ff | diguacheng/myleetcode | /400-799/682棒球比赛/ss.py | 336 | 3.5 | 4 | def calPoints(ops):
li=[]
for item in ops:
if item=="+":
li.append(li[-1]+li[-2])
elif item=="C":
li.pop(-1)
elif item=="D":
li.append(li[-1]*2)
else:
li.append(int(item))
return sum(li)
ops=["5","2","C","D","+"]
print... |
f41f4a75dc46c886dc7716bc5c9f9a374b2b5d0d | yskang/AlgorithmPractice | /baekjoon/python/seven_dwarfs_2309.py | 616 | 3.609375 | 4 | # Title: 일곱 난장이
# Link: https://www.acmicpc.net/problem/2309
import sys
import itertools
sys.setrecursionlimit(10 ** 6)
def read_list_int():
return list(map(int, sys.stdin.readline().strip().split(' ')))
def read_single_int():
return int(sys.stdin.readline().strip())
def get_true_dwarfs... |
3ee0e22eaa5e8fbe9149712441dcceb8c0b988d3 | cltl/python-for-text-analysis | /Chapters/the_program.py | 224 | 3.671875 | 4 | import utils
words = ['how', 'often', 'does', 'each', 'string', 'occur', 'in', 'this', 'list', '?']
word2freq = utils.count_words(words)
print('word2freq', word2freq)
print('x', utils.x)
print('python', utils.python)
|
41cc4ad59e27bba638fcab487345c5fd7cd556aa | sneh-k/python_cc | /u3_draw_shapes.py | 661 | 3.796875 | 4 | import turtle
def draw_sq():
# window.bgcolor("light blue")
teddy=turtle.Turtle()
teddy.shape("turtle")
teddy.color("red")
#teddy.speed(10)
for i in range(1,5):
teddy.back(100)
teddy.right(90)
i+=1
def draw_cr():
pooh=turtle.Turtle()
pooh.s... |
f2be4f6ad825037cf57fcd4b25bb50fc415f0a1e | myjr1/2021 | /2ndSep2021.py | 1,415 | 3.6875 | 4 | print("welcome")
import time
time.sleep(1)
print (".")
time.sleep(0.5)
print ("..")
time.sleep(0.5)
print ("...")
time.sleep(0.5)
print ("..")
time.sleep(0.5)
print (".")
time.sleep(0.5)
print ("..")
time.sleep(0.5)
print ("...")
time.sleep(0.5)
print ("..")
time.sleep(0.5)
print (".")
time.sleep(1)... |
ddabb982ecc7d964d4acca02a89f84448e81050f | sal-pal/Python-Practice | /onlinestatus.py | 297 | 3.640625 | 4 | statuses = {
"Alice": "online",
"Bob": "offline",
"Eve": "online",
}
def online_count(statuses):
online_count = 0
statuses = statuses.values()
for status in statuses:
if status == "online":
online_count += 1
return online_count
|
8b84a98895e0a4cf82470167e64ad5c4fbf43cb6 | krishna-rawat-hp/PythonProgramming | /codes/stringrfind.py | 408 | 4.09375 | 4 | # String rfind method in python
# Example-1 single parameter
s1 = " Hello this is krishna kant rawat"
print(s1.rfind("krishna"))
print(s1.rfind("are"))
# Example-2 string with double parameter
print(s1.rfind("krishna",10))
print(s1.rfind("krishna",21))
# Example-3 string with triple parameter
print(s1.rfind("krishna... |
0068ed2345c46cc157ef42a317e424c5bdf10644 | Liang-WenYan/Python-Crash-Course | /Chapter9_2.py | 681 | 3.546875 | 4 | class Restaurant():
def __init__(self, restaurant_name, cuisine_type):
self.restaurant_name = restaurant_name
self.cuisine_type = cuisine_type
def describe_restaurant(self):
print(
"\nThe restaurant named " + self.restaurant_name.title() + " is serves " + self.cuisine_type.t... |
7d63f44ef95376ee1b6499985b6638ff6e8732bb | PRKKILLER/Algorithm_Practice | /LeetCode/0054-Spiral Matrix/main.py | 1,225 | 3.671875 | 4 | """
Given an m x n matrix, return all elements of the matrix in spiral order.
Input: matrix = [[1,2,3],[4,5,6],[7,8,9]]
Output: [1,2,3,6,9,8,7,4,5]
"""
class Solution:
def spiralOrder(self, matrix: List[List[int]]) -> List[int]:
start_row, end_row = 0, len(matrix) - 1
start_col, end_col = 0, le... |
a25ed3d0b679a2a570bc400a11bf19f519d275b3 | mycomax0416/TIL | /01_python/test/대전_2반_이가경/대전_2반_이가경/03.py | 771 | 3.765625 | 4 | # 파일명 및 함수명을 변경하지 마시오.
def summary(word):
"""
아래에 코드를 작성하시오.
word는 알파벳으로 구성되어 있습니다.
요약된 문자열을 반환합니다.
"""
compare = word[0]
result = ''
count = 0
for i in range(len(word)):
if compare == word[i]:
count += 1
else:
result += compare
r... |
11fbcfd7fa221cccbb29bb6c115b4a4abee7903d | meighanv/05-Python-Programming | /LABS/Classes/cashregister.py | 2,056 | 4.46875 | 4 | """
7. Cash Register
This exercise assumes that you have created the RetailItem class for Programming
Exercise 5. Create a CashRegister class that can be used with the RetailItem class. The
CashRegister class should be able to internally keep a list of RetailItem objects. The
class should have the foll... |
c0c5c049a58eb27c39ea4da07d5f966c0a221770 | zbx911/angr-ctf-py3 | /05_angr_symbolic_memory/05_angr_symbolic_memory.py | 1,933 | 3.5625 | 4 | import angr
import claripy
def main():
path_to_binary = './05_angr_symbolic_memory'
project = angr.Project(path_to_binary)
start_address = 0x08049288
initial_state = project.factory.blank_state(addr=start_address)
# The binary is calling scanf("%8s %8s %8s %8s").
# (!)
pass1 = claripy.BV... |
b5dbf3852d90c62b71dba6a9bf0a71bdfb313cfd | destinyu/Python_Crash_Crouse | /fuction_array_08.py | 695 | 3.546875 | 4 | def greet_users(names):
for name in names:
msg="Hello, "+name.title()+"!"
print(msg)
usernames=['a','b','c']
greet_users(usernames)
def print_models(unprinted_designs,completed_models):
while unprinted_designs:
current_design=unprinted_designs.pop()
print("Printing model:"+curre... |
89eafe073644f0750153cc3205fb2b4ddb78af87 | Daniel-Montet/password-locker | /test.py | 1,139 | 3.546875 | 4 | import unittest
from credential import Credential
from login import add_credential
class CreateTest(unittest.TestCase):
def setUp(self):
"""
Instanciate the user account creation
"""
self.new_account= Credential("montet","123456")
def test_login(self):
"""
... |
4cd4430e0911c5b70a56b30b59135dac42880579 | kevin-a-nelson/leetCode | /ListNode.py | 797 | 3.65625 | 4 | class ListNode:
def __init__(self, val = 0, next = None):
self.val = val
self.next = next
def strLink(self):
return f"{self.val} -> {self.next}"
def toList(self):
nodeValues = []
nodeValues.append(self.val)
while(self.next):
self = self.nex... |
7bd3cd9699ae98046019347c12138fc1486788d9 | k3llymariee/oo-melons | /melons.py | 2,415 | 3.875 | 4 | from random import randint
from time import localtime
"""Classes for melon orders."""
class AbstractMelonOrder():
"""An abstract base class that other Melon Order inherit from"""
def __init__ (self, species, qty, country_code, order_type, tax):
self.species = species
self.qty = qty
s... |
38d87091fa69ae50d9355991c1d938c8c2fdc452 | dyh/a_share_psql_to_html | /utils/date_time.py | 4,749 | 3.578125 | 4 | import datetime
import time
def time_point(time_format='%Y%m%d_%H%M%S'):
return time.strftime(time_format, time.localtime())
def get_datetime_from_date_str(str_date):
"""
由日期字符串获得datetime对象
:param str_date: 日期字符串,格式 2021-10-20
:return: datetime对象
"""
year_temp = str_date.split('-')[0]
... |
513fad2cb8941b3f4a03513a941b6e71a327dd14 | Agnes5/Zadanie-3 | /zadanie3a.py | 330 | 3.515625 | 4 | import sys
if len(sys.argv) != 8: sys.exit("Blad: za malo argumentow")
a = int(sys.argv[1])
b = int(sys.argv[2])
c = int(sys.argv[3])
d = int(sys.argv[4])
e = int(sys.argv[5])
f = int(sys.argv[6])
g = int(sys.argv[7])
if a > 0 and (((b > a and c > b) or d <= c) and (e%a == 0 or (f*b > 20 or g < 5))):
print 1
else:... |
53a65a1f4947bfd38626d298226c7613ab8897ed | Asbert75/dbwebb-kurser | /python/kmom02/marvin1/marvin.py | 7,881 | 4.0625 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Marvin with a simple menu to start up with.
Marvin doesnt do anything, just presents a menu with some choices.
You should add functinoality to Marvin.
"""
def meImage():
"""
Store my ascii image in a separat variabel as a raw string
"""
return r"""
... |
185e43b8b3e2bcd18050016ca5ed47a49a614a56 | Pelos17/python_OOP | /C4Clases_Metodos.py | 746 | 3.703125 | 4 | class Stones:
coleccion_de_piedras = []
tipo = "Piedra"
def __init__(self,name):
self.name = name
if len(Stones.coleccion_de_piedras) <= 4:
Stones.coleccion_de_piedras.append(self)
else:
del Stones.coleccion_de_piedras[0]
Stones.coleccion_de_piedr... |
f8d7dcc542ba7613eaac63540a455acab08c0840 | kalpajpise/assignment-1 | /query-server/app/utils.py | 557 | 3.84375 | 4 | import pandas as pd
column_name = ['BANK', 'IFSC', 'MICR', 'BRANCH', 'ADDRESS', 'CITY1', 'CITY 2', 'STATE', 'STD CODE2', 'PHONE']
def create_data_dict(df):
data = {row['IFSC']: {column: row[column] for column in column_name} for i, row in df.iterrows()}
return data
def create_bank_lead_board(df):
lead ... |
5036ae83bb977d6ee6616e03a780690d5728c3c8 | kimonjo67/py-notes | /primeNon.py | 1,150 | 4.15625 | 4 | '''
This program reads numbers from user and stores the prime in one list and the non primes
in another list.
'''
# create 2 empty lists prime and non-prime
# read user input numbers
# create loop with sentinal value of -1
# compute if number is prime
# if prime, append it to primeList and vice versa
# No duplicates ... |
28a98d52520ae19d25806a21d357e28f3096e76b | Wuskysong/python01_- | /python_one_learn/day17/review.py | 1,023 | 3.890625 | 4 | """
迭代
可迭代对象
迭代器
生成器
class 可迭代对象:
def __iter__():
创建迭代器对象
class 迭代器:
def __next__():
返回一个元素
如果没有元素,则抛出一个StopIteration异常.
for 变量 in 可迭代对象:
变量得到的就是__next__方法返回值
原理:
iterator = 可迭代对象.__iter__()
while True:
try:
变量 = iterator.__next__()
exercep... |
dbb6a5df43a2bdd4d3a0db97134c4fdc467f976f | ssg543/mass | /p3.py | 115 | 3.84375 | 4 | n=int(input("enter the number:"))
rev=0
while n>0
c=n%10
rev=rev*10+c
n=n/10
print("reversal is:",rev)
|
4b7d8a7dd55ba4fba84dd385f6d2ceeea9aed9ba | ritadang/Python-Projects | /#2.py | 714 | 3.578125 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Feb 18 23:34:02 2020
@author: ritadang
"""
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
import numpy as np
img3=mpimg.imread('/Users/ritadang/Desktop/PIC 16/HW5/g.jpg')
img4=mpimg.imread('/Users/ritadang/Desktop/PIC 16/HW5/h.jpg')
... |
e38664b189013fa0946e83cc59be9c0921e8ef69 | pedr0diniz/cevpython | /Python_Aulas/aula2.12a - Condições Aninhadas.py | 723 | 4.3125 | 4 | #programar a melhor condições mas sempre explorar alternativas
#if - primeira condição, que vai validar iniciar as análises de condições
#elif - senão se, exceção ao primeiro if ou a elifs passados, mas sem ser a exceção a tudo
#else - senão, exceção a todas as condições vistas antes
nome = str(input('Qual é seu nome... |
e28e7810c2a73e3b2553ba9f38090f825e8d4c4f | Natnael-Mulat/Kattis-Problems | /anthonyAndDiablo.py | 215 | 3.875 | 4 | import math
info = input().split(" ")
area = float(info[0])
n = float(info[1])
circle_area = math.pi*(n/(math.pi*2))**2
if circle_area >= area:
print('Diablo is happy!')
else:
print('Need more materials!') |
ead100adb0bd925137653e5824c447da7a810f70 | Rabbi50/python-books-practice | /thinkPython/interface_design/mypolygon.py | 411 | 3.71875 | 4 | import turtle
import math
def square(t, length):
for i in range(4):
t.fd(length)
t.lt(90)
def polygon(t, length, n):
for i in range(n):
t.fd(length)
t.lt(360 / n)
def circle(t, r):
circumference = 2 * math.pi * r
n = 50
length = circumference / n
polygon(t, len... |
c4b704a6845e948095fd2bc6c99a73dee741dad6 | AskeyNil/LeetCode | /20190917/20190927/914. 卡牌分组.py | 874 | 3.515625 | 4 | '''
Description: 卡牌分组
Author: AskeyNil
CreateDate: 2019-09-26 22:33:51
LastEditors: AskeyNil
*********************************
** **
** 你只有足够努力 **
** 才能看上去毫不费力 **
** **
*********************************
'''
class Solution:
def has... |
234b79bf7052264d3caa7c4353ba05d6c3b32b51 | oliwka212/1AP4 | /python/zadanie4.py | 552 | 3.890625 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
def main(args):
start= 0
stop= int(input('Podaj liczbę n: '))
if stop>0 and stop and :
print("da się zbudować!")
else:
print("Nie da się")
drukuj_nieparzyste(start, stop):
if start % 2== 0:
start= start+1
for i in r... |
a3d26ec08a1c3bb33a279beccce1261c066ec4ec | cztaylor/GameBots | /TicTacToe/Game/TicTacToe.py | 847 | 3.796875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sun May 6 13:47:41 2018
@author: chrtaylo
"""
import board;
import teams;
b = board.Board()
gameTeams = teams.TeamList("X","O")
def turn(board,team):
print("Current State of Board:")
b.printBoardStateCoordinates()
space = int(input("Select a space for team " + te... |
4e2055b4b0b60e485f51167a89327b6b1f696539 | MeilingLiu1997/Python | /Lab/Lab 3/blackjack.py | 2,568 | 3.921875 | 4 | import random
def getCard(score):
score = random.randint(1, 11)
return score
def displayScore(playerscore, computerscore):
print("The player's score:", playerscore)
print("The computer's score:", computerscore)
def checkResults(playerscore, computerscore):
if playerscore > 21 and computerscore ... |
0e7c6401fd5dc14812da4d74aa37cb7074badad0 | accelero-cloud/tutorials | /various/hacks/ioc.py | 4,865 | 3.59375 | 4 | """
Non-invasive Dependency Injection Container.
It fills given constructors or factory methods
based on their named arguments.
See the demo usage at the end of file.
"""
import logging
NO_DEFAULT = "NO_DEFAULT" # pylint: disable=C0103
class Context(object):
"""A dependency injection container.
It detects t... |
4a70166fd27811bd861179c601acdffacf237872 | Jonathan-aguilar/DAS_Sistemas | /Ago-Dic-2017/Omar Abasta/PrimerParcial/PrimerParcialArqui.py | 2,852 | 3.796875 | 4 | class Electrodomestico(object):
def_init_(self, marca="", color="",modelo="", tipo="", size=""):
self.marca = marca
self.color = color
self.modelo = modelo
self.tipo = tipo
self.size = size
def factory(clase = "television", **parametros):
c = clase.upper()
if c == "lavadora"... |
5ff46bef5993ac95cb3dd8375c6971a9dd27a909 | papalagichen/algorithm-utils | /ListBuilder.py | 940 | 3.65625 | 4 | class ListNode:
def __init__(self, x):
self.val = x
self.next = None
def __str__(self):
s = ''
p = self
while p:
s += str(p.val)
if p.next:
s += ' -> '
p = p.next
return s
def __eq__(self, other):
r... |
b3c2a554e2c48de25cb9a31b93168db988acc844 | ndwei97/python_project | /Week 7 lab/Krenn_Cho_Fei_LabWk7b_Skrenn.py | 3,103 | 4.25 | 4 | # Steven Krenn
# Sangmin Cho
# Eric Mingfei
# Date created: 5/2/17
# Data modified: 5/2/17
# gets gallons of gasoline from the user, and converts it
# to liters, barrels, co2, energy, and USD.
# Has a menu function that lets the user pick
# which convertion to apply.
# function to convert to liters
def convert_to_lit... |
93abf5aef4bbff9828e57d81c86070b1312f3cfe | BhushanTayade88/Core-Python | /Feb/day 21 duck typing/hasattr.py | 244 | 3.578125 | 4 | class A:
def m1(self):
print("m1---of A")
class B:
def m2(self):
print("m2--- of B")
def comman(obj):
if hasattr(obj,"m1"):
obj.m1()
elif hasattr(obj,"m2"):
obj.m2()
comman(B())
comman(A())
|
2fcd503e76509688d59f90c0c2ec1ec29fb4ebe9 | kesh7644/cricquiz | /V4/v4_user details.py | 281 | 4.0625 | 4 | #Ask for name by using greet function
def greet():
global name
while True:
name = input("Please enter your name : ")
if name.isalpha():
break
print("Please enter your name in alphabets only.")
greet()#calling the greet function
|
55b8f82f4b24c435e4c5d7ad031e13a9cadb912f | dkdhinakaran/mypython | /strings/7-string-check-character-count-3.py | 253 | 3.953125 | 4 | ###counting the charater in the string...
#!/usr/bin/env python3
inp_str = input("Enter the string\n\t")
x=set()
result = ''
for i in inp_str:
if i not in x:
x.add(i)
result=result+str(inp_str.count(i))+i
print(result)
|
f895b103f8eedf900e7caa70ae17f243069d6a4b | itsolutionscorp/AutoStyle-Clustering | /all_data/exercism_data/python/bob/6c84ee666c234f6da8e573afc71d25e7.py | 429 | 3.5 | 4 | def hey(what):
def is_silence():
return len(what.strip()) == 0
def is_shouting():
return any(map(lambda c: c.isalpha(), what)) and what.upper() == what
def is_question():
return what.rstrip().endswith("?")
if is_silence():
return "Fine. Be that way!"
if is_shoutin... |
47f7d2e6bb21172a789d2f7c0cdf1bc2a266a227 | gschen/sctu-ds-2020 | /1906101114-胡艳萍/Day0225/test03.py | 660 | 3.703125 | 4 | # 练习:
# 1、找最大值
# list1=[1,2,3,4]
# a=0
# for i in list1:
# if i>a:
# a=i
# print(a)
# 2、数值的求和
# list2=[1,2,3,4,'a',1]
# sum=0
# for i in list2:
# if isinstance(i,int): # isinstance()函数用来判断一个对象是否是一个已知的类型,类似type()
# sum+=i
# print(sum)
# 3、判断是否为素数
# x=5
# for i in range(2,x):
# if x%i=... |
c5942391507734c3bf318c688f04b55564f2a790 | havenshi/cc150 | /Q1.7.py | 431 | 3.921875 | 4 | def label(matrix):
m = len(matrix)
n = len(matrix[0])
row = [0] * m
col = [0] * n
for i in range(m):
for j in range(n):
if matrix[i][j] == 0:
row[i] = True
col[j] = True
for i in range(m):
for j in range(n):
if row[i] or col... |
131c81d3f7eaf3205907c58c632412fcdf78446f | cassking/python-practice | /lists.py | 1,296 | 4.09375 | 4 | courses =['history', 'math', 'science', 'stuff']
print(len(courses))
print(courses[0])
print(courses[-1])
print(courses[0:2])#get range first index inclusive second index is not
print(courses[1:])#assumes from index to end of array
nums =[1,5,2,7,4]
courses_3 =['historyxxx', 'mathxxx', 'sciencexxx', 'stuffxxx']
#modif... |
046309c092eba66195ea8a368edb7975eed774f6 | shivap483/data-structures | /G4G_python/g4g_arrays/minimum_element_in_sorted_rotated_array.py | 471 | 3.625 | 4 | def findMinElement(arr, low, high):
if(high<low):
return -1
if(high==low):
return arr[low]
mid= int((high+low)/2)
if(mid<high and arr[mid]>arr[mid+1]):
return arr[mid+1]
if(mid>low and arr[mid-1]>arr[mid]):
return arr[mid]
if(arr[high]>arr[mid]):
return findMinElement(arr, l... |
4dc07564284e91eec488c4429aff331b5b25e08f | noobul/PythonTraining | /Ch10/10-1/text_program_thing.py | 686 | 3.640625 | 4 | filename = "Ch10/10-1/test.txt"
file_lines = []
with open(filename) as file_object:
#prints entire file
content = file_object.read()
print(content.rstrip())
with open(filename) as file_object:
#prints file content line by line
for line in file_object:
print(line.rstrip())
with open(f... |
0b9cc3ceff56e205cb7e8160524a96f53309a16b | DimAntDim/Python_Modules_Examples | /challenges/recursive_graph/solution/snowflake_turtle.py | 580 | 3.75 | 4 | #
# Example: snowflake
#
# topics: functions, recursion
#
__author__ = "Kristian Rother, Nils Goldmann"
from turtle import *
import time
def move_to(x,y):
up()
setx(x)
sety(y)
down()
def curve(length, depth):
if depth==0:
forward(length)
else:
curve(length*0.333,depth-1)
... |
8ee37497a745bc0ab88832315d43eccf47d14637 | mgracioli/conexaoSQLitePython | /usuario.py | 1,040 | 3.859375 | 4 | #cria um modelo de usuário
class Usuario(object):
#método construtor
def __init__(self, nome, telefone, email, cpf):
self.__nome = nome #o __ informa que essa variável é do tipo private. Em python não existe variável privada, então, isso é só uma convenção para dizer que essa variável deve ser... |
0fd1435df109d76912edfea40520671c846b1ab9 | Erniejie/python_Student-Data-Management-Program | /2021-08-16_Python_Student Data Management Program.py | 2,198 | 4.09375 | 4 | #python_Student Data Management Program
"Computer Programming Tutor,9th July 2021"
#1. Create Class Student
class Student:
def __init__(self,name,rollno,score1,score2):
self.name = name
self.rollno = rollno
self.score1 = score1
self.score2 = score2
#2.Function to C... |
01fa1cd43a52e2976ad89eb5d044595993f3a0bb | HiperbolickiParaboloid/Homework-2 | /zad2.py | 953 | 3.5 | 4 | def funkcija_map(y): #kvadrira elemente
return y**2
def funkcija_filter(y): #vraca prirodne brojeve
if y>=0:
return True
else:
return False
def funkcija_reduce(x,y): #sumira
return x+y
def MAPP(funk, iterab): #realizovana MAP funkcija
for x in range (0, len(iterab)):
itera... |
93b9efca85aff5d86c1c7855442561fea978f5c7 | MrinmoyBhattacharjee/Python_Practice | /List related/list_prac5.py | 572 | 3.96875 | 4 | l1=[11,3.45,4+5j,True,"Mrinmoy"]
#l2=[100,200,300]
#l3=l1+l2 # joining list
#print(l3)
#print(l2*3)#replicating a list
#slicing a list list_variable[start:stop:step] by default step 1
# it will work upto stop-1
l2=[11,22,33,44,55,66,77,88,99,100]
print("l2[1:4]",l2[1:4]) #list slicing
print("l2[3:-3]",l2[3:... |
0a369c9f65722ba1e48d36d61cf43bb1e42388d4 | aosid/prog | /euler/project euler 56.py | 974 | 3.8125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Wed Dec 26 11:27:13 2018
@author: vcian
"""
"""A googol (10^100) is a massive number: one followed by one-hundred zeros;
100^100 is almost unimaginably large: one followed by two-hundred zeros.
Despite their size, the sum of the digits in each number is only 1.
Considering na... |
ff24c7cfd1009e3904214f155d75efb5e5e74f0b | SarahJHMun/python_210119 | /02_condition/quiz04/quiz04_1.py | 357 | 3.734375 | 4 | # 1. 두 점수를 입력 받고, 평균이 70점 이상이면 합격 그렇지 않으면 불합격을 출력하세요.
score1, score2 = input("두 점수를 입력하세요:").split()
score1 = int(score1)
score2 = int(score2)
average = (score1 + score2) / 2
if average >= 70:
print("합격입니다.")
else:
print("불합격입니다.")
|
0781d7fd582db9a672d3df05ef54de345db912e6 | shrivastava-himanshu/Python-Programs | /pythagorean_triplet.py | 395 | 4.0625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Wed Dec 5 22:00:47 2018
@author: shrivh1
"""
def pythagorean_triplet():
peri = 1000
for a in range(1, peri + 1 ):
for b in range(a+1, peri +1):
c = peri - a - b
if a*a + b*b == c*c:
print(str(a ) +' '+ str(b) ... |
a6f15bf5c998aeaf55b674b3ee326ec8c32ec090 | aming0518/PythonStudy | /身份运算符.py | 218 | 3.890625 | 4 | num1=3
num2=3
print(id(num1),id(num2))
if num1 is num2:
print("同一个地址 ")
num1=4
if num1 is num2:
print("同地址")
else:
print("不同地址")
#is is not 判断地址是否相同 |
dbd95d26f724eef8a02dd50e2a9cb04ed81874d3 | lichangg/myleet | /classify/c_list/21. 合并两个有序链表.py | 1,257 | 3.71875 | 4 | #!/usr/bin/env python
# -*- coding:utf-8 -*-
from utils.util_funcs import ListNode,gen_list
# 迭代
class Solution:
def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode:
dummy = ListNode(0)
if not l1 or not l2:return l1 or l2
if l1.val<l2.val:
dummy.next = l1
... |
cbb10b24e5bdcdc8178ce676753e9581e7176305 | inkjet/FBS_Power5 | /populate_db.py | 2,552 | 4.125 | 4 | # -*- coding: utf-8 -*-
"""
Script to populate the database of "Big 5" and "Other FBS" schools
Uses example of scraping a Wikipedia table as documented here:
http://adesquared.wordpress.com/2013/06/16/using-python-beautifulsoup-to-scrape-a-wikipedia-table/
Project page: https://github.com/inkjet/FBS_Power5
Author: S... |
667ea219c628a20fa57b04d48074ea7536b25a4d | shaionbd/Bongo-Python-Code-Test | /First Test/test3.py | 1,811 | 4.125 | 4 | """
:TODO Answer of "Explain the Runtime and Memory requirements for your solution."
Explanation of the Runtime and Memory requirements for my solution.
Time Complexity: Time complexity of above solution is O(h) where h is height of tree. Because you call the wile loop from
bottom(node_left/node_right) and jump it's p... |
0308016cfff9f9d053f60d86bd7bd4d6f33d5d9c | uiblee/Exercise09 | /lettercount.py | 1,148 | 4.15625 | 4 | from sys import argv
#Get filename and open file
#Store file in a string
script, file_name = argv
my_file_contents = open(file_name).read()
#Convert the file string to all lower case
lowercase_file = my_file_contents.lower()
# Create an empty list of 26 spaces to use as a counter
counter = []
for i in range(0,26):... |
2a5b34ed14f5f0f5ba2ce1990956e93bda605abc | bronydell/python-cipher | /magic.py | 653 | 3.6875 | 4 | # Метод
import numpy as np
def encrypt(text, key):
w = h = len(text) / len(key)
x = 0
y = 0
result = ""
while x < h:
result += text[key[x][y] - 1];
y += 1
if y > w - 1:
y = 0
x += 1
return result
def decrypt(text, key):
key = key.flatten()... |
d76c077f61296ef3bafa332d90a8d27be55c5663 | joyrexus/CS212 | /homework/unit_4/bridge/successor.py | 4,383 | 3.765625 | 4 | # write a function, bsuccessors2 that takes a state as input
# and returns a dictionary of {state:action} pairs.
#
# The new representation for a path should be a list of
# [state, (action, total time), state, ... , ], though this
# function will just return {state:action} pairs and will
# ignore total time.
def s... |
946bb29d9b29e34ee85d8f9e72c1238d646bd856 | jhonatanx123/Python | /Python/Lab for Section 7.4.py | 746 | 4.03125 | 4 | #Test phone with output "ehnop"
#Test Forty seven days till Christmas with output " CFaadeehiillmnorrsssstttvyy"
#Test 47 days till Christmas with output " 47Caadhiillmrssstty"
#Test Santa will bring 5 presents and $20 dollars to house number #9110 for jenny. with output " #$.0011259Saaabbdeeeeefgh... |
2a5285df6be25d49f01ce7b269a47deb8f8d2b81 | jdleo/Leetcode-Solutions | /solutions/121/main.py | 476 | 3.640625 | 4 | class Solution:
def maxProfit(self, prices: List[int]) -> int:
# max profit and current minimum price
maxProfit, curMin = 0, float('inf')
for price in prices:
# compare this price to curmin
if price < curMin:
# this is a new curmin
cur... |
951190988919f864f034d413535785b3ea6b2bc5 | mathvolcano/leetcode | /0246_isStrobogrammatic.py | 454 | 3.703125 | 4 | """
246. Strobogrammatic Number
https://leetcode.com/problems/strobogrammatic-number/
"""
class Solution:
def isStrobogrammatic(self, num: str) -> bool:
dual = {'0': '0',
'1': '1',
'6': '9',
'8': '8',
'9': '6'}
for i in range(len(num) /... |
7ea108feb16c974b3af15cb4ad36363f36aeaa9b | estroud1991/Python-Examples | /Holdings and trades final exam/Stock holdings and trades Final exam.py | 5,737 | 3.828125 | 4 | ####YOU MAY NOT USE DICTIONARIES ANYWHERE IN THIS PROGRAM#####
####YOU MAY NOT USE DICTIONARIES ANYWHERE IN THIS PROGRAM#####
####YOU MAY NOT USE DICTIONARIES ANYWHERE IN THIS PROGRAM#####
####YOU MAY NOT USE DICTIONARIES ANYWHERE IN THIS PROGRAM#####
###
###
### Type your name here: Erik Stroud
###
##
## Look at the f... |
028414679ecb5a72a482b6454b2f08ae792a96c3 | stuartstein777/CodeWars | /6KYU/CamelCase Method/solution.py | 131 | 3.984375 | 4 | def camel_case(s):
words = s.split(" ")
capitalized = [word.capitalize() for word in words]
return "".join(capitalized) |
f216513f89444d42374196778e0d1f0f2eb13a03 | lindo-zy/python-100 | /python-015.py | 449 | 3.875 | 4 | #!/usr/bin/python3
# -*- coding:utf-8 -*-
'''
题目:利用条件运算符的嵌套来完成此题:学习成绩>=90分的同学用A表示,
60-89分之间的用B表示,60分以下的用C表示。
程序分析:程序分析:(a>b)?a:b这是条件运算符的基本例子。
'''
score = int(input('输入成绩:'))
if score >= 90:
grade = 'A'
elif score >= 60:
grade = 'B'
else:
grade = 'C'
print('%d属于%s' % (score, grade))
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.