blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
22de806668c99419b3de64c23f91b450aeafcd73 | brittani-ericksen/dec2020-dir | /week_01/python2/small_exercises.py | 383 | 4.03125 | 4 | # python 102 small exercises
numbers = [-2, -1, 0, 1, 2, 3, 4, 5, 6]
#1 sum of numbers
sum_of_all_numbers = sum(numbers)
#print(sum_of_all_numbers)
#2 largest number
max_number = max(numbers)
#print(max_number)
#3 smallest number
min_number = min(numbers)
#print(min_number)
#4 even numbers
#5 positive numbers
#... |
69c622768ed49e6180ddd9484322d528fdc784ad | kuralayenes/PythonUygulama | /Uygulama11.py | 624 | 3.5 | 4 | rs = input("Romen rakamlarıyla sayıyı giriniz: ")
k1 = 0
sy = 0
print("\n")
for i in range(0,len(rs),1):
k2 = k1
deger = rs[i]
if (deger == 'I'):
k1 = 1
elif (deger == 'V'):
k1 = 5
elif (deger == 'X'):
k1 = 10
elif (deger == 'L'):... |
f8a5b047d10bb1fdf12283857e226b4c4b31774e | tcarrio/cse233-dicts-sets | /prog3.py | 1,755 | 3.859375 | 4 | # Author: Tom Carrio
# Course: CSE-233
import sys
def setup_files():
if(len(sys.argv)==4):
infile=sys.argv[2]
outfile=sys.argv[3]
return infile,outfile
else:
fail_message("Not the correct number of args")
return
def setup_ciphers():
tmp_cipher=[c for c in "lpDzQ2FE... |
2413127b081dc6fddf49bec5ee1e545a1047f6a1 | caylemh/Python | /chapter_6/pg171_TryItYourself.py | 3,737 | 4.15625 | 4 | # People - Create a list(people) of dictionaries (person_*) and display them
print('People and their info:')
person_0 = {
'firstname': 'Caylem',
'lastname': 'Harris',
'age': 36,
'city': 'JHB',
}
person_1 = {
'firstname': 'Courtney',
'lastname': 'Alexander',
'age': 17,
'city': 'JHB',
}
pe... |
38eaf2876b6aaec5b3d3fa39722bee69a7f64583 | saeidp/Data-Structure-Algorithm | /Stack and Queue/StackDecimalToMultipleBase.py | 821 | 3.90625 | 4 | class Stack:
def __init__(self):
self.items = []
def isEmpty(self):
return self.items == []
def push(self, item):
self.items.append(item)
def pop(self):
return self.items.pop()
def peek(self):
return self.items[len(self.items) - 1]
def... |
bec5371bf938991bca1eb5b42bed4409513e2d92 | swaraj1999/python | /chap 4 function/greatest_function.py | 441 | 4.25 | 4 | # to find the greatest number #function inside function
def greater(a,b):
if a>b:
return a
return b #it is finding the greater function in two number
def greatest(a,b,c):
return greater(greater(a,b),c) #it will find among three
print(greatest(100000000,200,1200))
... |
68d30964085fd5a3802bfd83ba93aea64ea7b1cb | nbuyanova/stepik_exercises | /exercise_2_6__1.py | 757 | 4.21875 | 4 | # Напишите программу, которая считывает с консоли числа (по одному в строке) до тех пор, пока сумма введённых чисел
# не будет равна 0 и сразу после этого выводит сумму квадратов всех считанных чисел.
#
# Гарантируется, что в какой-то момент сумма введённых чисел окажется равной 0, после этого считывание продолжать
# н... |
8f8d61a23e300797e5d9ec658a2cbd37e9f84dfe | Stefiya/python | /upper.py | 148 | 3.6875 | 4 | a=input("enter a word")
class A:
def __init__(self,upper):
self.upper=upper
def up(self):
print(a.upper())
d=A(a)
d.up()
|
2c62d333a823eae6bedaa93e22e7923fc2c526d1 | spoty/Checkio | /MINE/08_Painting_wall.py | 3,159 | 3.671875 | 4 | # from bisect import bisect_left
# def binary_search(a, x, lo=0, hi=None): # can't use a to specify default for hi
# hi = hi or len(a) # hi defaults to len(a)
# pos = bisect_left(a,x,lo,hi) # find insertion position
# return pos if pos != hi and a[pos] == x else -1 # don't w... |
71b438d41458431f9cad540083ad717687fe0edf | JacobRammer/CIS122 | /assignments/Assignment 4/cis122-assign04-yearday-v2.py | 9,713 | 4.375 | 4 | '''
CIS 122 Fall 2018 Assignment 4
Author: Jacob Rammer
Partner: None
Description: Assignment 4 version 2
'''
def is_leap_year(year):
"""Determine is inputted year is a leap year
Tests if year is a leap year
Args:
year (Int): information to test
Returns:
True if true or False if false
... |
3b5260f915b40e19b1f2a23b67e9ac35baf9b434 | SulabhAgarwal007/Python_Machine_Learning | /Bokeh/Bokeh_Select_Dropdown.py | 1,398 | 3.609375 | 4 | # Perform necessary imports
from bokeh.models import ColumnDataSource, Select
from bokeh.plotting import figure
from bokeh.io import curdoc
from bokeh.layouts import row
import pandas as pd
data = pd.read_csv('literacy_birth_rate.csv')
fertility = data['fertility'].values
female_literacy = data['female litera... |
829804bcf14a0aec6ec9a95042040760578d27fc | yosuke-ippo/Atcoder | /submissions/abc201/b.py | 238 | 3.53125 | 4 | N = int(input())
yama_list =[]
for i in range(N):
namae, takasa = input().split()
takasa = int(takasa)
yama_list.append([namae,takasa])
ans_list = sorted(yama_list, reverse= True, key=lambda x: x[1])
print(ans_list[1][0])
|
cdbb96e8d7a25f82e492f84c9f1f6340dfd7145d | miriamnwachukwu/TestRepo | /Script.py | 321 | 3.96875 | 4 | greeting = 'Hello'
name = 'Michael'
message = greeting + ', ' + name + '. Welcome!'
#message = f'{greeting}, {name}. Welcome!'
print(f'The value of pi is approximately {name}.')
print(message)
# x = '''Bobby was a good kid
# until he got to university'''
# print(x)
# print(help(str))
#new line
#another new line... |
543e64f2c1cef0715a989453659eac6447b7d52e | mrapacz/ntgen | /ntgen/utils.py | 2,133 | 3.9375 | 4 | import re
from typing import Optional
def normalize_field_name(name: str, leading_undescores_prefix: Optional[str] = None) -> str:
"""
Normalize a string to take a Pythonic form.
Normalize a string to take a Pythonic form by:
- replacing leading underscores with a given (optional) prefix
- conver... |
75ff28ffa6678faffa6608e069c351e5449ac274 | ctanamas/cs50_houses | /import.py | 822 | 3.90625 | 4 | # Imports needed classes
import csv
from sys import argv, exit
from cs50 import SQL
def main():
# Checks correct usage
if len(argv) != 2:
print("Usage: python import.py data.csv")
exit(1)
# Opens the csv and the database
db = SQL("sqlite:///students.db")
with open(argv[1], "r") a... |
3754a73176e4f14f402a1808e474ef661fd18757 | nickeyinho/Python_course | /PY1_Lesson_2.1/week_temperature_by_city.py | 550 | 3.765625 | 4 | # пример того, как читать сложные файлы
# pretty print - красивое печатет словари, списки и пр.
from pprint import pprint
cities = {}
with open('week_temperature.txt') as f_week_temperature:
for city in f_week_temperature:
temperatures = f_week_temperature.readline()
cities[city.strip()] = temperatures.split()
... |
cd827ea903961d564401166da589fc460ad1a888 | nestor2502/Modelado | /python/oop.py | 391 | 3.828125 | 4 |
class Employee:
def __init__(self, first, last, pay):
self.first = first
self.last = last
self.pay = pay
self.email = first+'.'+last+'@company.com'
def fullName(self):
return '{} {}'.format(self.first,self.last)
emp_1 = Employee('Corey', 'schafer', 5000)
emp_2 = Employee('vazquez', 'nestor', 6000)
#pri... |
95c656aae6a654a20dd08a344dbedc6463abbb3c | vavronet/python-for-beginners | /functions/examples/example_5.py | 343 | 4.0625 | 4 | import datetime
def greetings():
now = datetime.datetime.now()
hour = now.hour
if hour <= 11 and hour >= 3:
return 'Good morning'
elif hour >= 12 and hour <= 18:
return 'Good afternoon'
elif hour >= 19 and hour <= 21:
return 'Good evening'
else:
return 'Good nigh... |
aa75186085b3d22af2778dfd33352fd0166661c5 | umeshgeeta/Python | /FindPathsInGraph.py | 4,993 | 3.859375 | 4 | # author: Umesh Patil
# November 9, 2019
# Finds number of paths and cycles in a random generated graph. Edge is redirections.
# When a value in the adjecancy graph cell [i][j] is > -1; it means there is an edge
# goinf from 'i' node to 'j' node. Nodes will be numbered from 0 to m-1 for m nodes graph.
#
# Assumptions:... |
00a16a27332244fd3aad683f1630c71fc9acbde3 | LucasLeone/tp1-algoritmos | /estructura_secuencial/es5.py | 435 | 4.03125 | 4 | '''
Si un lote de terreno tiene X metros de frente
por Y metros de fondo: calcular e imprimir la
cantidad da metros de alambre para cercarlo.
(X e Y serán leídos al comenzar el programa).
'''
x = float(input('Cuantos metros de frente tiene el terreno? '))
y = float(input('Cuantos metros de fondo tiene... |
864f3525b6108ea7eb7bd987748ad65ec40c5c14 | bqth29/simulated-bifurcation-algorithm | /src/simulated_bifurcation/simulated_bifurcation.py | 33,248 | 3.625 | 4 | """
Module defining high-level routines for a basic usage of the
simulated_bifurcation package.
Available routines
------------------
optimize:
Optimize a multivariate degree 2 polynomial using the SB algorithm.
minimize:
Minimize a multivariate degree 2 polynomial using the SB algorithm.
maximize:
Maximiz... |
fa8b56d81d03077d615920df4df46669cfca8b0d | blane612/-variables | /example_code.py | 2,062 | 4.75 | 5 | # author: elia deppe
# date: 6/6/21
#
# description: example code for variable exercises
# Saving a String to a variable.
name = 'elia'
# ----- Printing the contents of the variable.
print('my name is', name) # using regular strings
print(f'my name is {name}') # using f-strings
# When inserting a variable ... |
b19231bf909e93a44a8a67e3d8aa5baef1864951 | WeDias/RespCEV | /Exercicios-Mundo1/ex016.py | 74 | 3.859375 | 4 | num1 = float(input('Digite algum numero: '))
print('{:.0f}'.format(num1)) |
3946afc72e6ed2a4dd023130639a9d2b1f310aed | buy/cc150 | /1.8.is_rotation.py | 381 | 4.125 | 4 | def isSubstring(string1, string2):
return string1 in string2
def isRotation(string1, string2):
if type('') is not type(string1) or type('') is not type(string2):
raise Exception('Not Strings!')
if len(string1) is not len(string2):
return False
else:
return isSubstring(string1, string1 + string2)
... |
a0be796a375d94927bc6b234f57b459bd94fbc0d | dw2008/coding365 | /201904/0419.py | 501 | 4.15625 | 4 | #Given an array A of integers, return true if and only if it is sorted in ascending order.
#
#sorted means: A[0] < A[1] < ... A[i-1] < A[i]
#Example 1:
#Input: [2,1]
#Output: false
#Example 2:
#Input: [3,5,5]
#Output: true
#Example 3:
#Input: [0,3,2,1]
#Output: false
def isSorted(alist) :
for i in range(1,... |
b2093b426a215b0c86c004d49d3edde56922d092 | hansrajdas/algorithms | /Level-1/gcd_and_lcm.py | 397 | 4.09375 | 4 | #!/usr/bin/python
# Date: 2018-09-23
#
# Description:
# Find GCD(or HCF) and LCM of 2 numbers.
def gcd(a, b):
return gcd(b, a % b) if b else a
def main():
a = int(input('Enter first number: '))
b = int(input('Enter second number: '))
g = gcd(a, b)
print('GCD is: %d' % g)
l = (a * b) / g # Because a... |
0b34f9a9ff7d6f106c47cb9b41048d4e1a248334 | ArchAiA/lpthw | /ex19.py | 1,200 | 4.40625 | 4 | #The variables in a function, and the arguments identified in a function definition are not connected
#unless they are explicitly passed
#this is the function definition. It takes two arguments, and outputs them in strings
def cheese_and_crackers(cheese_count, boxes_of_crackers):
print "You have %d cheeses!" % chee... |
268cc75ed772c79ce00ebd3fbf7345f6a3faa1c4 | Jeffrey1202/comp9021 | /midterm/z5141180.files/question_5.py | 1,619 | 4.34375 | 4 |
def f(word):
'''
Recall that if c is an ascii character then ord(c) returns its ascii code.
Will be tested on nonempty strings of lowercase letters only.
>>> f('x')
The longest substring of consecutive letters has a length of 1.
The leftmost such substring is x.
>>> f('xy')
... |
17601d36f7cc6cde5f46175e37042d5fbad59dbb | cryoMike90s/Daily_warm_up | /Dictionaries/ex_38_average_instead.py | 512 | 3.90625 | 4 | """Write a Python program to replace dictionary values with their average."""
student_details= [
{'id' : 1, 'subject' : 'math', 'V' : 70, 'VI' : 82},
{'id' : 2, 'subject' : 'math', 'V' : 73, 'VI' : 74},
{'id' : 3, 'subject' : 'math', 'V' : 75, 'VI' : 86}
]
def average_me(number_1: float, number_2: float):... |
bdf81e6144246f4d627f9c341a63b61b92c3499a | KaterinaMutafova/SoftUni | /Programming Basics with Python/Conditional_statements/Condex_ex1_minute_sec.py | 315 | 3.890625 | 4 | first_sec = int(input())
second_sec = int(input())
third_sec = int(input())
total_sec = first_sec + second_sec + third_sec
total_minutes = total_sec // 60
left_sec = total_sec % 60
if left_sec > 9:
print(f"{total_minutes}:{left_sec}")
else:
print(f"{total_minutes}:0{left_sec}")
|
b6585d63f634ac0486c969377483ba562b5d0fcb | rafaelperazzo/programacao-web | /moodledata/vpl_data/55/usersdata/133/24237/submittedfiles/av2_p3_civil.py | 801 | 3.78125 | 4 | # -*- coding: utf-8 -*-
from __future__ import division
import numpy as np
# calcula o peso da matriz para um elemento na posição de linha a e coluna b
def peso(X, a, b):
s = 0
t = 0
for j in range(0, X.shape[0], 1):
if(j!=b):
s = s + X[a,j]
for i in range(0, X.shape[0], 1):
... |
415acca1654e9d78abf8bdba3f65e3bd68d3c730 | Gracekanagaraj/positive | /s8.py | 64 | 3.515625 | 4 | num=int(input())
ss=0
for i in range(1,num+1):
ss+=i
print(ss)
|
ebd4d5883f5292e4236429869089db9530ac2b85 | asterinwl/2021-K-Digital-Training_selfstudy | /5.26/13_Bulit-in-function/fun_ext.py | 2,028 | 4 | 4 | #재귀함수
'''
def selfCall():
print('ha', end='')
selfCall()
selfCall() #ha 계속 생기고 오류생김
'''
def selfcall(num):
if num==0:
return
else:
print('ha', end="")
selfcall(num-1)
selfcall(5)
print('')
#팩토리얼 계산
def fact(num) :
if num==1:
ret... |
48ce18e4d21154fb7284e810d158c355653f06b0 | babiswas/Practise2 | /test76.py | 421 | 3.625 | 4 | import sys
def string_splitter(str1,chunk_size):
l=[]
index=0
if len(str1)>=chunk_size:
while (chunk_size+index)<len(str1):
l.append(str1[index:chunk_size+index])
index=index+chunk_size
if str1[index:]:
l.append(str1[index:])
return l
if __... |
62b243c60cf3275f0fd7df6c9beff3efed080ff2 | nb341/algo-toolbox | /week2_algorithmic_warmup/6_last_digit_of_the_sum_of_fibonacci_numbers/fibonacci_sum_last_digit.py | 860 | 4.09375 | 4 | # Uses python3
# properties of fib numbers >= 60
import sys
def fibonacci_sum_naive(n):
if n <= 1:
return n
previous = 0
current = 1
sum = 1
for _ in range(n - 1):
previous, current = current, previous + current
sum += current
return sum % 10
def pisano(m):
... |
b505d955ac06b2a84414b6295c34d11d9fcfaa39 | zhenguo96/test1 | /Python基础笔记/4/作业4/中级2.py | 378 | 3.65625 | 4 | '''
2.输出1000以内的所有水仙花数:
水仙花数:一个三位数各个位上的立方之和,等于本身。
例如: 153 = 1(3) + 5(3)+ 3(3) = 1+125+27 = 153
'''
num = 100
while num < 1000:
a = num % 10
b = num // 10 % 10
c = num // 100
if num == a ** 3 + b ** 3 + c ** 3:
print(num)
num += 1
|
3cc783a460a50eff7b41fe5ef5782d037f9dbb08 | devchoplife/DataScience-Python | /Libraries/Python/pyfunctions.py | 2,240 | 4.25 | 4 | type ()#data type
is #retruns true or false e.g x is y will retun true if they are equal
print()#print results
float()#convert to floats
int()# convert to integers
complex()#convert to complex
int# a whole number
float # decimal number
complex # complex numbers
booleans # used together with the numerical operat... |
30c632898475e00ad3ef1fba0b0738095ca424a0 | serenabooth/DistributedComputing | /LogicalClocks/clock.py | 10,551 | 3.5625 | 4 | from datetime import datetime
from threading import *
import sys, time, socket, random, Queue
# cite: http://stackoverflow.com/questions/19846332/python-threading-inside-a-class
# yay decorators
def threaded(fn):
""" Creates a new thread to run the function fn """
def wrapper(*args, **kwargs):
Thread(... |
77f15c28252b89d77de38af29f72e383ab872095 | chunkityip/CodingBat- | /String-2.py | 2,503 | 4.21875 | 4 | double_char
#Given a string, return a string where for every char in the original, there are two chars.
def double_char(str):
count=''
for x in str:
count+=x*2
return count
---------------------------------------------------------------------------------------------------------------------------------------... |
e9d6bca8a5d67c8d14911b02d88f259a4638260c | Epistemological/practice_projects | /h_course/w2/Classes.py | 372 | 3.875 | 4 |
#normal usage of methods
ml = [5,9,3,6,8,11,4,3]
ml.sort()
min(ml)
max(ml)
ml.remove(5)
#create new class
class mylist(list):
def remove_min(self): #instance method
self.remove(min(self))
def remove_max(self): #instance method
self.remove(max(self))
x = [1,2,3,4,5,6,7,8]
y = mylist(x)
dir(y)... |
d3f5f225e7dca2e14aa0946d3a462925fa4e3991 | CiaranPlusPlus/Assur-Graphs-and-Rigidity-Circuits | /AssurGenerator.py | 26,154 | 3.65625 | 4 | #!/usr/bin/env python
"""
Generate a list of all Assur Graphs.
Author: Ciaran Mc Glue
Date of creation start: 25/03/2020
The purpose of this script is to create a comprehensive list of all
possible combinations of Assur Graphs starting with the smallest
'basic' Assur Graphs up to a ... |
06ba92945f0ffec726ab33072e848a30029c29ae | lazsecu/PyGame-Snake | /snake.py | 3,050 | 3.53125 | 4 | import pygame
import sys
import random
import time
pygame.init()
width = 400
height = 400
green = (0, 255, 0)
red = (255, 0, 0)
white = (255, 255, 255)
background_color = (0, 0, 0)
pygame.display.set_caption('Snek')
screen = pygame.display.set_mode([width, height])
clock = pygame.time.Clock()
game_exit = False
fon... |
b05d4a8427da78bedb0cc9cf0b254f503fb8cf47 | xaviruvpadhiyar98/Python-Assignments | /largestContinuousSum().py | 367 | 3.890625 | 4 | #largest Continues SUM problem in given array including negative numbers
def large_cont_sum(arr):
if len(arr)==0:
return 0
max_sum=current_sum=arr[0]
for num in arr[1:]:
current_sum=max(current_sum+num,num)
max_sum=max(current_sum,max_sum)
print(max_sum) ... |
cb471cfb4b4c98957e315ad860be4b5a82cf5f13 | savadev/leetcode-2 | /non_leetcode/fibonacci.py | 651 | 3.75 | 4 | class Solution():
def recursive(self, n):
def f(x):
if x in [0,1]:
return x
return f(x-1) + f(x-2)
return f(n)
def iterative(self, n):
array = [0 for _ in range(n+1)]
array[1] = 1
for i in range(2, n + 1):
array[i... |
42f42fa820fa5b3f1c4172f07155660cdbec0a5a | aka-luana/AulaEntra21_Luana | /Outros/URI/uri_1045.py | 603 | 3.90625 | 4 | a, b, c = input().split()
a = float(a)
b = float(b)
c = float(c)
lista = [a, b, c]
lista.sort(reverse = True)
a = lista[0]
b = lista[1]
c = lista[2]
if (a >= b + c):
print("NAO FORMA TRIANGULO")
else:
if(a ** 2 == b ** 2 + c ** 2):
print("TRIANGULO RETANGULO")
if(a ** 2 > b ** 2 + c ** 2):
... |
302315a10b03e89b72b9a6518258eab425362380 | Nicholas-Fabugais-Inaba/Sudoku | /sudokusolverGUI.py | 14,397 | 3.625 | 4 | import pygame
from sudokusolver import solver, valid_num, create_puzzle, finish_grid, start_grid, find_empty
import time
pygame.font.init()
def generate_Board():
#generate random puzzle
return create_puzzle(finish_grid(start_grid()))
class Grid:
def __init__(self, rows, columns, width, height)... |
af82f0999388418b9bd9a33a4b7e092638c2d593 | jennifersong/advent_of_code | /3/day3a.py | 1,562 | 3.859375 | 4 | import os
from collections import defaultdict
# Santa is delivering presents to an infinite two-dimensional grid of houses.
#
# He begins by delivering a present to the house at his starting location, and then an
# elf at the North Pole calls him via radio and tells him where to move next. Moves are
# always exactly o... |
1c8b52b56cea57fe490e87cfc5624f0c934553f3 | talesritz/Learning-Python---Guanabara-classes | /Exercises - Module I/EX024 - Verificando as primeiras letras de um texto.py | 363 | 4.09375 | 4 | #Crie um programa que leia o nome de uma cidade e diga se ela começa ou não com o nome 'SANTO'
print('-=-'*13)
print('EX024 - Verificando as Primeiras Letras')
print('-=-'*13)
print('\n')
name = input('type your citys name here: ').strip()
splited = name.split()
print('Does the name of the city starts wi... |
5fcd5710f47340e1b526f59e19f0a5e2430793c3 | JerryHu1994/LeetCode-Practice | /Solutions/445-Add-Two-Numbers-II/python.py | 1,101 | 3.65625 | 4 | # Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def addTwoNumbers(self, l1, l2):
"""
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
"""
stack... |
4cb471751bec4c0436b050323c549a193092a561 | karthik-siru/practice-simple | /trees/unique_lines_in_binary_tree.py | 1,203 | 4.21875 | 4 | #question
'''
Given a binary tree root, return the number of unique vertical lines that can be drawn such that every node has a line intersecting it. Each left child is angled at 45 degrees to its left, while the right child is angled at 45 degrees to the right.
For example, root and root.left.right are on the same ... |
9edf429620d081d02b9e27dd4d119b7327ee4e0c | oldomario/CursoEmVideoPython | /desafio23.py | 581 | 4.1875 | 4 | """
Faça um programa que leia um número de 0 a 9999 e mostre na tela cada um dos dígitos separados.
"""
numero = int(input('Digite um número de 0 a 9999: '))
while numero < 0 or numero > 9999:
numero = int(input('Número inválido!!! Digite um número de 0 a 9999: '))
unidade = numero // 1 % 10
dezena = numero // 10 %... |
c3aaff3842144d6e9f5f1de7082e0be48d90a07e | Cameron-Calpin/Code | /Python - learning/Classes/set_functions.py | 1,022 | 3.8125 | 4 | class Set:
def __init__(self, value = []): # constructor
self.data = [] # manages a list
self.concat(value)
def intersect(self, other): # other is any sequence
res = [] # self is the subject
for x in self.data:
if x in other: # pick common items
res.append(x)
return Set(res) # ret... |
4dbda697cfafeaab669386ebdd499a47ae5d26de | S-V-Naidu/Projects | /Python Codes/StockSelecting.py | 921 | 3.578125 | 4 |
def selectStock(saving, currentvalue, futurevalue):
y=[]
for i in range(len(currentvalue)):
c = futurevalue[i] - currentvalue[i]
y.append(c)
y = y.sort(reverse=True)
print(type(y))
print(y)
sum=0
if y is not None:
for i in range(len(y)):
if ... |
7fe17823a5386d16268e7b348e8eaec89e338ae0 | tian5017/LX | /suanfa/动态规划.py | 2,742 | 3.859375 | 4 |
# 动态规划-求两个字符串的最长公共子串(相同字符个数)
# 计算公式:如果对应位置两个字符相等,则此处网格的值位左上角网格的值加1,如果不相等,则为0
def dynamic_str(str1, str2):
if str1 == "" or len(str1) == 0 or str2 == "" or len(str2) == 0:
return 0
row_l = min(len(str1), len(str2))
col_l = max(len(str1), len(str2))
str_arr = [[0 for _ in range(col_l)] for _ in ... |
da136451160c455372b529450114b97572a4b0bc | sanskriti-agrawal/python-lab | /pt2.py | 72 | 3.53125 | 4 | h=int(input())
for i in range(1,h+1):
print(' '*(h-i)+'*'*(i))
print()
|
4da0a3f599de32bec9e1d1d9a63b310234c3b349 | ruddysimon/Python_bank_analysis | /ByBank/main.py | 2,447 | 4.0625 | 4 | import os
import csv
# CSV FILE
csv_file = os.path.join("Resources","budget_data.csv")
# LIST TO STORE DATA
total_month = []
net_total = []
average_change_total= []
average_change = []
great_pdecrease = []
great_pincrease = []
# OPEN AND READ THE CSV FILE
with open(csv_file, newline="") as csvfile:
csv_reader =... |
883bbd0fa617f00c8296854f51829fa2789d3d00 | hjh0915/toronto_exercise | /q6.py | 732 | 3.796875 | 4 | HIT = 'X'
MISS = 'M'
def count_hits_and_misses(board):
""" (list of list of str) -> list of int
Precondition: board != [] and each list in board has len(board)
Return a list that contains the number of occurrences of the
HIT or MISS symbol in each row of board.
>>> board = [['-','M','-'], ['X','... |
0447d2a3760ff795f387802c8e41f5d6c099de7c | mrslwiseman/python | /printTable.py | 504 | 3.84375 | 4 | tableData = [
['apples', 'oranges', 'cherries', 'bananas'],
['Alice', 'Bob', 'Carol', 'David'],
['dogs', 'cats', 'moose', 'goose']
]
def printTable(data):
for cell in range(len(data[0])):
longestWord = 0
for line in data:
for x in line:
if len(x) > longestWord... |
0fda4f79f00a182406a7de168c425d27c8b92127 | Matheus872/Python | /Learning/ex034 (Aumentos múltiplos).py | 153 | 3.78125 | 4 | s = float(input('Insira o salário atual: '))
if s>1250:
sa = 1.1*s
else:
sa = 1.15*s
print('O salário com aumento é de: R${:.2f}'.format(sa)) |
8df5b547cdb45a613d7c0df4cf14b9ef0149e95e | angelortiz0398/dada2020-1 | /Examenes/A-1.py | 737 | 3.59375 | 4 | def numfalta(L,e):
Lc = [0,1,2,3,4,5,6,7,8,9]
s = 0
res = 0
List = L
if len(List) < 9:
if List != Lc:
for i in range(e):
Lc.remove(List[i])
print("Los elementos que faltan ",Lc)
else:
if len(List) == 10:
print("No fa... |
64cb2afa79fd3d6a4bd00b69c683bd3ac92a41ca | junfeiZTE/pythonCode | /列表用法.py | 198 | 3.703125 | 4 | a=[1,2,3,4,5,6]
print(a)
a.append(7)
print(a)
a.insert(1,8)
print(a)
a.remove(4)
print(a)
print(a[3])
print(a.index(8))
print(a.count(4))
a.sort()
print(a)
a.reverse()
print(a)
|
cd69992f6136bb4071feb6771c281f02b5857327 | unet-echelon/by_of_python_lesson | /Molchanov/functions.py | 555 | 3.640625 | 4 | # movie = 'The good, the bad, adn the ugly'
# rating = 100
# resault = f'Movie: "{movie}", rating: {rating}'
# print(resault)
# movie = 'Alien'
# rating = 200
# resault = f'Movie: "{movie}", rating: {rating}'
# print(resault)
greeting = 'Hello'
to = "World"
def greet(message, name):
# print('Hello', name)
res... |
1c5e6580163614935e51745d20f6898360d46992 | bondiano/skillsmart-py | /algorithms/stack.py | 1,289 | 3.890625 | 4 | class Stack:
def __init__(self):
self.stack = []
def size(self):
return len(self.stack)
def pop(self):
if (self.size() == 0):
return None # если стек пустой
return self.stack.pop(0)
def push(self, value):
self.stack.insert(0, value)
def peek(... |
d011a84e5b641515eb0da381a9f01f464e28e67f | pygogogo/author_zmt | /public/str_to_format.py | 841 | 3.78125 | 4 | def strFormatNum(num_format):
new_num = 0
try:
if '亿' in num_format:
new_num = float(num_format.replace('亿', ''))
new_num = new_num * 100000000
new_num = int(new_num)
# return new_num
elif 'w' in num_format:
new_num = float(num_format.r... |
79c05f9f20ae94059e0b4b4bc63ee75bead0ca40 | aaliyah-jardien/python-art | /123.py | 1,100 | 3.765625 | 4 | from tkinter import *
root = Tk()
root.geometry("300x300")
# functions
choice=None
def one():
global choice
choice='Choice 1'
def two():
global choice
choice='Choice 2'
def start():
global choice
if choice=='Choice 1':
elif choice=='Choice 2':
else:
#do something else since the... |
90889b7165fb49caf8c9575c1c43d233796a16c9 | maits/25-small-python-projects | /guess-number-2.py | 490 | 4.03125 | 4 | import random
secret_num = random.randint(1, 1000)
i = 1
user_num = input("Hey there! I'm thinking of a number betweetn 1 and 1000. Do you want to guess it? ")
while secret_num != user_num:
if user_num < secret_num:
print ("Too low. Guess again!")
i += 1
user_num = input("Guess a number ")
elif user_num >... |
41457f3c1924b1896f64716c39b7d2c44fddde10 | vjvarada/Tipo-Braille-Keyboard | /brailleDotToBin.py | 206 | 3.9375 | 4 |
while True:
brailleKeys =0
print("Enter Braille Dot Numbers")
string = str(input())
for char in string:
brailleKeys = brailleKeys | 1 << (6-int(char))
print(bin(brailleKeys))
|
757911cc0b8e5adf42f261a1909ef1b4b52ad5b8 | zhqsherry/Coursera-PY4E | /Sp3 Using Python to Access Web Data/ex_wk6_JSON.py | 739 | 4.03125 | 4 | # Actual data: http://py4e-data.dr-chuck.net/comments_555761.json
# The program will prompt for a URL, read the JSON data from that URL using urllib and then parse and extract the comment counts from the JSON data, compute the sum of the numbers in the file and enter the sum below:
import json
import urllib.reques... |
d463d5ebfd0a83b4907b74aee1b6233efa325a02 | SafonovMikhail/python_000577 | /001703StepPyStudy/Step001703PyStudyсh10_sets_TASK03_20210304_setsIntersec.py | 1,161 | 3.859375 | 4 | '''
Задача «Пересечение множеств»
Условие
Даны два списка чисел. Найдите все числа, которые входят как в первый, так и во второй список и выведите их в порядке возрастания.
Примечание. И даже эту задачу на Питоне можно решить в одну строчку.
'''
a = input()
b = input()
a1 = a.split()
b1 = b.split()
l1 = (list(set(a1) ... |
3f2615f09a5411389a888acf81f810f0d8d0d3f1 | kurenov/algorithms-2 | /w1-p1-greedy-schedule.py | 1,158 | 3.71875 | 4 | ###
# Code by Olzhas Kurenov
# Implementation of Greedy Task Scheduler
# W1 P1
# 1: 69119377652
# 2: 67311454237
###
print '\n~~~~~~~~~Greedy Task Scheduler~~~~~~~~~\n'
# Compares jobs based on score=w-l
# if two scores are the same compares by weight
def comparerDifference(a, b):
# print a, b... |
1ec5502f2f45fdc128171c4b784d10853229c5a3 | mummyli/python_practice | /concurrent_programing/check_thread_start_with_event.py | 627 | 3.65625 | 4 | from threading import Thread, Event
import time
'''
Event对象包含一个可以有线程设置的信号标志
初始状态下Event的信号标志设置为False
线程会一直等待Event信号标志位True
event对象最好单次使用
'''
def countdown(n: int, started_evt: Event) -> None:
print("countdown starting")
started_evt.set()
while(n>0):
print("T-minus", n)
n -= 1
... |
47af14b06661970a66a453c3a5e0e314cae24a58 | garlock402/MonsterSlash | /game.py | 2,218 | 3.6875 | 4 | import random
from actors import Player, Enemy, Ogre, Imp
class Game:
def __init__(self, player, enemies):
self.player = player
self.enemies = enemies
def main():
print_intro()
play()
def print_intro():
print('''
Monster Slash!!!
Ready... |
3436539628248a97f88100936dafb6e4b9d6fb36 | peiyanz/Assessment2_object-orientation | /assessment.py | 5,262 | 4.65625 | 5 | """
Part 1: Discussion
1. What are the three main design advantages that object orientation
can provide? Explain each concept.
Answer: 1.Encapsulation: Whenever we create an instance, all the attribute
and methods come with it.
2.Abstraction: We do not need to know specific info for a method us... |
6e36c13dc5e26e2ca2f316ebb342aab301a07181 | zaslavskayaeg/geek-python | /lesson03/homework3/task6.py | 1,578 | 3.84375 | 4 | # 6. Реализовать функцию int_func(), принимающую слово из маленьких латинских букв и возвращающую его же,
# но с прописной первой буквой. Например, print(int_func(‘text’)) -> Text.
# Продолжить работу над заданием. В программу должна попадать строка из слов, разделенных пробелом.
# Каждое слово состоит из латинских бук... |
af90781bca56b57ed70c9567b2c44d6ca3a165b8 | mohmad011/Other_Interstent | /all_of_project-master/python/mypyton/prject5.py | 641 | 3.9375 | 4 | class calc:
def __init__(self,a,b):
self.a = a
self.b = b
def add(self):
return self.a + self.b
def mul(self):
return self.a * self.b
class powering(calc):
def power(self):
return pow(self.a , self.b)
key = 'yes'
while key == 'yes':
p = poweri... |
edf01996d1666d1c86a9dd488770c23a84c8ac8a | yingxingtianxia/python | /PycharmProjects/my_python_v03/base1/zhan.py | 968 | 4.03125 | 4 | #!/usr/bin/env python3
#--*--coding: utf8--*--
import sys
stack = []
def push_it():
item = input('压栈数据:')
stack.append(item)
return stack
def pop_it():
stack.pop()
return stack
def view_it():
print(stack)
def show_menu():
prompt = """请做出如下选择:
【0】:压栈
【1】:出栈
【2】:查询
【3】:退出
请在(0/1/2/3)中选择... |
44d5e5e402f1760d25e0be0477358e242dcb0820 | chinuteja/CSPP1 | /cspp1-practice/cspp1 assignment/m6/p2/special_char.py | 388 | 3.984375 | 4 | '''
author : teja
date : 4/8/2018
'''
def main():
'''
Read string from the input, store it in variable str_input.
'''
n_n = input()
s_s = " "
for i_i in n_n:
if i_i in "!@#$%^&*/-" :
i_i = ' '
s_s = s_s + i_i
else:
i_i = i_i
s_s =... |
a2589fea35afdc908b225d94c0b1db0e84af39b8 | Josh999999/python-pi-example | /Main.py | 186 | 3.734375 | 4 | print("Hello World")
print("Goodbye World")
def main(msg):
print(msg)
#No longer need comments
# Print a message
main("Hello People")
# This is the next Comment
# Another comment
|
63a16daaa360e324d2d2ff1d8ab56e0dbd5cb29d | MrHamdulay/csc3-capstone | /examples/data/Assignment_2/plltam005/question3.py | 270 | 4.09375 | 4 | import math
k=0
pi=2.0
x=5
while (2/x)!=1:
if k!=0:
pi=pi*(2/k)
k=math.sqrt(2+k)
x=k
print("Approximation of pi:",round(math.pi,3))
radius=eval(input("Enter the radius:\n"))
print("Area:",round(pi*radius*radius,3))
|
ad2ddc9a6f58615d99ac903783a1b6bd9e961250 | godori16/PRML_code | /Chapter3/BasisFunction.py | 457 | 3.546875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Tue Sep 4 14:47:16 2018
@author: TJ
"""
import numpy.matlib as matlib
import numpy as np
def BasisFunction(x, basis_name='polynomial', *options):
if basis_name == 'polynomial':
basis_function = np.power(matlib.repmat(x, options[0]+1, 1).transpose(),
... |
bf9816b2238b3f3eb01d0706103d2bc3be9e56bb | valeriaGratt/Python | /prikluchenie.py | 4,413 | 4.0625 | 4 | print('Забавная история')
print()
h=int(input("""Одним дивным-дивным вечером девушка прогуливалась по центру города.
Вдруг она заметила какое-то движение в с свою сторону. Это был человек странной внешности.
1-Не обращать внимания и пройти мимо
2-Проявить интерес к нему.
(введите цифру вашего ответа)- """))
if h... |
acf79d7dba2ede23ed74b40e27e4731ca00b1432 | Priya-dharshini-r/practice | /matrix_diagoanl.py | 853 | 3.5625 | 4 | import math
list1 = [[1,2,3],[4,5,6],[7,8,9]]
n = len(list1)
# result = 0
# result2 = 0
# odd_length = math.floor(n/2)
p_d = []
s_d = []
for i in range(n):
result = list1[i][i]
p_d.append(result)
print("Primary diagonals",sum(p_d))
# secondary diagonal
for i in range(n):
result2 = list1[i][n-i-1]
# sum1+=result
s... |
092a9d28eec093e96cb39f72886f7a9e8a855564 | Abusagit/practise | /Rosalind/rabbits.py | 241 | 3.734375 | 4 | def rabbits(n, k):
# old = 0 on month 1
old1 = 1 # month n
old2 = 1 #month 2 old
for _ in range(n - 2):
old1, old2 = old2, old1 * k + old2
return old2
if __name__ == '__main__':
print(rabbits(5,3)) |
573172a82a3457e67795b5f4567f9462cb7b7f0f | tytea/itp-u6-c2-oop-hangman-game | /hangman/game.py | 3,392 | 3.625 | 4 | from .exceptions import *
import random
class GuessAttempt(object):
def __init__(self, letter, hit=None, miss=None):
if hit and miss:
raise InvalidGuessAttempt("Can't be both hit and miss")
self.letter = letter
self.hit = hit
self.miss = miss
def is_hit(se... |
58cdd9e9474c3f1fc32978dbd2b89732e905c7cb | YuriiKhomych/ITEA_course | /artem_zhuchenko/2_data_types/hw/artem_zhuchenko_data_types.py | 1,376 | 4.4375 | 4 | #creating car price
car = 100000
#warning the user of increase
print("Price start from 100000$. Please type your parameters. Each one costs 10$.")
#Get car brand:
desired_brand = input("Please type desired car brand: ")
car += 10
#Get car model
desired_model = input("Please type desired model: ")
car += 10
#Get ... |
6bfd3a64721b314f7a779eacb389a3179c5bfc31 | alexdsaguiar/faculdade-impacta | /linguagem_programacao_01/ac04_01.py | 159 | 3.734375 | 4 | s=("abc ")
vowel=0
consonant=0
for letter in s:
if letter in "aeiou":
vowel=vowel+1
else:
consonant=consonant+1
print(vowel+consonant)
|
d57d920aa6501b1ee443b2b02cf3d46efd17fc70 | dexman/AdventOfCode | /2016/aoc09.py | 5,887 | 3.5625 | 4 | # --- Day 9: Explosives in Cyberspace ---
# Wandering around a secure area, you come across a datalink port to a new part
# of the network. After briefly scanning it for interesting files, you find one
# file in particular that catches your attention. It's compressed with an
# experimental format, but fortunately, the... |
5fd9b25c5f0af45b86959b43ecc8ed1143d5273b | urandu/kattis-challenges | /aboveaverage/aboveaverage.py | 478 | 3.65625 | 4 | classes = input()
output1 = []
for i in range(int(classes)):
class_data = input()
marks = class_data.split(" ")
y = 0
total_students = int(marks[0])
marks.pop(0)
marks = list(map(int, marks))
average = sum(marks)/float(len(marks))
for x in marks:
x = int(x)
if x > average... |
cc5ab26fba846fcf0524afdeb7307327a1c345fd | wangchongsheng/fullstack | /week6/day24/继承.py | 1,898 | 3.5625 | 4 | # __author__: wang_chongsheng
# date: 2017/10/25 0025
#子承父类
"""
class F: #父类,基类
def f1(self):
print('F.f1')
def f2(self):
print('F.f2')
class S(F): #子类,派生类
def s1(self):
print('S.s1')
obj=S()
obj.s1()
obj.f2()
"""
#子类只继承父类的某些特性
class F: #父类,基类
def f1(self):
print('F... |
db0eebb22daecdf2e457f6c0da59ca8b3fab94bf | aloksahoo92/learnandbuild | /lnbmerge.py | 1,350 | 4.09375 | 4 | '''
14.MAKE A PROGRAM TO MERGE TWO LIST INTO A
SINGLE DICTIONARIES
● Take inputs from the user
● Any one list must contain unique elements
● both the list should be of the same size
● both the list should be a combination of numbers and names
● Name of dictionary you can take it accordingly
● file name should b... |
fb998c3b96b29df38e11292ba012f9a6dc3c4617 | Max-Stevo/Learning- | /Boolean Table.py | 172 | 4.28125 | 4 | true = True
false = False
if true and false is False:
print('true')
else:
print('false')
if true or false is False:
print('true')
else:
print('false')
|
a11c03c51cd3ab0ae8a0ee9e647e35526ea8631b | coolcatco888/cmpt414-term-project | /character-recognition/prototypes/cley/testwork/layer.py | 2,293 | 3.765625 | 4 | from neuron import Neuron
class Layer:
size = 0 # size of layer aka number of neurons in layer
number_of_inputs = 100 # number of inputs for each neuron aka size of previous
# layer
neurons = [] # list of neurons in layer
def __i... |
e7236b20f385028fc298af384c58aeabe4422e49 | guilhermemaas/guanabara-pythonworlds | /exercicios/ex082.py | 922 | 3.9375 | 4 | """
Crie um programa que vai ler varios numeros e colocar em uma lista.
Depois disso, crie duas listas extras que vao conter apenas os valores
pares e os impares digitados, respectivamente.
Ao final, mostre o conteudo das tres listas geradas.
"""
lista = []
while True:
lista.append(int(input('Informe um valor p... |
8dffa5898317ecfcb4b6588aed74646571627b40 | DurgaMahesh31/Python | /source/Control_Statement.py | 1,087 | 3.875 | 4 |
logger.info("=============== ATM Application ============== #")
logger.info("Insert your card")
logger.info("Enter your password:")
pass_word = input()
# Get Card password from db
# To validate the entered password
# Get card account details and balance
balance = 20000
while True: # while True/Falsee
logger.inf... |
0753dd3fbe932d9f480dc7c498a4e5d2856c4128 | 0xTiefer-Atem/Algorithm-DataStructure-Python | /batch_1/leet_code_168.py | 652 | 3.84375 | 4 | """
Excel表列名称
给定一个正整数,返回它在 Excel 表中相对应的列名称。
例如,
1 -> A
2 -> B
3 -> C
...
26 -> Z
27 -> AA
28 -> AB
...
示例 1:
输入: 1
输出: "A"
示例 2:
输入: 28
输出: "AB"
示例 3:
输入: 701
输出: "ZY"
"""
class Solution:
def convertToTitle(self, columnNumber: int) -> str:
s = ''
while co... |
4957dcc53977e29f7a2c330b13da84a739901e87 | guofei9987/leetcode_python | /solved/[784][Letter Case Permutation][Easy].py | 611 | 3.671875 | 4 | # https://leetcode.com/problems/letter-case-permutation
class Solution:
def letterCasePermutation(self, S):
"""
:type S: str
:rtype: List[str]
"""
if S:
if S[0] in 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ':
return [char+j for char in ... |
ba6709c5dde9f35180414bb455fd817eed619ff5 | Arjun2001/coding | /codechef Bouncing balls.py | 208 | 3.5625 | 4 | import math
test=int(input())
while(test):
m=int(input())
ctr=0
while(m>0):
temp=int(math.log(m,2))
m-=int(math.pow(2,temp))
ctr+=1
print(ctr-1)
test-=1
|
d83887577d4b55edc81cb5f77e316c93f08a8605 | andrewghaddad/OOP | /OOP/Notes/Week7/myprogram.py | 1,292 | 4.375 | 4 | # importing
"""
the import statement tells Python to load the functions that exist
within a specific module into memory
and make them available to use
(import random to use random.randint function)
Because you don't see the inner workings of a function inside of a module,
we sometimes call them "black boxes"
A "blac... |
01a7026976f8ef20da7fa3001498174dc8309d15 | yddong/Py3L | /src/Week1/test3.py | 373 | 3.9375 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
mytext = "hello world"
print(mytext[1])
print(mytext[2:4])
print( mytext[0: : 2 ] )
print(mytext.center(80))
print("Number of es in mytext:", mytext.count("e") )
print("Number of lds in mytext:", mytext.count("ld") )
print(mytext.endswith("ing"))
print(mytext.capit... |
a26aee7c1460872e8e2fca2db4fce8f5f4a82c39 | MrHamdulay/csc3-capstone | /examples/data/Assignment_1/fnsdan001/question2.py | 306 | 4.15625 | 4 | hours = eval(input("Enter the hours: \n"))
minutes = eval(input("Enter the minutes: \n"))
sec = eval(input("Enter the seconds: \n"))
if hours<=23 and hours>=0 and minutes <=59 and minutes>=0 and sec <=60 and sec>=0:
print ("Your time is valid.")
else:
print ("Your time is invalid.")
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.