blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
bb276f9056c88373e092b9880b1b5e6c93ea2500 | carlosvalgar/Apuntes | /CFGS Desarrollo de Aplicaciones Web/M03_Programación/UF2/UF2_Ejercicios_De_Prueba/Funciones.py | 1,019 | 3.953125 | 4 | # Función con parámetros y con return
def suma1(a, *b):
resultat = a
for x in b:
resultat += x
return resultat
# Función con parámetros y sin return
def suma2(a, *b):
resultat = a
for x in b:
resultat += x
print(resultat)
# Función sin parámetros y con return
def suma... |
198e58c6e253ff2aa037213621308c4f96439531 | HendryRoselin/100-days-of-python | /Day02/funcode2.py | 462 | 4.15625 | 4 | ## Script for splitwise calculator
print("This is Splitwise calculator")
x = float(input("What was the total amount? $"))
y = int(input("What percentage tip did you give? 10, 12, or 15"))
z = int(input("How many people in total to divide?"))
answer = (y / 100 * x + x) / z
print(f"Each needs to contribute: {answer}")... |
9251bba080eeb88234ad34f853ff63069316640c | MrHamdulay/csc3-capstone | /examples/data/Assignment_3/nckkem001/question1.py | 147 | 3.875 | 4 | y=eval(input("Enter the height of the rectangle: \n"))
x=eval(input("Enter the width of the rectangle: \n"))
for i in range(y):
print(x*"*") |
e52e35d3f9160346525b3abc2846d8cc2dd99ff1 | Rksseth/Python-Games | /solitaire.py | 9,136 | 3.515625 | 4 | '''
Solitaire
May 10
'''
import random
from tkinter import*
from tkinter import font
root = Tk()
root.title("Solitaire")
root.geometry("700x600")
root.configure(bg = "green")
title = Label(root,text = "Solitaire",font = ('Algerian',20),bg='green',fg = 'white').pack()
class Card(object):
def __ini... |
eed4a9001b9084224e19163d84d53828f2155cd4 | khaldoun11/GIZ-pass-python | /python-pass.py | 672 | 3.890625 | 4 |
class Solution:
#@staticmethod
def longest_palindromic(s: str) -> str:
# Create a string to store our resultant palindrome
palindrome = ''
# loop through the input string
for i in range(len(s)):
# loop backwards through the input string
for j in rang... |
74a74dc1ab4b67102900613ad7cd6bee3096797f | JorgeGallegosMS/universe-quiz | /app.py | 3,540 | 3.984375 | 4 | mult_choice = "Please enter a-d as an answer"
num_response = "Please enter a whole number"
true_or_false = "Please enter 1 for true and 0 for false"
questions_wrong = []
total_score = 0
def correct_answer():
global total_score
total_score += 1
print("Correct!\n")
def wrong_answer(question_number, answer)... |
8953350f20164c344a5f13eaa635cff84edb3113 | amod26/DataStructuresPython | /Binary search tree element.py | 650 | 3.9375 | 4 | # Given two binary search trees root1 and root2.
# Return a list containing all the integers from both trees sorted in ascending order.
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
... |
f34ad75d46185eb271e9d04d19e0ca8396246678 | codershenghai/PyLeetcode | /easy/0263.ugly-number.py | 584 | 3.828125 | 4 | class Solution(object):
def isUgly(self, num):
"""
:type num: int
:rtype: bool
"""
# 将给定数字除以2、3、5(顺序无所谓),直到无法整除。
# 若结果为1,则说明所有的因子都是2或3或5,给定数字是丑数。
# 否则,给定数字不是丑数。
if num <= 0:
return False
for i in [2, 3, 5]:
while num % i... |
f2abf358e63c8ddcf82325a579b3d251fb1bd187 | claudiodacruz/listasAPE | /Lista 01/Lista1_07.py | 286 | 3.796875 | 4 | '''
7. Escreva um programa para calcular e exibir a média ponderada de 2 notas dadas. Sabe-se que
nota1 possui peso 6 e nota2 possui peso 4
'''
N1 = float(input('Informe a Nota 1: '))
N2 = float(input('Informe a Nota 2: '))
M = (N1 * 6 + N2 * 4)/10
print('A média é =',M)
|
40ae1f5c165e81a9507df40e6dc49b41284e9475 | B-kelly28/CIS106-Brian-Kelly | /Assignment 3/Assignment 3-2.py | 237 | 4.4375 | 4 | # This program will convert between Celcius and Fahrenheit
print("Enter Celcius temperature:")
celcius = float(input())
fahrenheit = celcius * 9 / 5 + 32
print(str(celcius) + "° Celcius is " + str(fahrenheit) + "° Fahrenheit")
|
ec00c1d22d002b551c7eb8f79bc218c5f441f56c | Zhoujie-SONG/Uncuffed | /Uncuffed/helpers/JSONSerializable.py | 469 | 3.5625 | 4 | import json
from abc import ABC, abstractmethod
class JSONSerializable(ABC):
def to_json(self, **args) -> bytes:
return json.dumps(self.to_dict(), **args).encode('utf-8')
@classmethod
@abstractmethod
def from_json(cls, data):
pass
@abstractmethod
def to_dict(self) -> dict:
... |
343cf71179fadd6d79120138004a652326fac1a7 | brpadilha/exercicioscursoemvideo | /Desafios/Desafio 068.py | 1,399 | 3.8125 | 4 | #programa jogar par ou impar com o computador
#o jogo para quando o jogador perder
#mostrar o total de vitorias que ele conseguiu
from random import randint
verdade = False
c=0
while not verdade:
print ('--'*15)
print ('Vamos brincar de par ou impar?')
print ('--'*15)
comp=randint(0,10)
n... |
6b1eede0a69825c2e9d90042da1144ec47db404c | cielavenir/checkio | /incinerator/shortest-knight-path.py | 1,146 | 3.515625 | 4 | between=lambda a,x,b: (a)<=(x) and (x)<=(b)
x=[
[0,3,2,3,2,3,4,5],
[3,4,1,2,3,4,3,4],
[2,1,4,3,2,3,4,5],
[3,2,3,2,3,4,3,4],
[2,3,2,3,4,3,4,5],
[3,4,3,4,3,4,5,4],
[4,3,4,3,4,5,4,5],
[5,4,5,4,5,4,5,6]
]
def checkio(move):
a=ord(move[0])-ord('a')
b=ord(move[3])-ord('a')
c=ord(move[1])-ord('1')
d=ord(move[4])-o... |
5a319e771cfc80aa47e4882e09991755cb91a67f | dbmi-pitt/DIKB-Micropublication | /scripts/mp-scripts/Bio/Mindy/SimpleSeqRecord.py | 5,803 | 3.84375 | 4 | """Index a file based on information in a SeqRecord object.
This indexer tries to make it simple to index a file of records (ie. like
a GenBank file full of entries) so that individual records can be
readily retrieved.
The indexing in this file takes place by converting the elements in the
file into SeqRecord object... |
39fbb698934e98118393546e977253052dce022a | VannucciS/python_from_scratch_waterloo | /exercise_11.6.5.py | 1,558 | 4.4375 | 4 | '''
Instructions
Finally, add a method is_colour such that circ_1.is_colour(col) is True if the colour of circ_1 is col and False otherwise.
'''
class Circle:
"""Circle radius, x and y coordinates, colour
Public methods:
__init__: initializes a new object
Attributes:
radius: int o... |
e84fa62e7cadbf19f0e1531fa52982af178c1636 | lurichaowo/Jason_Chen_CS127_Assignments | /02/165097_front_times.py | 213 | 3.625 | 4 | def front_times(str, n):
front = str[0:3]
i = n
string = ''
#string = i * front
if len(str) == 0:
return string
else :
while i > 0 :
string = string + front
i = i -1
return string
|
df2fbeb99a6bd2e8fbc7f6204f411c439035fade | gencelo/PythonEgitimi | /h3_1.py | 171 | 3.546875 | 4 | # -*- coding: cp1254 -*-
liste = ["cemil", "mustafa", "ibrahim"]
for eleman in liste:
print eleman
for sayi in range(100):
print sayi**2
print "program bitti"
|
3a808cf913a59c2752f506e89e14131ab5d8417e | erikliu0801/leetcode | /python3/solved/P645. Set Mismatch.py | 2,424 | 4.03125 | 4 | # ToDo:
"""
645. Set Mismatch
Easy
The set S originally contains numbers from 1 to n. But unfortunately, due to the data error, one of the numbers in the set got duplicated to another number in the set, which results in repetition of one number and loss of another number.
Given an array nums representing the data st... |
bd5d7b900d3cf6405633ca60a3d9a5a79eca8055 | JRodriguez9510/holbertonschool-higher_level_programming-2 | /0x0B-python-input_output/0-read_file.py | 218 | 3.765625 | 4 | #!/usr/bin/python3
""" Function to read a file """
def read_file(filename=""):
""" Function to print file content on the stdout """
with open(filename, encoding="utf-8") as f:
print(f.read(), end="")
|
3dbe12b8a5d63bea1c4bfeb96b5e6bd0ef03b331 | childxr/lintleetcode | /TwoSumGreaterThanTarget/solution.py | 555 | 3.59375 | 4 | class Solution:
"""
@param nums: an array of integer
@param target: An integer
@return: an integer
"""
def twoSum2(self, nums, target):
# write your code here
if not nums or len(nums) < 2:
return 0
nums.sort()
cnt = 0
i, j = 0, len(nums) - 1
... |
11f077b166e5bc26f0484817a4597d90bf0b9578 | rayvace/tictactoe | /board/test.py | 4,119 | 3.875 | 4 | from board import Board
import unittest
class TestBoard(unittest.TestCase):
"""
1 | 2 | 3
----------
4 | 5 | 6
----------
7 | 8 | 9
"""
def setUp(self):
self.board = Board()
def test_add_mark(self):
#position must be a dict
position = None
self... |
997e9f3ff568b5ef1e635bdeb27a88f376a22fae | iistrate/Parser | /Main.py | 591 | 3.90625 | 4 | #
## Parses and validates text
#
from Parser import *
import os
def main():
running = True
while(running):
try:
path = input("Howdy Mr. J, please enter filename: ")
file = open(path, 'r')
except:
print("{} is an invalid filename!".format(path))
els... |
d8325a2d9e1214a72880b37b023d4af1a8d88469 | pandeesh/CodeFights | /Challenges/find_and_replace.py | 556 | 4.28125 | 4 | #!/usr/bin/env python
"""
ind all occurrences of the substring in the given string and replace them with another given string...
just for fun :)
Example:
findAndReplace("I love Codefights", "I", "We") = "We love Codefights"
[input] string originalString
The original string.
[input] string stringToFind
A string to ... |
326d2130712fefd254c6628bba3a0bd226350dec | Dinesh94Singh/PythonArchivedSolutions | /Concepts/Backtracking/131.Palindrome_Partitioning.py | 1,162 | 3.578125 | 4 | def partition(s):
res = []
dfs(s, [], res)
return res
def dfs(s, path, res):
if not s:
res.append(path[:]) # creates a new list if you do :
return # backtracking
for i in range(1, len(s) + 1):
# we are not expanding around center, rather a, aa, aab, aaba, aabaa.
i... |
58fca85f4908fd630d10cc76731e9f5ad95a8e2a | nshattuck20/Data_Structures_Algorithms1 | /ch11/sortingPractice.py | 1,883 | 4.21875 | 4 | '''
This is a simple program to practice:
1. Selection sort
2. Linear Search
3. Binary Search
'''
def selection_sort(numbers):
for i in range(len(numbers)):
#Find index of the smallest element
index_smallest = i
for j in range(i + 1, len(numbers)):
if numbers[j] < numbers[inde... |
7db35b395426db494a642fb2ec1604577bb988df | Youngj7449/cti110 | /M3T1_AreasOfRectangles_Young.py | 656 | 4.28125 | 4 | # Calculate the area of two rectangles and determine which one is greater
#6/14/2017
#CTI-110 M3T1 - Areas of Rectangles
#Jessica Young
#
#
length1 = int(input('Enter the length of rectangle 1: '))
width1 = int(input('Enter the width of rectangle 1: '))
length2 = int(input('Enter the length of rectangle 2... |
346ed26be4da241fb9fc093f3d07ed31e4ea56eb | 1000monkeys/probable-invention | /8/8-2.py | 154 | 3.625 | 4 | def favorite_book(book):
print("Your favorite book is " + book)
if __name__ == "__main__":
favorite_book(input("What is your favorite book? "))
|
ad93f96071d4096ed1d24f79209328ab5aae1c76 | lakshaymehra/fine-grained-sentiment-analysis | /visualize_results.py | 3,269 | 3.75 | 4 | import pandas as pd
import matplotlib.pyplot as plt
from wordcloud import WordCloud, STOPWORDS
import seaborn as sn
from sklearn.metrics import f1_score, accuracy_score, confusion_matrix
import argparse
def generate_wordcloud(df):
''' Create a wordcloud using Customer Reviews to see most commonly used words'''
... |
48584d00c67d06fe3c8105a192156f818cfce7d6 | AmitBaanerjee/Data-Structures-Algo-Practise | /hackerrank/reverse_array.py | 678 | 4.25 | 4 | #REVERSE ARRAY IN ORDER
# Given an array,A , of N integers, print each element in reverse order as a single line of space-separated integers.
#!/bin/python3
import math
import os
import random
import re
import sys
# Complete the reverseArray function below.
def reverseArray(a):
length=len(a)-1
for i in range(l... |
1897113f6ca4f4bd7202bf39fac2b490033128ef | jhiltonsantos/ADS-Algoritmos-IFPI | /Atividade_Fabio_06_STRING/fabio06_13_nome_em_biografia.py | 698 | 3.65625 | 4 | from tools_string import transforma_palavra_em_maiuscula, ultimo_nome
def main():
nome_completo = input('Digite o nome completo: ')
nome_completo = transforma_palavra_em_maiuscula(nome_completo)
ultimo = ultimo_nome(nome_completo)
primeiro, segundo = iniciais(nome_completo)
print... |
17dd5c33da3455607319348d8f99af4a7fdbabea | MU-Enigma/Hacktoberfest_2020 | /Problems/Problem_3/Divyesh_Problem_3.py | 225 | 4 | 4 | print("Input 3 numbers")
a = int(input())
b = int(input())
c = int(input())
A = a*a
B = b*b
C = c*c
if A == B+C:
print(a, b, c)
elif B == A+C:
print(b, a, c)
elif C == A+B:
print(c, a, b)
else:
print("NOPE!")
|
7119653c6364a42f53808a376192d09e9c5e9e93 | MichelleZ/leetcode | /algorithms/python/customSortString/customSortString.py | 278 | 3.5625 | 4 | #! /usr/bin/env python3
# -*- coding: utf-8 -*-
# Source: https://leetcode.com/problems/custom-sort-string/
# Author: Miao Zhang
# Date: 2021-03-11
class Solution:
def customSortString(self, S: str, T: str) -> str:
return "".join(sorted(T, key=lambda x: S.find(x)))
|
9711923c76c4b2e9938f0c2b09894e36558d1be2 | effectivemadness/ct_exercise | /가장 큰 수/solution.py | 892 | 3.859375 | 4 | # import itertools
# def solution(numbers):
# answer = ''
# str_list = itertools.permutations(numbers, len(numbers))
# number_list = []
# print(str_list)
# for item in str_list:
# tmp_str = ""
# for num_str in item:
# tmp_str = tmp_str + str(num_str)
# number_list... |
e159a36468a7b9cd51ced91d3aca51f9e0167885 | Schnei1811/PythonScripts | /Practice/Contacts Problem.py | 1,675 | 3.8125 | 4 | # Write a program that allows you to add names and tell you after you enter
# a string, how many contacts start with that string
def binarysearch(contactlist, val, count):
first = 0
last = len(contactlist) - 1
while first <= last:
mid = (first + last) // 2
if contactlist[mid][:len(val)... |
3844e9a7b08b6cd10fc9ac9b05141766c821a6ec | allyemmett/python_warmups | /day3_warmups.py | 739 | 4.3125 | 4 | # Write a hello world program and run it in python
message = "Hello world"
print(message) # or just print("hello world") with string
# Write a program that asks for a your name and prints hello, <your name>
name = input("What is your name: ")
print(f"Hello, {name}")
# Write a function that checks whether a numb... |
3143b4f35a0a5fab614c0c2131d4f0bf9f7133a1 | tharunnayak14/python | /ch7_files.py | 842 | 3.625 | 4 | # opening a file
# handle = open(filename,mode)
# f hand = open('m.txt','r')
xfile = open('m.txt')
for c in xfile:
print(c)
print("***********************************")
# counting lines
h = open('m.txt')
count = 0
for l in h:
count = count + 1
print('Line count:-', count)
print("***************... |
a8593605ba58824fa65d4d8dd11eae23797d58aa | darongliu/Input_Method | /demo/code/input.py | 3,383 | 3.734375 | 4 | # coding=UTF-8
import cmd
import math
from word_generate import possible_generate
def print_possible_word(all_possible_word):
num = len(all_possible_word)
for count in range(num) :
if (count % 10) == 0 :
print
print "%3d" % count ,
print all_possible_word[count],
... |
29f1704e3c78d3bde1cdf38815a9938feff60a01 | Imsid64/Siddharth | /rps.py | 318 | 4.15625 | 4 | #!/usr/bin/python3
import random
player = input("Enter your choice (rock/paper/scissor): ");
player =player.lower();
while (player != "rock and player != "paper" and player != "scissors"):
print(player);
player = input("That choice is not valid. Enter your choice (rock/paper/scissors): ");
player = player.lower(); |
b94576909d3ec3b897ca5eced31695598fb0dd58 | Hanlen520/Leetcode-4 | /src/117. 填充每个节点的下一个右侧节点指针 II.py | 1,410 | 4.125 | 4 | """
给定一个二叉树
struct Node {
int val;
Node *left;
Node *right;
Node *next;
}
填充它的每个 next 指针,让这个指针指向其下一个右侧节点。如果找不到下一个右侧节点,则将 next 指针设置为 NULL。
初始状态下,所有 next 指针都被设置为 NULL。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/populating-next-right-pointers-in-each-node-ii
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
"""
# 区别... |
f1d9e8140f0a2440ab9b614c01f55fe09e456c8e | ava6969/CS101 | /AndyJohnson/AndyLoops.py | 1,034 | 3.859375 | 4 | # i = 0
# while i < 5:
# print(i)
# i += 1
# for i in range(0, 5, 1):
# print(i)
def buy_game(game_price, game_name):
andy_money = int(input('how much money do you have: '))
diff = 0
while andy_money < game_price:
print('you dont have enough money, try again')
andy_money = int... |
babf8c3dd697855e07a7705f823c89751b558534 | richardbradshaw/Nashville_Weather | /ObservedWeather3Day.py | 3,093 | 3.53125 | 4 | #!/usr/bin/env python
# coding: utf-8
# In[1]:
import pandas as pd
import requests
# In[2]:
# get the data from the url, then parse it as a DataFrame
url = 'https://w1.weather.gov/data/obhistory/KBNA.html'
r = requests.get(url)
df_list = pd.read_html(r.text) # this parses all the tables in webpages to a list
dat... |
4cc82d03b0d54bb327b8819e29bab88aebacbcd5 | vanessa9910/Metodos | /Kata7.py | 446 | 4.3125 | 4 | #Create a function that takes an integer and returns the factorial of that integer.
#That is, the integer multiplied by all positive lower integers.
def factorial(num):
if (num ==1):
return 1;
else:
return num * factorial(num-1)
#Take a list of integers (positive or negative or both) and return the sum of the ab... |
66191e7f8e70a93f950d0e16e43817a0b7495c5b | nicobrubaker/modernArt | /modernArt.py | 4,623 | 3.5 | 4 | # By Nico Brubaker, applying 9th grade
from tkinter import *
from webbrowser import open_new
from random import randint, choice
from PIL import Image, ImageDraw
from os import remove
root = Tk()
root.wm_title("Mondrian Generator")
runAgain = Button(root, text="Generate Another!")
runAgain.pack()
save = Button(root... |
0a611cdca203788efad5080d5198a612965898de | Albertkwek/Fakathon | /html_to_factors.py | 6,639 | 3.53125 | 4 | def html_to_factors_general(url):
"""
Given a general website, this function returns a dictionary which the links on the website, the headline,
the body and the url.
"""
import requests
from bs4 import BeautifulSoup
response = requests.get(url)
if response.status_code == 200:
... |
ee87a11e478ad31d52cf395adb17360af8eb6a52 | Michael-png/olympiad-python-lvl-3 | /Python Homework/Homework 6 g).py | 260 | 4.03125 | 4 | Number = 0
x = 0
while x > 6: #this while loop looks like it never runs
x = x + 1
SomeKindOfInput = int(input("Enter a number here: "))
OddNumbers = SomeKindOfInput % 2
if OddNumbers == 1:
Number = Number + OddNumbers
print(Number)
|
8c6f2d8ed077e74b798ac7d6c42927834183267b | syurskyi/Algorithms_and_Data_Structure | /Python Data Structures and Algorithms/src/13. Graphs/5.2 Breadth-First Search.py | 1,897 | 3.546875 | 4 | from queuelinked import LinkedQueue
import numpy as np
class Graph:
def __init__(self, vertices):
self._adjMat = np.zeros((vertices, vertices))
self._vertices = vertices
def insert_edge(self, u, v, w=1):
self._adjMat[u][v] = w
def delete_edge(self, u, v):
self._adjMat[u][... |
45afbb7aeff958f9018733dece69b358781b60a5 | cxu60-zz/LeetCodeInPython | /subsets.py | 1,328 | 3.6875 | 4 | #!/usr/bin/env python
# encoding: utf-8
"""
subsets.py
Created by Shengwei on 2014-07-20.
"""
# https://oj.leetcode.com/problems/subsets/
# tags: easy / medium, numbers, set, combination, dfs
"""
Given a set of distinct integers, S, return all possible subsets.
Note:
Elements in a subset must be in non-descending o... |
88343cf1da3d149ca82343604c83cd3009b59aff | ntcho/CAU2019 | /Pre-term/Computational Thinking and Problem Solving/Lecture 3/prog1.py | 1,427 | 4.28125 | 4 | # 2019-01-31
# Quadratic equation example
from math import sqrt
print("Enter variables of your equation (ax^2 + bx + c = 0)")
a = float(input("a = "))
if a == 0:
print("Equation is not quadratic")
else:
b = float(input("b = "))
c = float(input("c = "))
# variable for checking if x exists
equati... |
6c63a54f527742a31a5d254565f2672a66dbc0e7 | JimChr-R4GN4R/angstromCTF-Writeups | /2019/Crypto/Half and Half (50 points)/two_letters_finder.py | 3,081 | 3.734375 | 4 | # So from the first script we are here:
# ciphertext is = \x15\x02\x07\x12\x1e\x100\x01\t\n\x01"
# we know these: a c t f { .. . . . . _
# unkown_letters: t a s t e .. . . . . }
# So now the only thing we know is the hex result...
# We see in unkown_letters that there is the word "tas... |
aef95277237ca10d3c62b9cf3162ff3efaa37bc6 | nickciaravella/leetcode | /215_Kth_Largest_Element_In_An_Array.py | 447 | 3.53125 | 4 | # https://leetcode.com/problems/kth-largest-element-in-an-array
# Medium
import heapq
class Solution:
def findKthLargest(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: int
"""
max_heap = list(map(lambda x: -1*x, nums))
heapq.heapify(max_heap... |
d9edc9627ccb1de30e2bfc4097c4a6ebc1ecaa05 | FrankAkumbissah/intro_to_python | /calculate.py | 1,330 | 4.03125 | 4 | def calculate():
ask = input("What do you want to do?:\n ADD \t\t\t SUBTRACT \n MULTIPLY \t\t\t DIVIDE\n")
if (ask == "ADD"):
print(add())
elif (ask == "SUBTRACT"):
print(subtract())
elif (ask == "MULTIPLY"):
print(multiply())
elif (ask == "DIVIDE"):
... |
0f05e2e5062d8b8a156a6d4f241be56a13113951 | xjtushare/learnPython2020 | /basic_class_03_Error/Solution_03_TypeError.py | 2,211 | 4.40625 | 4 | # !/usr/bin/env python
# -*- coding:utf-8 -*-
"""
TypeError
例1:在 for 循环语句中忘记调用 len()
导致TypeError: 'list' object cannot be interpreted as an integer
通常你想要通过索引来迭代一个 list 或者 string 的元素,这需要调用 range() 函数。
要记得返回 len 值而不是返回这个列表
"""
aa = ['cmbc','libai','chinese']
'''
错误示范
'''
# for i in range(aa):
# print(aa[i])
''... |
9b11ac786620863cf9c4a271a30bf3c2faf82104 | ferran9908/Algorithms---Stanford | /Graph Search, Shortest Paths and Data Structures/Graph Search/bfs_connected_components.py | 967 | 3.78125 | 4 | def read_graph(filename):
with open(filename,'r') as file:
lines = file.readlines()
for i in range(len(lines)):
lines[i] = lines[i].strip()
adjacency_list = {}
for line in lines:
line = list(map(int,line.split()))
adjacency_list[line[0]] = line[1:]
retu... |
b910dffeaa632c267d07467c0ca36c046d0d5790 | amanuelggy/Python---checkerboard-challenge | /String and List Assignment/string_List_assignment.py | 927 | 3.8125 | 4 | words = "It's thanksgiving day. It's my birthday,too!"
print words.find('d')
print words[18:21]
m = 'month'
print words[:18] + m + words[21:]
#another way of doing this will be
print words.find('day')
words = words.replace('day', 'month')
print words
#Printing Min & Max
x = [2,54,-2,7,12,98]
minV = min(x)
maxV = max(x... |
d14e3b7cd7ff62fdbc3cc59ed177271e82ee4c17 | Ebrahim94/Data_structures | /Arrays and Linked List/2_check_strings_anagram.py | 452 | 4.21875 | 4 | #goal is to write a function to check if two strings are anagrams of one another
#the function should take in two inputs of type String and output a Boolean
def anagram(string1, string2):
string1 = string1.replace(" ", "").lower()
string2 = string2.replace(" ", "").lower()
if sorted(string1) == sorted(st... |
bae39fcca485917faec4df3a8316c7b7479694de | Ghostant/basic-python-selenium-test | /src/test2.py | 584 | 3.921875 | 4 | name = "Yevhen"
height = "197"
weight = "72"
married = False
print(name)
print(height + height)
print("My name is " + name)
print(name + " is " + str(height) + " cm and " + str(weight) + " kg")
print("name is {} and height {}".format(name, height))
a = 4
b = 6.5
c = "2.5"
print(a + b)
age = 12
if (age < 10):
... |
41b0af3a67fcf7e28128c07b398560482cb3a4fd | zengx-git/teachingpython | /20201008list.py | 374 | 3.859375 | 4 | #问题引入,要求把输入的所有信息记录下来,供后面其它地方使用
import os
import time
while True:
strInput = input("请输入内容:")
print(strInput)
if strInput.upper() == "Q":
print("输入结束")
break;
#怎么把输入的内容找出来呢???
print("????")
# print(listStore)
time.sleep(100)
|
d42cc6d91494260c8ae3d0f9b22e9d4451b6bae1 | SamuelJadzak/UNITTESTINGCLASS | /test_Calculator.py | 578 | 3.53125 | 4 | import unittest
from Calculator import calculator
class testcase1(unittest.TestCase):
def test_additioncheck(self):
result = calculator.add(5,5)
self.assertEqual(result, 10)
def test_subtractioncheck(self):
result = calculator.subtract(10,5)
self.assertEqual(result, 5)
def t... |
b71f395bb4a7c45e6ad603ccc9cc58f4a6967b0d | shuiqukeyou/CodeExercise | /python/Data-structure-408/Sorting.py | 8,348 | 3.546875 | 4 | import random
import Time_count
from DataStructureClass import LinkL
# 无标记冒泡
@ Time_count.timecount
def bubble_sort1(l):
i = 0
while i < len(l) - 1:
j = len(l) - 1
while j > i:
if l[j - 1] > l[j]:
l[j], l[j - 1] = l[j - 1], l[j]
j = j - 1
i = i ... |
7721f1f89ce35c36faf2b6ff0b0d8ad5b11f293e | mmanfrin/cenapad_py | /aula1/task1.py | 407 | 3.5625 | 4 | #Exercício 1: calcule a média dos numeros ímpares até 100 usando slices, a função len e a função sum
n100 = list(range(0,101))
print(f'\nListagem 0-100: {n100}')
impar = n100[1::2]
print(f'\nListagem dos números ímpares: {impar}')
imparTotal = sum(impar)
print(f'\nSomatória dos números ímpares: {imparTotal}')
media... |
701d5535220c4025d43a5d956c6643ba3f4a033a | daniel-reich/turbo-robot | /RejeSPe68ajYzzgXM_3.py | 1,248 | 4.21875 | 4 | """
Create a function that, when given a list of individual [finite-state
automaton](https://en.wikipedia.org/wiki/Finite-state_machine) instructions,
generates an FSA in the form described in [this
challenge](https://edabit.com/challenge/86CrsZ2rRMnCsDSza). Each instruction
will be a list of three elements: The fir... |
5023a71b1f0e1d5bf0dd0cfca26cebf25179657f | YorkFish/learning_notes | /Python3/MorvanZhou/Tkinter/Tkinter_12.py | 893 | 3.671875 | 4 | #!/usr/bin/env python3
# coding:utf-8
import tkinter as tk
window = tk.Tk() # 窗口 object
window.title("my window") # 标题
window.geometry("300x200") # 窗口大小
'''
# 1. pack()
tk.Label(window, text=1).pack(side="top")
tk.Label(window, text=1).pack(side="bottom")
tk.Label(window, text=1).pack(side=... |
ab1e33d40a99b68c8477af45ee64f5d31c4af2f9 | Wakwandou/youtube-videos | /greedy-programming/scheduling.py | 2,795 | 4.15625 | 4 | import random as random
def schedule_jobs(jobs, length):
'''
Returns a schedule that maximzes the payoff of the jobs available
given a list of jobs.
Jobs are in format of (job_number, deadline, payoff)
'''
schedule = []
# sorting based on payoff
jobs.sort(key = lambda job: job[2])
... |
778cc52561e37918842f493fd0d2200536d19969 | lucascalebe/cs50-psets | /PSET 6/cash.py/cash.py | 486 | 3.828125 | 4 | from cs50 import get_float
dollars = get_float("Change owed: ")
# get just positive numbers
while dollars <= 0:
dollars = get_float("Change owed: ")
count = 0;
#converting dollar to cents
cents = round(dollars * 100)
while cents > 0:
if cents >= 25:
cents -= 25
count += 1
elif cents >= ... |
aa82d0a09e08860e086659e643bbe5d4428645f3 | Stepess/machine_learning_basic_alg | /desicion_tree/main.py | 4,552 | 3.75 | 4 | from sklearn import *
import numpy as np
import operator
def unique_vals(rows, col):
"""Find the unique values for a column in a dataset."""
return set([row[col] for row in rows])
def class_counts(rows):
"""Counts the number of each type of example in a dataset."""
counts = {} # a dictionary of lab... |
35eb911412524d0cf1797cbd961d3a57a8443411 | lancelote/stepik_algorithms_1 | /src/module_4/continuous_backpack.py | 868 | 4.09375 | 4 | from typing import List
from typing import NamedTuple
class Thing(NamedTuple):
price: int
weight: int
@property
def unit_cost(self) -> float:
return self.price / self.weight
def max_value(capacity: int, data: List[Thing]) -> float:
total_value = 0.0
things = sorted(data, key=lambda ... |
2ba91c655ccf7a327fdb5a8d3fe6989cf12a6b2b | msarahan/chaco | /examples/tutorials/tutorial1.py | 2,251 | 4.09375 | 4 | """Tutorial 1. Creating a plot and saving it as an image to disk."""
import os
import sys
from scipy import arange, pi, sin
from chaco import api as chaco
# First, we create two arrays of data, x and y. 'x' will be a sequence of
# 100 points spanning the range -2pi to 2pi, and 'y' will be sin(x).
numpoints = 100
st... |
8d7d502d6d346fd31e638ac4222e4eecfc9eebda | Simochenko/PythonPracticalTasks | /2.1_data_output_and_input.py | 4,747 | 4.09375 | 4 | # print(5*5%3//2+7//2+1)
# a = "5"
# b = "7"
# s = b + a
# print(s)
# first = '5'
# second = 2
# print(first * second)
# a = int('2')
# b = '3'
# s = a*b
# print(s)
# a = int(input())
# b = int(input())
# c = int(input())
# s = (a + b + c)
# print(s)
'''n школьников делят k яблок поровну, неделящийся остаток остается в... |
13e5f162bbadb660f88861eb56d3fb8c342ee99c | nathanwisla/PythonScriptCollection | /School Projects/lab 3 (Strings and formatting)/simpleTriangle.py | 205 | 4.09375 | 4 | ##make a program that print's the user's name in a simple triangle.
name = input('What is your name? ')
for letterPosition in range(len(name)):
print(name[letterPosition] * (letterPosition+1))
|
6e10d9b482990da0e2f164bdbe0a82d6fd6898a8 | daniel-reich/ubiquitous-fiesta | /FLgJEC8SK2AJYLC6y_6.py | 245 | 3.5625 | 4 |
def possible_path(lst):
for cur,fut in zip(lst,lst[1:]):
if cur=='H' and fut in (1,3) or cur in (1,3) and fut=='H':
return False
if isinstance(cur,int) and isinstance(fut,int) and cur%2==fut%2:
return False
return True
|
bf01799067f611f23b08f1857adaaea890439315 | oisinm/MIS40750 | /Assignment_1.py | 5,933 | 4.03125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Mon Oct 05 22:23:29 2015
MIS40750: Python Programming, Databases, and Version Control Assignment
@author: Oisin Mangan
Student Number: 15201541
"""
import math
import sqlite3
# Function to calculate distance between two points in long lat format
# Takes in two sets of coordina... |
a9c22c2934e325d4c600b29f5e84a24dc68f4eaf | Woosiq92/Pythonworkspace | /8_set.py | 687 | 3.734375 | 4 | # 집합 ( set )
# 중복 안됨, 순서 없음
my_set = {1, 2, 3, 3, 3}
print(my_set) # 중복 허용 안함
java = {"유재석", "김태호", "양세형"}
python = set(["유재석", "박명수"])
# 교집합 ( java 와 python 을 모두 할수 있는 사람 )
print (java & python )
print(java.intersection(python))
# 합집합 (java or python 중 하나라도 할 수 있는 사람 )
print(java | python )
print(java.union(pyth... |
b0893edb265b30d041296b2a30839b157d5e143d | El-Bando/Python_Sheet | /Python_Sheet-master/code/Listen/Listen_sort.py | 250 | 3.546875 | 4 | def myfunc(e):
return len(e)
mylist = [4, 3, 5, 7, 3, 2]
strlist = ['BMW', 'Tesla', 'GM']
mylist.sort()
print('#1', mylist)
mylist.sort(reverse=True)
print('#2', mylist)
print('#3', mylist.count(2))
strlist.sort(key=myfunc)
print('#4', strlist) |
8e983eeca522c2f695016729e8e2a245de035ee9 | nikita-chudnovskiy/ProjectPyton | /00 Базовый курс/046 Генераторы списков Python/03 Двойные циклы.py | 358 | 3.71875 | 4 | a =[(i,j) for i in 'abc' for j in [1,2,3]]
print(a)
a =[i*j for i in [2,4,6,] for j in [2,4,6] ] # перемножим числа на числа и выведем если больше 10
print(a)
a =[i*j for i in [2,4,6,] for j in [2,4,6] if i*j>10 ] # перемножим числа на числа и выведем если больше 10
print(a)
|
9c7c1f3c9122a1bbb01750bc5861ead638937f79 | MihaChug/PRRIS | /MinMax/main.py | 1,280 | 3.5625 | 4 | # -*- coding: utf-8 -*-
inputText = open("input.txt")
data = inputText.read()
#создаем список из слов для удобства поиска
data = data.split(' ')
inputText.close
first = input("Input first word: ")
second = input("Input second word: ")
#определяем все вхождения первого и второго слова в исходном тексте
firstInputs = [i... |
15abd817e63cc5804a1dd0ccd6af90a0c6c7a7d7 | mateuscorreiamartins/Curso-de-Python | /PythonExercicios/ex020.py | 439 | 3.921875 | 4 | # O mesmo professor do desafio anterior quer sortear a ordem de
# apresentação de trabalhos dos alunos.
# Faça um programa que leia o nome dos quatro alunos e mostre
# a ordem sorteada.
import random
a1 = str(input('Nome do primeiro aluno: '))
a2 = str(input('Nome do segundo aluno: '))
a3 = str(input('Nome do tercei... |
c0c2372da98f75a5b57092ab467400da7be1eb4a | smithevan/python_test | /caesar_cipher_exercise.py | 883 | 4.1875 | 4 | #trying out a basic encryption algorithm (caesar cipher)
password = input("Save Password:")
letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l',
'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']
def encrypt(password):
encrypted_password = []
for char in range(l... |
0e90cc458b17358b1cc07b702f4c037b23c51f78 | kgerginov/dungeons-and-python | /src/treasures.py | 963 | 3.5 | 4 | from random import choice
from src.spell import Spell
from src.weapon import Weapon
class Treasure:
def __init__(self):
self.treasures = {
'health_potion': [10, 20, 30, 50, 100],
'mana_potion': [10, 20, 30, 50, 100],
'weapon': [
Weapon(name='S... |
e31b0176539564d29f6c9084fd8af752c2170e14 | Oscar-Oliveira/Python-3 | /18_Exercises/B_Complementary/Solutions/Ex18.py | 406 | 3.953125 | 4 | """
Exercise 18
"""
def pos_int():
value = input("Enter a positive integer: ")
try:
value = int(value)
if value < 0:
raise ValueError
except ValueError:
print(">>>Error: Value must be a positive integer")
return pos_int()
return value
def main... |
21a6e597c6e1454a6ac3eea2592f4bd757191f23 | tails1434/Atcoder | /ABC/169/C.py | 181 | 3.625 | 4 | import math
from decimal import Decimal
def main():
A, B = input().split()
ans = Decimal(A) * Decimal(B)
print(math.floor(ans))
if __name__ == "__main__":
main() |
bbde57885a890397ff221680947d859f9fed8f70 | ashcarino/MP3-Python | /Coefficients_Polynomial.py | 637 | 3.8125 | 4 | def f(x):
result = x**10+x+1
return result
def least_norm_error_vector(experimental_points,n):
error_array=[0]*n
for i in range(0,n):
error_array[i]=experimental_points[i][1] - f(experimental_points[i][0])
return error_array
n=int(input("Enter number of experimental points you ... |
6b792e2101e2aef906a55c45f2990f3b5d56147c | kostcher/algorithmsPython | /hw_7/task_2.py | 975 | 4.1875 | 4 | # Отсортируйте по возрастанию методом слияния одномерный вещественный массив,
# заданный случайными числами на промежутке [0; 50). Выведите на экран исходный и отсортированный массивы.
import random
def merge_sort(array):
length = len(array)
if length <= 1:
return array
middle = int(length / 2)... |
1276472d7459a91f997ca1730401ffd894b77604 | yuta346/Algorithms | /LeetCode/coinChange.py | 910 | 3.8125 | 4 | # You are given an integer array coins representing coins of different denominations
# and an integer amount representing a total amount of money.
# Return the fewest number of coins that you need to make up that amount.
# If that amount of money cannot be made up by any combination of the coins, return -1.
# You may... |
973a04455185e799eabea33fdc4284198bfb8fb8 | freshpie/python | /HelloPy/test/exception.py | 932 | 3.53125 | 4 | import sys
import traceback
class NegativeDivisionError(Exception):
def __init__(self,value):
self.value = value
def foo(x):
assert type(x) == int, ["타입 오루ㅠ","wfef"]
return x*10
try:
a=[1,2,3]
#print(a[6])
#raise NameError("rrr")
#raise NegativeDivisionError(4)
raise ZeroDivi... |
7e14d08778e3934af61d69fe71d3b686a8b7fbb3 | HermanObst/algoritmos-y-programacion-1 | /Guia/serie15/ej5.py | 208 | 3.515625 | 4 | def par(n):
if n == 1:
return False
else:
return not par(n - 1)
def impar(n):
if n == 1:
return True
else:
return not impar(n - 1)
print(par(9))
print(impar(9))
print(par(10))
print(impar(10)) |
4d391906ada53b2b742ec91cd3895813d28942c4 | MartiniBnu/DataScienceLearning | /python/exercises5.py | 576 | 4.15625 | 4 | number1 = 0
number2 = 0
try:
number1 = int(input("Number 1:"))
except:
print("Invalid input!")
try:
number2 = int(input("Number 2:"))
except:
print("Invalid input!")
try:
signal = input("Chose your signal [+,-,*,/]:")
except:
print("Invalid input!")
if signal == "+":
print("... |
b8e2d0c35b8d6f196c1eb9784545ec2557006bf2 | DanielEcheverry96/verificador-palindromos | /cola_doble.py | 853 | 3.75 | 4 | class ColaDoble:
def __init__(self):
self.items = []
def estaVacia(self):
return self.items == []
# Asumimos que el frente de la Cola Doble corresponde al final de la lista
def agregarFrente(self, item):
self.items.append(item)
# Asumimos que el final de la Cola Doble corr... |
ee3ff0b7fa8705a5b23dfc46747a4ea833bbc4df | pratikkarad/unipune-practicals | /ml/linear-reg.py | 673 | 3.59375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Fri Apr 19 11:34:52 2019
@author: percy
"""
import numpy as np
import pandas as pd
from sklearn.linear_model import LinearRegression
import matplotlib.pyplot as plt
df = pd.read_csv('hours.csv')
linear = LinearRegression()
linear.fit(df[['Hours']],df['Risk'])
#regression_line = ... |
cbf86538e8000c27cefa3fa8c48598c2377ae90a | ShikhaShrivastava/Python-core | /List/Copy of Nested List.py | 814 | 4.40625 | 4 | '''creating copy of Nested list'''
# shallow copy
print(" ")
print("Creating Copy Of Nested List")
print(" ")
print("1. Shallow Copy")
print(" ")
lst1 = [[1, 2], [3, 4]]
print(lst1)
print(id(lst1))
print(id(lst1[0]))
print("copied list=")
lst2 = lst1[:]
print(lst2)
print(id(lst2))
print(id(lst2[0]))
print("Appending=... |
d5454d6e1dd811740bf63b96504c7fde87420bac | dwagon/pydominion | /dominion/cards/Card_Forge.py | 2,358 | 3.59375 | 4 | #!/usr/bin/env python
import unittest
from dominion import Game, Card, Piles
import dominion.Card as Card
###############################################################################
class Card_Forge(Card.Card):
def __init__(self):
Card.Card.__init__(self)
self.cardtype = Card.CardType.ACTION
... |
486fc395fe1c1559bdeb10fc021b0a1767aa3feb | Jokertion/MOOC | /tempconvert_ii.py | 1,151 | 3.671875 | 4 | #温度转换 II
Temp = input()
if Temp[0] in ['C']:
F_Temp = eval(Temp[1:]) * 1.8 + 32
print ("F"+"{:.2f}".format(F_Temp))
elif Temp[0] in ['F']:
C_Temp =(eval(Temp[1:]) - 32 ) / 1.8
print ("C"+"{:.2f}".format(C_Temp))
"""
温度转换 II
描述
温度的刻画有两个不同体系:摄氏度(Celsius)和华氏度(Fabrenheit)。
请编写程序将用户输入华氏度转换为摄氏度,... |
88508a2d0ea65871b3131e6876ef552c7c5e3040 | niranjan-nagaraju/Development | /python/leetcode/3sum/3sum-1.py | 1,418 | 3.71875 | 4 | '''
https://leetcode.com/problems/3sum/
Return all unique triplets that add upto 0
a + b + c = 0
Given array nums = [-1, 0, 1, 2, -1, -4],
A solution set is:
[
[-1, 0, 1],
[-1, -1, 2]
]
'''
'''
Solution Outline:
1. Generate all pairs (a,b) and their sums, and store their indices in a lookup table
2. For each ... |
1e6c5c877ed43aacd7455257474f29c3ddb96f90 | pratikt2212/High-Speed-Networking-Labs | /Lab 1/DeleteFromCircle.py | 855 | 3.703125 | 4 | import sys
import os
import random
z = 0
while z != 1 :
n = int(raw_input("N is the numbers in the circle :"))
m = int(raw_input("M is the m^th index to be deleted :"))
k = int(raw_input("K are the numbers remaining in the circle after deletion :"))
count = 1
my = [0 for a in range(n)]
... |
8ade6a7931243445927895987c19275427dcafa1 | upaezreyes/chem160module8 | /pbc.py | 371 | 3.578125 | 4 | import numpy as np
def neighbors(arr,x,y,n):
arr = np.roll(np.roll(arr,shift=-x+n//2,axis=0),shift=-y+n//2,axis=1)
return arr[:n,:n]
a = np.arange(0,100).reshape(10,10) # creates an 10x10 array
print(a)
print(neighbors(a,0,0,3)) # creates a 3x3 array with values around position 0o
print(neighbors(a,0,0,5)) ... |
3c40cad59385550425405fe1326f23fd48f88ec1 | ram-jay07/Code-Overflow | /Second smallest element in list | 527 | 4 | 4 | def second_smallest(numbers):
if (len(numbers)<2):
return
if ((len(numbers)==2) and (numbers[0] == numbers[1]) ):
return
dup_items = set()
uniq_items = []
for x in numbers:
if x not in dup_items:
uniq_items.append(x)
dup_items.add(x)
uniq_items.sort()
return uniq_items[1]
... |
0bcfa7953130c6989ca06967cfe2cd4e08d72e0b | neadie/pands-problem-set | /datetime.py | 551 | 3.875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sun Feb 3 21:54:08 2019
@author: Sinead Frawley
Question 8
"""
import datetime
def getDateInWordFormat():
my_date = datetime.datetime.now()
dayOfTheWeek=my_date.strftime("%A")
monthOftheYear=my_date.strftime("%B")
dateOfMonth=my_date.strftime("%d")
year=my... |
8ee4393e5dfe28f1df5a5c208cfb45fdf0ec4681 | aernesto24/Python-el-practices | /Basic/Python-university/OOP/classes-extra.py | 1,032 | 4.34375 | 4 | """we will show that self is not necessary,m is a convention on C is called this so we are using this
Also we can name the parameter diff form the arguments, arguments are really created during this.name"""
class Person:
#IF we want to pass a tupple just put * plus the var name also * indicates that the v... |
7104da8ade40f1b4ff142ecd2c24705563eb8322 | LeanderSilur/Snippets | /bezier/distance_point_curve/bezier_distance_example.py | 8,044 | 3.53125 | 4 | import numpy as np
# Bezier Class representing a CUBIC bezier defined by four
# control points.
#
# at(t): gets a point on the curve at t
# distance2(pt) returns the closest distance^2 of
# pt and the curve
# closest(pt) returns the point on the curve
# which ... |
4601ce8beaa9fd2d19a87c76148d96cab37720b8 | vitorskt/ExerciciosPython | /ex7 funcao.py | 1,782 | 4.03125 | 4 | #Faça um programa que use a função valorPagamento para determinar o valor
#a ser pago por uma prestação de uma conta. O programa deverá solicitar
#ao usuário o valor da prestação e o número de dias em atraso e passar estes
#valores para a função valorPagamento, que calculará o valor a ser pago e
#devolverá este valor a... |
0368a554b0e59c7b2149bf3c7946b45cdac83cfc | zjmdyd/Web | /04_python/12_常用内建模块/01_datetime.py | 4,752 | 3.71875 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
# datetime是Python处理日期和时间的标准库。
from datetime import datetime
##
# 获取当前日期和时间
##
now = datetime.now()
print(now) # 2018-10-09 17:34:17.195987
print(type(now)) # <class 'datetime.datetime'>
# 注意到datetime是模块,datetime模块还包含一个datetime类,通过from datetime import datetime导入的才是d... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.